blob: c154364505f7398ca2bc99993e51b8d858ccd2ab [file] [log] [blame]
Douglas Gregor81b747b2009-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 McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000026#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000027#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000028#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000029#include <list>
30#include <map>
31#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000032
33using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000034using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000035
Douglas Gregor86d9a522009-09-21 16:56:56 +000036namespace {
37 /// \brief A container of code-completion results.
38 class ResultBuilder {
39 public:
40 /// \brief The type of a name-lookup filter, which can be provided to the
41 /// name-lookup routines to specify which declarations should be included in
42 /// the result set (when it returns true) and which declarations should be
43 /// filtered out (returns false).
44 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
45
John McCall0a2c5e22010-08-25 06:19:51 +000046 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000047
48 private:
49 /// \brief The actual results we have found.
50 std::vector<Result> Results;
51
52 /// \brief A record of all of the declarations we have found and placed
53 /// into the result set, used to ensure that no declaration ever gets into
54 /// the result set twice.
55 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
56
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000057 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
58
59 /// \brief An entry in the shadow map, which is optimized to store
60 /// a single (declaration, index) mapping (the common case) but
61 /// can also store a list of (declaration, index) mappings.
62 class ShadowMapEntry {
63 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
64
65 /// \brief Contains either the solitary NamedDecl * or a vector
66 /// of (declaration, index) pairs.
67 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
68
69 /// \brief When the entry contains a single declaration, this is
70 /// the index associated with that entry.
71 unsigned SingleDeclIndex;
72
73 public:
74 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
75
76 void Add(NamedDecl *ND, unsigned Index) {
77 if (DeclOrVector.isNull()) {
78 // 0 - > 1 elements: just set the single element information.
79 DeclOrVector = ND;
80 SingleDeclIndex = Index;
81 return;
82 }
83
84 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
85 // 1 -> 2 elements: create the vector of results and push in the
86 // existing declaration.
87 DeclIndexPairVector *Vec = new DeclIndexPairVector;
88 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
89 DeclOrVector = Vec;
90 }
91
92 // Add the new element to the end of the vector.
93 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
94 DeclIndexPair(ND, Index));
95 }
96
97 void Destroy() {
98 if (DeclIndexPairVector *Vec
99 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
100 delete Vec;
101 DeclOrVector = ((NamedDecl *)0);
102 }
103 }
104
105 // Iteration.
106 class iterator;
107 iterator begin() const;
108 iterator end() const;
109 };
110
Douglas Gregor86d9a522009-09-21 16:56:56 +0000111 /// \brief A mapping from declaration names to the declarations that have
112 /// this name within a particular scope and their index within the list of
113 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000114 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000115
116 /// \brief The semantic analysis object for which results are being
117 /// produced.
118 Sema &SemaRef;
119
120 /// \brief If non-NULL, a filter function used to remove any code-completion
121 /// results that are not desirable.
122 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000123
124 /// \brief Whether we should allow declarations as
125 /// nested-name-specifiers that would otherwise be filtered out.
126 bool AllowNestedNameSpecifiers;
127
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000128 /// \brief If set, the type that we would prefer our resulting value
129 /// declarations to have.
130 ///
131 /// Closely matching the preferred type gives a boost to a result's
132 /// priority.
133 CanQualType PreferredType;
134
Douglas Gregor86d9a522009-09-21 16:56:56 +0000135 /// \brief A list of shadow maps, which is used to model name hiding at
136 /// different levels of, e.g., the inheritance hierarchy.
137 std::list<ShadowMap> ShadowMaps;
138
Douglas Gregor3cdee122010-08-26 16:36:48 +0000139 /// \brief If we're potentially referring to a C++ member function, the set
140 /// of qualifiers applied to the object type.
141 Qualifiers ObjectTypeQualifiers;
142
143 /// \brief Whether the \p ObjectTypeQualifiers field is active.
144 bool HasObjectTypeQualifiers;
145
Douglas Gregor265f7492010-08-27 15:29:55 +0000146 /// \brief The selector that we prefer.
147 Selector PreferredSelector;
148
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000149 void AdjustResultPriorityForPreferredType(Result &R);
150
Douglas Gregor86d9a522009-09-21 16:56:56 +0000151 public:
152 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor3cdee122010-08-26 16:36:48 +0000153 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
154 HasObjectTypeQualifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000155
Douglas Gregord8e8a582010-05-25 21:41:55 +0000156 /// \brief Whether we should include code patterns in the completion
157 /// results.
158 bool includeCodePatterns() const {
159 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000160 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000161 }
162
Douglas Gregor86d9a522009-09-21 16:56:56 +0000163 /// \brief Set the filter used for code-completion results.
164 void setFilter(LookupFilter Filter) {
165 this->Filter = Filter;
166 }
167
168 typedef std::vector<Result>::iterator iterator;
169 iterator begin() { return Results.begin(); }
170 iterator end() { return Results.end(); }
171
172 Result *data() { return Results.empty()? 0 : &Results.front(); }
173 unsigned size() const { return Results.size(); }
174 bool empty() const { return Results.empty(); }
175
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000176 /// \brief Specify the preferred type.
177 void setPreferredType(QualType T) {
178 PreferredType = SemaRef.Context.getCanonicalType(T);
179 }
180
Douglas Gregor3cdee122010-08-26 16:36:48 +0000181 /// \brief Set the cv-qualifiers on the object type, for us in filtering
182 /// calls to member functions.
183 ///
184 /// When there are qualifiers in this set, they will be used to filter
185 /// out member functions that aren't available (because there will be a
186 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
187 /// match.
188 void setObjectTypeQualifiers(Qualifiers Quals) {
189 ObjectTypeQualifiers = Quals;
190 HasObjectTypeQualifiers = true;
191 }
192
Douglas Gregor265f7492010-08-27 15:29:55 +0000193 /// \brief Set the preferred selector.
194 ///
195 /// When an Objective-C method declaration result is added, and that
196 /// method's selector matches this preferred selector, we give that method
197 /// a slight priority boost.
198 void setPreferredSelector(Selector Sel) {
199 PreferredSelector = Sel;
200 }
201
Douglas Gregor45bcd432010-01-14 03:21:49 +0000202 /// \brief Specify whether nested-name-specifiers are allowed.
203 void allowNestedNameSpecifiers(bool Allow = true) {
204 AllowNestedNameSpecifiers = Allow;
205 }
206
Douglas Gregore495b7f2010-01-14 00:20:49 +0000207 /// \brief Determine whether the given declaration is at all interesting
208 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000209 ///
210 /// \param ND the declaration that we are inspecting.
211 ///
212 /// \param AsNestedNameSpecifier will be set true if this declaration is
213 /// only interesting when it is a nested-name-specifier.
214 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000215
216 /// \brief Check whether the result is hidden by the Hiding declaration.
217 ///
218 /// \returns true if the result is hidden and cannot be found, false if
219 /// the hidden result could still be found. When false, \p R may be
220 /// modified to describe how the result can be found (e.g., via extra
221 /// qualification).
222 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
223 NamedDecl *Hiding);
224
Douglas Gregor86d9a522009-09-21 16:56:56 +0000225 /// \brief Add a new result to this result set (if it isn't already in one
226 /// of the shadow maps), or replace an existing result (for, e.g., a
227 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000228 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000229 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000230 ///
231 /// \param R the context in which this result will be named.
232 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000233
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000234 /// \brief Add a new result to this result set, where we already know
235 /// the hiding declation (if any).
236 ///
237 /// \param R the result to add (if it is unique).
238 ///
239 /// \param CurContext the context in which this result will be named.
240 ///
241 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000242 ///
243 /// \param InBaseClass whether the result was found in a base
244 /// class of the searched context.
245 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
246 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000247
Douglas Gregora4477812010-01-14 16:01:26 +0000248 /// \brief Add a new non-declaration result to this result set.
249 void AddResult(Result R);
250
Douglas Gregor86d9a522009-09-21 16:56:56 +0000251 /// \brief Enter into a new scope.
252 void EnterNewScope();
253
254 /// \brief Exit from the current scope.
255 void ExitScope();
256
Douglas Gregor55385fe2009-11-18 04:19:12 +0000257 /// \brief Ignore this declaration, if it is seen again.
258 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
259
Douglas Gregor86d9a522009-09-21 16:56:56 +0000260 /// \name Name lookup predicates
261 ///
262 /// These predicates can be passed to the name lookup functions to filter the
263 /// results of name lookup. All of the predicates have the same type, so that
264 ///
265 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000266 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000267 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000268 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000269 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 bool IsNestedNameSpecifier(NamedDecl *ND) const;
271 bool IsEnum(NamedDecl *ND) const;
272 bool IsClassOrStruct(NamedDecl *ND) const;
273 bool IsUnion(NamedDecl *ND) const;
274 bool IsNamespace(NamedDecl *ND) const;
275 bool IsNamespaceOrAlias(NamedDecl *ND) const;
276 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000277 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000278 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000279 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000280 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000281 //@}
282 };
283}
284
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000285class ResultBuilder::ShadowMapEntry::iterator {
286 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
287 unsigned SingleDeclIndex;
288
289public:
290 typedef DeclIndexPair value_type;
291 typedef value_type reference;
292 typedef std::ptrdiff_t difference_type;
293 typedef std::input_iterator_tag iterator_category;
294
295 class pointer {
296 DeclIndexPair Value;
297
298 public:
299 pointer(const DeclIndexPair &Value) : Value(Value) { }
300
301 const DeclIndexPair *operator->() const {
302 return &Value;
303 }
304 };
305
306 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
307
308 iterator(NamedDecl *SingleDecl, unsigned Index)
309 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
310
311 iterator(const DeclIndexPair *Iterator)
312 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
313
314 iterator &operator++() {
315 if (DeclOrIterator.is<NamedDecl *>()) {
316 DeclOrIterator = (NamedDecl *)0;
317 SingleDeclIndex = 0;
318 return *this;
319 }
320
321 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
322 ++I;
323 DeclOrIterator = I;
324 return *this;
325 }
326
327 iterator operator++(int) {
328 iterator tmp(*this);
329 ++(*this);
330 return tmp;
331 }
332
333 reference operator*() const {
334 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
335 return reference(ND, SingleDeclIndex);
336
Douglas Gregord490f952009-12-06 21:27:58 +0000337 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000338 }
339
340 pointer operator->() const {
341 return pointer(**this);
342 }
343
344 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000345 return X.DeclOrIterator.getOpaqueValue()
346 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000347 X.SingleDeclIndex == Y.SingleDeclIndex;
348 }
349
350 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000351 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000352 }
353};
354
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000355ResultBuilder::ShadowMapEntry::iterator
356ResultBuilder::ShadowMapEntry::begin() const {
357 if (DeclOrVector.isNull())
358 return iterator();
359
360 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
361 return iterator(ND, SingleDeclIndex);
362
363 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
364}
365
366ResultBuilder::ShadowMapEntry::iterator
367ResultBuilder::ShadowMapEntry::end() const {
368 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
369 return iterator();
370
371 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
372}
373
Douglas Gregor456c4a12009-09-21 20:12:40 +0000374/// \brief Compute the qualification required to get from the current context
375/// (\p CurContext) to the target context (\p TargetContext).
376///
377/// \param Context the AST context in which the qualification will be used.
378///
379/// \param CurContext the context where an entity is being named, which is
380/// typically based on the current scope.
381///
382/// \param TargetContext the context in which the named entity actually
383/// resides.
384///
385/// \returns a nested name specifier that refers into the target context, or
386/// NULL if no qualification is needed.
387static NestedNameSpecifier *
388getRequiredQualification(ASTContext &Context,
389 DeclContext *CurContext,
390 DeclContext *TargetContext) {
391 llvm::SmallVector<DeclContext *, 4> TargetParents;
392
393 for (DeclContext *CommonAncestor = TargetContext;
394 CommonAncestor && !CommonAncestor->Encloses(CurContext);
395 CommonAncestor = CommonAncestor->getLookupParent()) {
396 if (CommonAncestor->isTransparentContext() ||
397 CommonAncestor->isFunctionOrMethod())
398 continue;
399
400 TargetParents.push_back(CommonAncestor);
401 }
402
403 NestedNameSpecifier *Result = 0;
404 while (!TargetParents.empty()) {
405 DeclContext *Parent = TargetParents.back();
406 TargetParents.pop_back();
407
Douglas Gregorfb629412010-08-23 21:17:50 +0000408 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
409 if (!Namespace->getIdentifier())
410 continue;
411
Douglas Gregor456c4a12009-09-21 20:12:40 +0000412 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000413 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000414 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
415 Result = NestedNameSpecifier::Create(Context, Result,
416 false,
417 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000418 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000419 return Result;
420}
421
Douglas Gregor45bcd432010-01-14 03:21:49 +0000422bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
423 bool &AsNestedNameSpecifier) const {
424 AsNestedNameSpecifier = false;
425
Douglas Gregore495b7f2010-01-14 00:20:49 +0000426 ND = ND->getUnderlyingDecl();
427 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000428
429 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000430 if (!ND->getDeclName())
431 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000432
433 // Friend declarations and declarations introduced due to friends are never
434 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000435 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000436 return false;
437
Douglas Gregor76282942009-12-11 17:31:05 +0000438 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000439 if (isa<ClassTemplateSpecializationDecl>(ND) ||
440 isa<ClassTemplatePartialSpecializationDecl>(ND))
441 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000442
Douglas Gregor76282942009-12-11 17:31:05 +0000443 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000444 if (isa<UsingDecl>(ND))
445 return false;
446
447 // Some declarations have reserved names that we don't want to ever show.
448 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000449 // __va_list_tag is a freak of nature. Find it and skip it.
450 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000451 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000452
Douglas Gregorf52cede2009-10-09 22:16:47 +0000453 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000454 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000455 //
456 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000457 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000458 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000459 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000460 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
461 (ND->getLocation().isInvalid() ||
462 SemaRef.SourceMgr.isInSystemHeader(
463 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000464 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000465 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000467
Douglas Gregor86d9a522009-09-21 16:56:56 +0000468 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000469 if (isa<CXXConstructorDecl>(ND))
470 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000471
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000472 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
473 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
474 Filter != &ResultBuilder::IsNamespace &&
475 Filter != &ResultBuilder::IsNamespaceOrAlias))
476 AsNestedNameSpecifier = true;
477
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000479 if (Filter && !(this->*Filter)(ND)) {
480 // Check whether it is interesting as a nested-name-specifier.
481 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
482 IsNestedNameSpecifier(ND) &&
483 (Filter != &ResultBuilder::IsMember ||
484 (isa<CXXRecordDecl>(ND) &&
485 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
486 AsNestedNameSpecifier = true;
487 return true;
488 }
489
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000491 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000492 // ... then it must be interesting!
493 return true;
494}
495
Douglas Gregor6660d842010-01-14 00:41:07 +0000496bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
497 NamedDecl *Hiding) {
498 // In C, there is no way to refer to a hidden name.
499 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
500 // name if we introduce the tag type.
501 if (!SemaRef.getLangOptions().CPlusPlus)
502 return true;
503
504 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
505
506 // There is no way to qualify a name declared in a function or method.
507 if (HiddenCtx->isFunctionOrMethod())
508 return true;
509
510 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
511 return true;
512
513 // We can refer to the result with the appropriate qualification. Do it.
514 R.Hidden = true;
515 R.QualifierIsInformative = false;
516
517 if (!R.Qualifier)
518 R.Qualifier = getRequiredQualification(SemaRef.Context,
519 CurContext,
520 R.Declaration->getDeclContext());
521 return false;
522}
523
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000524/// \brief A simplified classification of types used to determine whether two
525/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000526SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000527 switch (T->getTypeClass()) {
528 case Type::Builtin:
529 switch (cast<BuiltinType>(T)->getKind()) {
530 case BuiltinType::Void:
531 return STC_Void;
532
533 case BuiltinType::NullPtr:
534 return STC_Pointer;
535
536 case BuiltinType::Overload:
537 case BuiltinType::Dependent:
538 case BuiltinType::UndeducedAuto:
539 return STC_Other;
540
541 case BuiltinType::ObjCId:
542 case BuiltinType::ObjCClass:
543 case BuiltinType::ObjCSel:
544 return STC_ObjectiveC;
545
546 default:
547 return STC_Arithmetic;
548 }
549 return STC_Other;
550
551 case Type::Complex:
552 return STC_Arithmetic;
553
554 case Type::Pointer:
555 return STC_Pointer;
556
557 case Type::BlockPointer:
558 return STC_Block;
559
560 case Type::LValueReference:
561 case Type::RValueReference:
562 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
563
564 case Type::ConstantArray:
565 case Type::IncompleteArray:
566 case Type::VariableArray:
567 case Type::DependentSizedArray:
568 return STC_Array;
569
570 case Type::DependentSizedExtVector:
571 case Type::Vector:
572 case Type::ExtVector:
573 return STC_Arithmetic;
574
575 case Type::FunctionProto:
576 case Type::FunctionNoProto:
577 return STC_Function;
578
579 case Type::Record:
580 return STC_Record;
581
582 case Type::Enum:
583 return STC_Arithmetic;
584
585 case Type::ObjCObject:
586 case Type::ObjCInterface:
587 case Type::ObjCObjectPointer:
588 return STC_ObjectiveC;
589
590 default:
591 return STC_Other;
592 }
593}
594
595/// \brief Get the type that a given expression will have if this declaration
596/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000597QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000598 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
599
600 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
601 return C.getTypeDeclType(Type);
602 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
603 return C.getObjCInterfaceType(Iface);
604
605 QualType T;
606 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000607 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000608 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000609 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000610 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000611 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000612 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
613 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
614 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
615 T = Property->getType();
616 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
617 T = Value->getType();
618 else
619 return QualType();
620
621 return T.getNonReferenceType();
622}
623
624void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
625 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
626 if (T.isNull())
627 return;
628
629 CanQualType TC = SemaRef.Context.getCanonicalType(T);
630 // Check for exactly-matching types (modulo qualifiers).
Douglas Gregoreb0d0142010-08-24 23:58:17 +0000631 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) {
632 if (PreferredType->isVoidType())
633 R.Priority += CCD_VoidMatch;
634 else
635 R.Priority /= CCF_ExactTypeMatch;
636 } // Check for nearly-matching types, based on classification of each.
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000637 else if ((getSimplifiedTypeClass(PreferredType)
638 == getSimplifiedTypeClass(TC)) &&
639 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
640 R.Priority /= CCF_SimilarTypeMatch;
641}
642
Douglas Gregore495b7f2010-01-14 00:20:49 +0000643void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
644 assert(!ShadowMaps.empty() && "Must enter into a results scope");
645
646 if (R.Kind != Result::RK_Declaration) {
647 // For non-declaration results, just add the result.
648 Results.push_back(R);
649 return;
650 }
651
652 // Look through using declarations.
653 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
654 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
655 return;
656 }
657
658 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
659 unsigned IDNS = CanonDecl->getIdentifierNamespace();
660
Douglas Gregor45bcd432010-01-14 03:21:49 +0000661 bool AsNestedNameSpecifier = false;
662 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000663 return;
664
Douglas Gregor86d9a522009-09-21 16:56:56 +0000665 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000666 ShadowMapEntry::iterator I, IEnd;
667 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
668 if (NamePos != SMap.end()) {
669 I = NamePos->second.begin();
670 IEnd = NamePos->second.end();
671 }
672
673 for (; I != IEnd; ++I) {
674 NamedDecl *ND = I->first;
675 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000676 if (ND->getCanonicalDecl() == CanonDecl) {
677 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000678 Results[Index].Declaration = R.Declaration;
679
Douglas Gregor86d9a522009-09-21 16:56:56 +0000680 // We're done.
681 return;
682 }
683 }
684
685 // This is a new declaration in this scope. However, check whether this
686 // declaration name is hidden by a similarly-named declaration in an outer
687 // scope.
688 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
689 --SMEnd;
690 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000691 ShadowMapEntry::iterator I, IEnd;
692 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
693 if (NamePos != SM->end()) {
694 I = NamePos->second.begin();
695 IEnd = NamePos->second.end();
696 }
697 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000698 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000699 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000700 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
701 Decl::IDNS_ObjCProtocol)))
702 continue;
703
704 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000705 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000706 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000707 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000708 continue;
709
710 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000711 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000712 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000713
714 break;
715 }
716 }
717
718 // Make sure that any given declaration only shows up in the result set once.
719 if (!AllDeclsFound.insert(CanonDecl))
720 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000721
722 // If this is an Objective-C method declaration whose selector matches our
723 // preferred selector, give it a priority boost.
724 if (!PreferredSelector.isNull())
725 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
726 if (PreferredSelector == Method->getSelector())
727 R.Priority += CCD_SelectorMatch;
728
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000729 // If the filter is for nested-name-specifiers, then this result starts a
730 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000731 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000732 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000733 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000734 } else if (!PreferredType.isNull())
735 AdjustResultPriorityForPreferredType(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000736
Douglas Gregor0563c262009-09-22 23:15:58 +0000737 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000738 if (R.QualifierIsInformative && !R.Qualifier &&
739 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000740 DeclContext *Ctx = R.Declaration->getDeclContext();
741 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
742 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
743 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
744 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
745 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
746 else
747 R.QualifierIsInformative = false;
748 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000749
Douglas Gregor86d9a522009-09-21 16:56:56 +0000750 // Insert this result into the set of results and into the current shadow
751 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000752 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000753 Results.push_back(R);
754}
755
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000756void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000757 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000758 if (R.Kind != Result::RK_Declaration) {
759 // For non-declaration results, just add the result.
760 Results.push_back(R);
761 return;
762 }
763
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000764 // Look through using declarations.
765 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
766 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
767 return;
768 }
769
Douglas Gregor45bcd432010-01-14 03:21:49 +0000770 bool AsNestedNameSpecifier = false;
771 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000772 return;
773
774 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
775 return;
776
777 // Make sure that any given declaration only shows up in the result set once.
778 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
779 return;
780
781 // If the filter is for nested-name-specifiers, then this result starts a
782 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000783 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000784 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000785 R.Priority = CCP_NestedNameSpecifier;
786 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000787 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
788 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
789 ->getLookupContext()))
790 R.QualifierIsInformative = true;
791
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000792 // If this result is supposed to have an informative qualifier, add one.
793 if (R.QualifierIsInformative && !R.Qualifier &&
794 !R.StartsNestedNameSpecifier) {
795 DeclContext *Ctx = R.Declaration->getDeclContext();
796 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
797 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
798 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
799 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000800 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000801 else
802 R.QualifierIsInformative = false;
803 }
804
Douglas Gregor12e13132010-05-26 22:00:08 +0000805 // Adjust the priority if this result comes from a base class.
806 if (InBaseClass)
807 R.Priority += CCD_InBaseClass;
808
Douglas Gregor265f7492010-08-27 15:29:55 +0000809 // If this is an Objective-C method declaration whose selector matches our
810 // preferred selector, give it a priority boost.
811 if (!PreferredSelector.isNull())
812 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
813 if (PreferredSelector == Method->getSelector())
814 R.Priority += CCD_SelectorMatch;
815
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000816 if (!PreferredType.isNull())
817 AdjustResultPriorityForPreferredType(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000818
Douglas Gregor3cdee122010-08-26 16:36:48 +0000819 if (HasObjectTypeQualifiers)
820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
821 if (Method->isInstance()) {
822 Qualifiers MethodQuals
823 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
824 if (ObjectTypeQualifiers == MethodQuals)
825 R.Priority += CCD_ObjectQualifierMatch;
826 else if (ObjectTypeQualifiers - MethodQuals) {
827 // The method cannot be invoked, because doing so would drop
828 // qualifiers.
829 return;
830 }
831 }
832
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000833 // Insert this result into the set of results.
834 Results.push_back(R);
835}
836
Douglas Gregora4477812010-01-14 16:01:26 +0000837void ResultBuilder::AddResult(Result R) {
838 assert(R.Kind != Result::RK_Declaration &&
839 "Declaration results need more context");
840 Results.push_back(R);
841}
842
Douglas Gregor86d9a522009-09-21 16:56:56 +0000843/// \brief Enter into a new scope.
844void ResultBuilder::EnterNewScope() {
845 ShadowMaps.push_back(ShadowMap());
846}
847
848/// \brief Exit from the current scope.
849void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000850 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
851 EEnd = ShadowMaps.back().end();
852 E != EEnd;
853 ++E)
854 E->second.Destroy();
855
Douglas Gregor86d9a522009-09-21 16:56:56 +0000856 ShadowMaps.pop_back();
857}
858
Douglas Gregor791215b2009-09-21 20:51:25 +0000859/// \brief Determines whether this given declaration will be found by
860/// ordinary name lookup.
861bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000862 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
863
Douglas Gregor791215b2009-09-21 20:51:25 +0000864 unsigned IDNS = Decl::IDNS_Ordinary;
865 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000866 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000867 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
868 return true;
869
Douglas Gregor791215b2009-09-21 20:51:25 +0000870 return ND->getIdentifierNamespace() & IDNS;
871}
872
Douglas Gregor01dfea02010-01-10 23:08:15 +0000873/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000874/// ordinary name lookup but is not a type name.
875bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
876 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
877 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
878 return false;
879
880 unsigned IDNS = Decl::IDNS_Ordinary;
881 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000882 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000883 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
884 return true;
885
886 return ND->getIdentifierNamespace() & IDNS;
887}
888
Douglas Gregorf9578432010-07-28 21:50:18 +0000889bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
890 if (!IsOrdinaryNonTypeName(ND))
891 return 0;
892
893 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
894 if (VD->getType()->isIntegralOrEnumerationType())
895 return true;
896
897 return false;
898}
899
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000900/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000901/// ordinary name lookup.
902bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000903 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
904
Douglas Gregor01dfea02010-01-10 23:08:15 +0000905 unsigned IDNS = Decl::IDNS_Ordinary;
906 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000907 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000908
909 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000910 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
911 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000912}
913
Douglas Gregor86d9a522009-09-21 16:56:56 +0000914/// \brief Determines whether the given declaration is suitable as the
915/// start of a C++ nested-name-specifier, e.g., a class or namespace.
916bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
917 // Allow us to find class templates, too.
918 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
919 ND = ClassTemplate->getTemplatedDecl();
920
921 return SemaRef.isAcceptableNestedNameSpecifier(ND);
922}
923
924/// \brief Determines whether the given declaration is an enumeration.
925bool ResultBuilder::IsEnum(NamedDecl *ND) const {
926 return isa<EnumDecl>(ND);
927}
928
929/// \brief Determines whether the given declaration is a class or struct.
930bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
931 // Allow us to find class templates, too.
932 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
933 ND = ClassTemplate->getTemplatedDecl();
934
935 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000936 return RD->getTagKind() == TTK_Class ||
937 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000938
939 return false;
940}
941
942/// \brief Determines whether the given declaration is a union.
943bool ResultBuilder::IsUnion(NamedDecl *ND) const {
944 // Allow us to find class templates, too.
945 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
946 ND = ClassTemplate->getTemplatedDecl();
947
948 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000949 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000950
951 return false;
952}
953
954/// \brief Determines whether the given declaration is a namespace.
955bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
956 return isa<NamespaceDecl>(ND);
957}
958
959/// \brief Determines whether the given declaration is a namespace or
960/// namespace alias.
961bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
962 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
963}
964
Douglas Gregor76282942009-12-11 17:31:05 +0000965/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +0000967 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
968 ND = Using->getTargetDecl();
969
970 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000971}
972
Douglas Gregor76282942009-12-11 17:31:05 +0000973/// \brief Determines which members of a class should be visible via
974/// "." or "->". Only value declarations, nested name specifiers, and
975/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000976bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000977 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
978 ND = Using->getTargetDecl();
979
Douglas Gregorce821962009-12-11 18:14:22 +0000980 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
981 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000982}
983
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000984static bool isObjCReceiverType(ASTContext &C, QualType T) {
985 T = C.getCanonicalType(T);
986 switch (T->getTypeClass()) {
987 case Type::ObjCObject:
988 case Type::ObjCInterface:
989 case Type::ObjCObjectPointer:
990 return true;
991
992 case Type::Builtin:
993 switch (cast<BuiltinType>(T)->getKind()) {
994 case BuiltinType::ObjCId:
995 case BuiltinType::ObjCClass:
996 case BuiltinType::ObjCSel:
997 return true;
998
999 default:
1000 break;
1001 }
1002 return false;
1003
1004 default:
1005 break;
1006 }
1007
1008 if (!C.getLangOptions().CPlusPlus)
1009 return false;
1010
1011 // FIXME: We could perform more analysis here to determine whether a
1012 // particular class type has any conversions to Objective-C types. For now,
1013 // just accept all class types.
1014 return T->isDependentType() || T->isRecordType();
1015}
1016
1017bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1018 QualType T = getDeclUsageType(SemaRef.Context, ND);
1019 if (T.isNull())
1020 return false;
1021
1022 T = SemaRef.Context.getBaseElementType(T);
1023 return isObjCReceiverType(SemaRef.Context, T);
1024}
1025
Douglas Gregorfb629412010-08-23 21:17:50 +00001026bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1027 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1028 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1029 return false;
1030
1031 QualType T = getDeclUsageType(SemaRef.Context, ND);
1032 if (T.isNull())
1033 return false;
1034
1035 T = SemaRef.Context.getBaseElementType(T);
1036 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1037 T->isObjCIdType() ||
1038 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1039}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001040
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001041/// \rief Determines whether the given declaration is an Objective-C
1042/// instance variable.
1043bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1044 return isa<ObjCIvarDecl>(ND);
1045}
1046
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001047namespace {
1048 /// \brief Visible declaration consumer that adds a code-completion result
1049 /// for each visible declaration.
1050 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1051 ResultBuilder &Results;
1052 DeclContext *CurContext;
1053
1054 public:
1055 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1056 : Results(Results), CurContext(CurContext) { }
1057
Douglas Gregor0cc84042010-01-14 15:47:35 +00001058 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1059 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001060 }
1061 };
1062}
1063
Douglas Gregor86d9a522009-09-21 16:56:56 +00001064/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001065static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001066 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001067 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001068 Results.AddResult(Result("short", CCP_Type));
1069 Results.AddResult(Result("long", CCP_Type));
1070 Results.AddResult(Result("signed", CCP_Type));
1071 Results.AddResult(Result("unsigned", CCP_Type));
1072 Results.AddResult(Result("void", CCP_Type));
1073 Results.AddResult(Result("char", CCP_Type));
1074 Results.AddResult(Result("int", CCP_Type));
1075 Results.AddResult(Result("float", CCP_Type));
1076 Results.AddResult(Result("double", CCP_Type));
1077 Results.AddResult(Result("enum", CCP_Type));
1078 Results.AddResult(Result("struct", CCP_Type));
1079 Results.AddResult(Result("union", CCP_Type));
1080 Results.AddResult(Result("const", CCP_Type));
1081 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001082
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083 if (LangOpts.C99) {
1084 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001085 Results.AddResult(Result("_Complex", CCP_Type));
1086 Results.AddResult(Result("_Imaginary", CCP_Type));
1087 Results.AddResult(Result("_Bool", CCP_Type));
1088 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001089 }
1090
1091 if (LangOpts.CPlusPlus) {
1092 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001093 Results.AddResult(Result("bool", CCP_Type));
1094 Results.AddResult(Result("class", CCP_Type));
1095 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001096
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001097 // typename qualified-id
1098 CodeCompletionString *Pattern = new CodeCompletionString;
1099 Pattern->AddTypedTextChunk("typename");
1100 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1101 Pattern->AddPlaceholderChunk("qualifier");
1102 Pattern->AddTextChunk("::");
1103 Pattern->AddPlaceholderChunk("name");
1104 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001105
Douglas Gregor86d9a522009-09-21 16:56:56 +00001106 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001107 Results.AddResult(Result("auto", CCP_Type));
1108 Results.AddResult(Result("char16_t", CCP_Type));
1109 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001110
1111 CodeCompletionString *Pattern = new CodeCompletionString;
1112 Pattern->AddTypedTextChunk("decltype");
1113 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1114 Pattern->AddPlaceholderChunk("expression");
1115 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1116 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001117 }
1118 }
1119
1120 // GNU extensions
1121 if (LangOpts.GNUMode) {
1122 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001123 // Results.AddResult(Result("_Decimal32"));
1124 // Results.AddResult(Result("_Decimal64"));
1125 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001126
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001127 CodeCompletionString *Pattern = new CodeCompletionString;
1128 Pattern->AddTypedTextChunk("typeof");
1129 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1130 Pattern->AddPlaceholderChunk("expression");
1131 Results.AddResult(Result(Pattern));
1132
1133 Pattern = new CodeCompletionString;
1134 Pattern->AddTypedTextChunk("typeof");
1135 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1136 Pattern->AddPlaceholderChunk("type");
1137 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1138 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001139 }
1140}
1141
John McCallf312b1e2010-08-26 23:41:50 +00001142static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001143 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001144 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001145 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001146 // Note: we don't suggest either "auto" or "register", because both
1147 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1148 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001149 Results.AddResult(Result("extern"));
1150 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001151}
1152
John McCallf312b1e2010-08-26 23:41:50 +00001153static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001154 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001155 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001156 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001157 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001158 case Sema::PCC_Class:
1159 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001160 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001161 Results.AddResult(Result("explicit"));
1162 Results.AddResult(Result("friend"));
1163 Results.AddResult(Result("mutable"));
1164 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001165 }
1166 // Fall through
1167
John McCallf312b1e2010-08-26 23:41:50 +00001168 case Sema::PCC_ObjCInterface:
1169 case Sema::PCC_ObjCImplementation:
1170 case Sema::PCC_Namespace:
1171 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001172 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001173 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001174 break;
1175
John McCallf312b1e2010-08-26 23:41:50 +00001176 case Sema::PCC_ObjCInstanceVariableList:
1177 case Sema::PCC_Expression:
1178 case Sema::PCC_Statement:
1179 case Sema::PCC_ForInit:
1180 case Sema::PCC_Condition:
1181 case Sema::PCC_RecoveryInFunction:
1182 case Sema::PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001183 break;
1184 }
1185}
1186
Douglas Gregorbca403c2010-01-13 23:51:12 +00001187static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1188static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1189static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001190 ResultBuilder &Results,
1191 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001192static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001193 ResultBuilder &Results,
1194 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001195static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001196 ResultBuilder &Results,
1197 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001198static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001199
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001200static void AddTypedefResult(ResultBuilder &Results) {
1201 CodeCompletionString *Pattern = new CodeCompletionString;
1202 Pattern->AddTypedTextChunk("typedef");
1203 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1204 Pattern->AddPlaceholderChunk("type");
1205 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1206 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001207 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001208}
1209
John McCallf312b1e2010-08-26 23:41:50 +00001210static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001211 const LangOptions &LangOpts) {
1212 if (LangOpts.CPlusPlus)
1213 return true;
1214
1215 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001216 case Sema::PCC_Namespace:
1217 case Sema::PCC_Class:
1218 case Sema::PCC_ObjCInstanceVariableList:
1219 case Sema::PCC_Template:
1220 case Sema::PCC_MemberTemplate:
1221 case Sema::PCC_Statement:
1222 case Sema::PCC_RecoveryInFunction:
1223 case Sema::PCC_Type:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001224 return true;
1225
John McCallf312b1e2010-08-26 23:41:50 +00001226 case Sema::PCC_ObjCInterface:
1227 case Sema::PCC_ObjCImplementation:
1228 case Sema::PCC_Expression:
1229 case Sema::PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001230 return false;
1231
John McCallf312b1e2010-08-26 23:41:50 +00001232 case Sema::PCC_ForInit:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001233 return LangOpts.ObjC1 || LangOpts.C99;
1234 }
1235
1236 return false;
1237}
1238
Douglas Gregor01dfea02010-01-10 23:08:15 +00001239/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001240static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001241 Scope *S,
1242 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001243 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001244 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001245 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001246 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001247 if (SemaRef.getLangOptions().CPlusPlus) {
1248 CodeCompletionString *Pattern = 0;
1249
1250 if (Results.includeCodePatterns()) {
1251 // namespace <identifier> { declarations }
1252 CodeCompletionString *Pattern = new CodeCompletionString;
1253 Pattern->AddTypedTextChunk("namespace");
1254 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1255 Pattern->AddPlaceholderChunk("identifier");
1256 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1257 Pattern->AddPlaceholderChunk("declarations");
1258 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1259 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1260 Results.AddResult(Result(Pattern));
1261 }
1262
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263 // namespace identifier = identifier ;
1264 Pattern = new CodeCompletionString;
1265 Pattern->AddTypedTextChunk("namespace");
1266 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001267 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001268 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001269 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001270 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001271
1272 // Using directives
1273 Pattern = new CodeCompletionString;
1274 Pattern->AddTypedTextChunk("using");
1275 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1276 Pattern->AddTextChunk("namespace");
1277 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1278 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001279 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280
1281 // asm(string-literal)
1282 Pattern = new CodeCompletionString;
1283 Pattern->AddTypedTextChunk("asm");
1284 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1285 Pattern->AddPlaceholderChunk("string-literal");
1286 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001287 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001288
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001289 if (Results.includeCodePatterns()) {
1290 // Explicit template instantiation
1291 Pattern = new CodeCompletionString;
1292 Pattern->AddTypedTextChunk("template");
1293 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1294 Pattern->AddPlaceholderChunk("declaration");
1295 Results.AddResult(Result(Pattern));
1296 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001297 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001298
1299 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001300 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001301
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001302 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001303 // Fall through
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001306 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 // Using declaration
1308 CodeCompletionString *Pattern = new CodeCompletionString;
1309 Pattern->AddTypedTextChunk("using");
1310 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001311 Pattern->AddPlaceholderChunk("qualifier");
1312 Pattern->AddTextChunk("::");
1313 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001314 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001315
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001316 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001317 if (SemaRef.CurContext->isDependentContext()) {
1318 Pattern = new CodeCompletionString;
1319 Pattern->AddTypedTextChunk("using");
1320 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1321 Pattern->AddTextChunk("typename");
1322 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001323 Pattern->AddPlaceholderChunk("qualifier");
1324 Pattern->AddTextChunk("::");
1325 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001326 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001327 }
1328
John McCallf312b1e2010-08-26 23:41:50 +00001329 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001330 AddTypedefResult(Results);
1331
Douglas Gregor01dfea02010-01-10 23:08:15 +00001332 // public:
1333 Pattern = new CodeCompletionString;
1334 Pattern->AddTypedTextChunk("public");
1335 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001336 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001337
1338 // protected:
1339 Pattern = new CodeCompletionString;
1340 Pattern->AddTypedTextChunk("protected");
1341 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001342 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001343
1344 // private:
1345 Pattern = new CodeCompletionString;
1346 Pattern->AddTypedTextChunk("private");
1347 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001348 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001349 }
1350 }
1351 // Fall through
1352
John McCallf312b1e2010-08-26 23:41:50 +00001353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001355 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001356 // template < parameters >
1357 CodeCompletionString *Pattern = new CodeCompletionString;
1358 Pattern->AddTypedTextChunk("template");
1359 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1360 Pattern->AddPlaceholderChunk("parameters");
1361 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001362 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001363 }
1364
Douglas Gregorbca403c2010-01-13 23:51:12 +00001365 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1366 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001367 break;
1368
John McCallf312b1e2010-08-26 23:41:50 +00001369 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001370 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1371 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1372 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001373 break;
1374
John McCallf312b1e2010-08-26 23:41:50 +00001375 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001376 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1377 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1378 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001379 break;
1380
John McCallf312b1e2010-08-26 23:41:50 +00001381 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001382 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001383 break;
1384
John McCallf312b1e2010-08-26 23:41:50 +00001385 case Sema::PCC_RecoveryInFunction:
1386 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001388
1389 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001390 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001391 Pattern = new CodeCompletionString;
1392 Pattern->AddTypedTextChunk("try");
1393 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Pattern->AddPlaceholderChunk("statements");
1395 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1397 Pattern->AddTextChunk("catch");
1398 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1399 Pattern->AddPlaceholderChunk("declaration");
1400 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1401 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1402 Pattern->AddPlaceholderChunk("statements");
1403 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1404 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001405 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001406 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001407 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001408 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001409
Douglas Gregord8e8a582010-05-25 21:41:55 +00001410 if (Results.includeCodePatterns()) {
1411 // if (condition) { statements }
1412 Pattern = new CodeCompletionString;
1413 Pattern->AddTypedTextChunk("if");
1414 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1415 if (SemaRef.getLangOptions().CPlusPlus)
1416 Pattern->AddPlaceholderChunk("condition");
1417 else
1418 Pattern->AddPlaceholderChunk("expression");
1419 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1420 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1421 Pattern->AddPlaceholderChunk("statements");
1422 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1423 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1424 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001425
Douglas Gregord8e8a582010-05-25 21:41:55 +00001426 // switch (condition) { }
1427 Pattern = new CodeCompletionString;
1428 Pattern->AddTypedTextChunk("switch");
1429 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1430 if (SemaRef.getLangOptions().CPlusPlus)
1431 Pattern->AddPlaceholderChunk("condition");
1432 else
1433 Pattern->AddPlaceholderChunk("expression");
1434 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1435 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1436 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1437 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1438 Results.AddResult(Result(Pattern));
1439 }
1440
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001442 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001443 // case expression:
1444 Pattern = new CodeCompletionString;
1445 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001446 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447 Pattern->AddPlaceholderChunk("expression");
1448 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001449 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001450
1451 // default:
1452 Pattern = new CodeCompletionString;
1453 Pattern->AddTypedTextChunk("default");
1454 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001455 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001456 }
1457
Douglas Gregord8e8a582010-05-25 21:41:55 +00001458 if (Results.includeCodePatterns()) {
1459 /// while (condition) { statements }
1460 Pattern = new CodeCompletionString;
1461 Pattern->AddTypedTextChunk("while");
1462 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1463 if (SemaRef.getLangOptions().CPlusPlus)
1464 Pattern->AddPlaceholderChunk("condition");
1465 else
1466 Pattern->AddPlaceholderChunk("expression");
1467 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1468 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1469 Pattern->AddPlaceholderChunk("statements");
1470 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1471 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1472 Results.AddResult(Result(Pattern));
1473
1474 // do { statements } while ( expression );
1475 Pattern = new CodeCompletionString;
1476 Pattern->AddTypedTextChunk("do");
1477 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1478 Pattern->AddPlaceholderChunk("statements");
1479 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1480 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1481 Pattern->AddTextChunk("while");
1482 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001483 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001484 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1485 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486
Douglas Gregord8e8a582010-05-25 21:41:55 +00001487 // for ( for-init-statement ; condition ; expression ) { statements }
1488 Pattern = new CodeCompletionString;
1489 Pattern->AddTypedTextChunk("for");
1490 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1491 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1492 Pattern->AddPlaceholderChunk("init-statement");
1493 else
1494 Pattern->AddPlaceholderChunk("init-expression");
1495 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1496 Pattern->AddPlaceholderChunk("condition");
1497 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1498 Pattern->AddPlaceholderChunk("inc-expression");
1499 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1500 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1501 Pattern->AddPlaceholderChunk("statements");
1502 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1503 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1504 Results.AddResult(Result(Pattern));
1505 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001506
1507 if (S->getContinueParent()) {
1508 // continue ;
1509 Pattern = new CodeCompletionString;
1510 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001511 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001512 }
1513
1514 if (S->getBreakParent()) {
1515 // break ;
1516 Pattern = new CodeCompletionString;
1517 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001518 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001519 }
1520
1521 // "return expression ;" or "return ;", depending on whether we
1522 // know the function is void or not.
1523 bool isVoid = false;
1524 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1525 isVoid = Function->getResultType()->isVoidType();
1526 else if (ObjCMethodDecl *Method
1527 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1528 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001529 else if (SemaRef.getCurBlock() &&
1530 !SemaRef.getCurBlock()->ReturnType.isNull())
1531 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 Pattern = new CodeCompletionString;
1533 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001534 if (!isVoid) {
1535 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001537 }
Douglas Gregora4477812010-01-14 16:01:26 +00001538 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001539
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001540 // goto identifier ;
1541 Pattern = new CodeCompletionString;
1542 Pattern->AddTypedTextChunk("goto");
1543 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1544 Pattern->AddPlaceholderChunk("label");
1545 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001546
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001547 // Using directives
1548 Pattern = new CodeCompletionString;
1549 Pattern->AddTypedTextChunk("using");
1550 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1551 Pattern->AddTextChunk("namespace");
1552 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1553 Pattern->AddPlaceholderChunk("identifier");
1554 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001555 }
1556
1557 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001558 case Sema::PCC_ForInit:
1559 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001560 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561 // Fall through: conditions and statements can have expressions.
1562
John McCallf312b1e2010-08-26 23:41:50 +00001563 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001564 CodeCompletionString *Pattern = 0;
1565 if (SemaRef.getLangOptions().CPlusPlus) {
1566 // 'this', if we're in a non-static member function.
1567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1568 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001569 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001570
1571 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001572 Results.AddResult(Result("true"));
1573 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001574
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001575 // dynamic_cast < type-id > ( expression )
1576 Pattern = new CodeCompletionString;
1577 Pattern->AddTypedTextChunk("dynamic_cast");
1578 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1579 Pattern->AddPlaceholderChunk("type");
1580 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1581 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1582 Pattern->AddPlaceholderChunk("expression");
1583 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1584 Results.AddResult(Result(Pattern));
1585
1586 // static_cast < type-id > ( expression )
1587 Pattern = new CodeCompletionString;
1588 Pattern->AddTypedTextChunk("static_cast");
1589 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1590 Pattern->AddPlaceholderChunk("type");
1591 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1592 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1593 Pattern->AddPlaceholderChunk("expression");
1594 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1595 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001596
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001597 // reinterpret_cast < type-id > ( expression )
1598 Pattern = new CodeCompletionString;
1599 Pattern->AddTypedTextChunk("reinterpret_cast");
1600 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1601 Pattern->AddPlaceholderChunk("type");
1602 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1603 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1604 Pattern->AddPlaceholderChunk("expression");
1605 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1606 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001607
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001608 // const_cast < type-id > ( expression )
1609 Pattern = new CodeCompletionString;
1610 Pattern->AddTypedTextChunk("const_cast");
1611 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1612 Pattern->AddPlaceholderChunk("type");
1613 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1614 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1615 Pattern->AddPlaceholderChunk("expression");
1616 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1617 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001618
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001619 // typeid ( expression-or-type )
1620 Pattern = new CodeCompletionString;
1621 Pattern->AddTypedTextChunk("typeid");
1622 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1623 Pattern->AddPlaceholderChunk("expression-or-type");
1624 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1625 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001627 // new T ( ... )
1628 Pattern = new CodeCompletionString;
1629 Pattern->AddTypedTextChunk("new");
1630 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1631 Pattern->AddPlaceholderChunk("type");
1632 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1633 Pattern->AddPlaceholderChunk("expressions");
1634 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1635 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001636
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001637 // new T [ ] ( ... )
1638 Pattern = new CodeCompletionString;
1639 Pattern->AddTypedTextChunk("new");
1640 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1641 Pattern->AddPlaceholderChunk("type");
1642 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1643 Pattern->AddPlaceholderChunk("size");
1644 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1645 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1646 Pattern->AddPlaceholderChunk("expressions");
1647 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1648 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001649
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001650 // delete expression
1651 Pattern = new CodeCompletionString;
1652 Pattern->AddTypedTextChunk("delete");
1653 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1654 Pattern->AddPlaceholderChunk("expression");
1655 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // delete [] expression
1658 Pattern = new CodeCompletionString;
1659 Pattern->AddTypedTextChunk("delete");
1660 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1661 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1662 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1663 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1664 Pattern->AddPlaceholderChunk("expression");
1665 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001666
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001667 // throw expression
1668 Pattern = new CodeCompletionString;
1669 Pattern->AddTypedTextChunk("throw");
1670 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1671 Pattern->AddPlaceholderChunk("expression");
1672 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001673
1674 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001675 }
1676
1677 if (SemaRef.getLangOptions().ObjC1) {
1678 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001679 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1680 // The interface can be NULL.
1681 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1682 if (ID->getSuperClass())
1683 Results.AddResult(Result("super"));
1684 }
1685
Douglas Gregorbca403c2010-01-13 23:51:12 +00001686 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001687 }
1688
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001689 // sizeof expression
1690 Pattern = new CodeCompletionString;
1691 Pattern->AddTypedTextChunk("sizeof");
1692 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1693 Pattern->AddPlaceholderChunk("expression-or-type");
1694 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1695 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001696 break;
1697 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001698
John McCallf312b1e2010-08-26 23:41:50 +00001699 case Sema::PCC_Type:
Douglas Gregord32b0222010-08-24 01:06:58 +00001700 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001701 }
1702
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001703 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1704 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001705
John McCallf312b1e2010-08-26 23:41:50 +00001706 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001707 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708}
1709
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001710/// \brief If the given declaration has an associated type, add it as a result
1711/// type chunk.
1712static void AddResultTypeChunk(ASTContext &Context,
1713 NamedDecl *ND,
1714 CodeCompletionString *Result) {
1715 if (!ND)
1716 return;
1717
1718 // Determine the type of the declaration (if it has a type).
1719 QualType T;
1720 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1721 T = Function->getResultType();
1722 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1723 T = Method->getResultType();
1724 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1725 T = FunTmpl->getTemplatedDecl()->getResultType();
1726 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1727 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1728 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1729 /* Do nothing: ignore unresolved using declarations*/
1730 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1731 T = Value->getType();
1732 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1733 T = Property->getType();
1734
1735 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1736 return;
1737
Douglas Gregor84139d62010-04-05 21:25:31 +00001738 PrintingPolicy Policy(Context.PrintingPolicy);
1739 Policy.AnonymousTagLocations = false;
1740
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001741 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001742 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001743 Result->AddResultTypeChunk(TypeStr);
1744}
1745
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001746static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1747 CodeCompletionString *Result) {
1748 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1749 if (Sentinel->getSentinel() == 0) {
1750 if (Context.getLangOptions().ObjC1 &&
1751 Context.Idents.get("nil").hasMacroDefinition())
1752 Result->AddTextChunk(", nil");
1753 else if (Context.Idents.get("NULL").hasMacroDefinition())
1754 Result->AddTextChunk(", NULL");
1755 else
1756 Result->AddTextChunk(", (void*)0");
1757 }
1758}
1759
Douglas Gregor83482d12010-08-24 16:15:59 +00001760static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001761 ParmVarDecl *Param,
1762 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001763 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1764 if (Param->getType()->isDependentType() ||
1765 !Param->getType()->isBlockPointerType()) {
1766 // The argument for a dependent or non-block parameter is a placeholder
1767 // containing that parameter's type.
1768 std::string Result;
1769
Douglas Gregoraba48082010-08-29 19:47:46 +00001770 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001771 Result = Param->getIdentifier()->getName();
1772
1773 Param->getType().getAsStringInternal(Result,
1774 Context.PrintingPolicy);
1775
1776 if (ObjCMethodParam) {
1777 Result = "(" + Result;
1778 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001779 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001780 Result += Param->getIdentifier()->getName();
1781 }
1782 return Result;
1783 }
1784
1785 // The argument for a block pointer parameter is a block literal with
1786 // the appropriate type.
1787 FunctionProtoTypeLoc *Block = 0;
1788 TypeLoc TL;
1789 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1790 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1791 while (true) {
1792 // Look through typedefs.
1793 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1794 if (TypeSourceInfo *InnerTSInfo
1795 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1796 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1797 continue;
1798 }
1799 }
1800
1801 // Look through qualified types
1802 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1803 TL = QualifiedTL->getUnqualifiedLoc();
1804 continue;
1805 }
1806
1807 // Try to get the function prototype behind the block pointer type,
1808 // then we're done.
1809 if (BlockPointerTypeLoc *BlockPtr
1810 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1811 TL = BlockPtr->getPointeeLoc();
1812 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1813 }
1814 break;
1815 }
1816 }
1817
1818 if (!Block) {
1819 // We were unable to find a FunctionProtoTypeLoc with parameter names
1820 // for the block; just use the parameter type as a placeholder.
1821 std::string Result;
1822 Param->getType().getUnqualifiedType().
1823 getAsStringInternal(Result, Context.PrintingPolicy);
1824
1825 if (ObjCMethodParam) {
1826 Result = "(" + Result;
1827 Result += ")";
1828 if (Param->getIdentifier())
1829 Result += Param->getIdentifier()->getName();
1830 }
1831
1832 return Result;
1833 }
1834
1835 // We have the function prototype behind the block pointer type, as it was
1836 // written in the source.
1837 std::string Result = "(^)(";
1838 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1839 if (I)
1840 Result += ", ";
1841 Result += FormatFunctionParameter(Context, Block->getArg(I));
1842 }
1843 if (Block->getTypePtr()->isVariadic()) {
1844 if (Block->getNumArgs() > 0)
1845 Result += ", ...";
1846 else
1847 Result += "...";
1848 } else if (Block->getNumArgs() == 0 && !Context.getLangOptions().CPlusPlus)
1849 Result += "void";
1850
1851 Result += ")";
1852 Block->getTypePtr()->getResultType().getAsStringInternal(Result,
1853 Context.PrintingPolicy);
1854 return Result;
1855}
1856
Douglas Gregor86d9a522009-09-21 16:56:56 +00001857/// \brief Add function parameter chunks to the given code completion string.
1858static void AddFunctionParameterChunks(ASTContext &Context,
1859 FunctionDecl *Function,
1860 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001861 typedef CodeCompletionString::Chunk Chunk;
1862
Douglas Gregor86d9a522009-09-21 16:56:56 +00001863 CodeCompletionString *CCStr = Result;
1864
1865 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1866 ParmVarDecl *Param = Function->getParamDecl(P);
1867
1868 if (Param->hasDefaultArg()) {
1869 // When we see an optional default argument, put that argument and
1870 // the remaining default arguments into a new, optional string.
1871 CodeCompletionString *Opt = new CodeCompletionString;
1872 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1873 CCStr = Opt;
1874 }
1875
1876 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001877 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001878
1879 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001880 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1881
Douglas Gregor86d9a522009-09-21 16:56:56 +00001882 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001883 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001884 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001885
1886 if (const FunctionProtoType *Proto
1887 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001888 if (Proto->isVariadic()) {
Douglas Gregorb3d45252009-09-22 21:42:17 +00001889 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001890
1891 MaybeAddSentinel(Context, Function, CCStr);
1892 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001893}
1894
1895/// \brief Add template parameter chunks to the given code completion string.
1896static void AddTemplateParameterChunks(ASTContext &Context,
1897 TemplateDecl *Template,
1898 CodeCompletionString *Result,
1899 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001900 typedef CodeCompletionString::Chunk Chunk;
1901
Douglas Gregor86d9a522009-09-21 16:56:56 +00001902 CodeCompletionString *CCStr = Result;
1903 bool FirstParameter = true;
1904
1905 TemplateParameterList *Params = Template->getTemplateParameters();
1906 TemplateParameterList::iterator PEnd = Params->end();
1907 if (MaxParameters)
1908 PEnd = Params->begin() + MaxParameters;
1909 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1910 bool HasDefaultArg = false;
1911 std::string PlaceholderStr;
1912 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1913 if (TTP->wasDeclaredWithTypename())
1914 PlaceholderStr = "typename";
1915 else
1916 PlaceholderStr = "class";
1917
1918 if (TTP->getIdentifier()) {
1919 PlaceholderStr += ' ';
1920 PlaceholderStr += TTP->getIdentifier()->getName();
1921 }
1922
1923 HasDefaultArg = TTP->hasDefaultArgument();
1924 } else if (NonTypeTemplateParmDecl *NTTP
1925 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1926 if (NTTP->getIdentifier())
1927 PlaceholderStr = NTTP->getIdentifier()->getName();
1928 NTTP->getType().getAsStringInternal(PlaceholderStr,
1929 Context.PrintingPolicy);
1930 HasDefaultArg = NTTP->hasDefaultArgument();
1931 } else {
1932 assert(isa<TemplateTemplateParmDecl>(*P));
1933 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1934
1935 // Since putting the template argument list into the placeholder would
1936 // be very, very long, we just use an abbreviation.
1937 PlaceholderStr = "template<...> class";
1938 if (TTP->getIdentifier()) {
1939 PlaceholderStr += ' ';
1940 PlaceholderStr += TTP->getIdentifier()->getName();
1941 }
1942
1943 HasDefaultArg = TTP->hasDefaultArgument();
1944 }
1945
1946 if (HasDefaultArg) {
1947 // When we see an optional default argument, put that argument and
1948 // the remaining default arguments into a new, optional string.
1949 CodeCompletionString *Opt = new CodeCompletionString;
1950 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1951 CCStr = Opt;
1952 }
1953
1954 if (FirstParameter)
1955 FirstParameter = false;
1956 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001957 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001958
1959 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001960 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001961 }
1962}
1963
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001964/// \brief Add a qualifier to the given code-completion string, if the
1965/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001966static void
1967AddQualifierToCompletionString(CodeCompletionString *Result,
1968 NestedNameSpecifier *Qualifier,
1969 bool QualifierIsInformative,
1970 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001971 if (!Qualifier)
1972 return;
1973
1974 std::string PrintedNNS;
1975 {
1976 llvm::raw_string_ostream OS(PrintedNNS);
1977 Qualifier->print(OS, Context.PrintingPolicy);
1978 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001979 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001980 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001981 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001982 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001983}
1984
Douglas Gregora61a8792009-12-11 18:44:16 +00001985static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1986 FunctionDecl *Function) {
1987 const FunctionProtoType *Proto
1988 = Function->getType()->getAs<FunctionProtoType>();
1989 if (!Proto || !Proto->getTypeQuals())
1990 return;
1991
1992 std::string QualsStr;
1993 if (Proto->getTypeQuals() & Qualifiers::Const)
1994 QualsStr += " const";
1995 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1996 QualsStr += " volatile";
1997 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1998 QualsStr += " restrict";
1999 Result->AddInformativeChunk(QualsStr);
2000}
2001
Douglas Gregor86d9a522009-09-21 16:56:56 +00002002/// \brief If possible, create a new code completion string for the given
2003/// result.
2004///
2005/// \returns Either a new, heap-allocated code completion string describing
2006/// how to use this result, or NULL to indicate that the string or name of the
2007/// result is all that is needed.
2008CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002009CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002010 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002011 typedef CodeCompletionString::Chunk Chunk;
2012
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002013 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002014 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002015
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002016 if (!Result)
2017 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002018
2019 if (Kind == RK_Keyword) {
2020 Result->AddTypedTextChunk(Keyword);
2021 return Result;
2022 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002023
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002024 if (Kind == RK_Macro) {
2025 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002026 assert(MI && "Not a macro?");
2027
2028 Result->AddTypedTextChunk(Macro->getName());
2029
2030 if (!MI->isFunctionLike())
2031 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002032
2033 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002034 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002035 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2036 A != AEnd; ++A) {
2037 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002038 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002039
2040 if (!MI->isVariadic() || A != AEnd - 1) {
2041 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002042 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002043 continue;
2044 }
2045
2046 // Variadic argument; cope with the different between GNU and C99
2047 // variadic macros, providing a single placeholder for the rest of the
2048 // arguments.
2049 if ((*A)->isStr("__VA_ARGS__"))
2050 Result->AddPlaceholderChunk("...");
2051 else {
2052 std::string Arg = (*A)->getName();
2053 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00002054 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002055 }
2056 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002057 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002058 return Result;
2059 }
2060
Douglas Gregord8e8a582010-05-25 21:41:55 +00002061 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002062 NamedDecl *ND = Declaration;
2063
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002064 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002065 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002066 Result->AddTextChunk("::");
2067 return Result;
2068 }
2069
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002070 AddResultTypeChunk(S.Context, ND, Result);
2071
Douglas Gregor86d9a522009-09-21 16:56:56 +00002072 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002073 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2074 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002075 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002076 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002077 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002078 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002079 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002080 return Result;
2081 }
2082
2083 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002084 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2085 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002086 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00002087 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00002088
2089 // Figure out which template parameters are deduced (or have default
2090 // arguments).
2091 llvm::SmallVector<bool, 16> Deduced;
2092 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2093 unsigned LastDeducibleArgument;
2094 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2095 --LastDeducibleArgument) {
2096 if (!Deduced[LastDeducibleArgument - 1]) {
2097 // C++0x: Figure out if the template argument has a default. If so,
2098 // the user doesn't need to type this argument.
2099 // FIXME: We need to abstract template parameters better!
2100 bool HasDefaultArg = false;
2101 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2102 LastDeducibleArgument - 1);
2103 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2104 HasDefaultArg = TTP->hasDefaultArgument();
2105 else if (NonTypeTemplateParmDecl *NTTP
2106 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2107 HasDefaultArg = NTTP->hasDefaultArgument();
2108 else {
2109 assert(isa<TemplateTemplateParmDecl>(Param));
2110 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002111 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002112 }
2113
2114 if (!HasDefaultArg)
2115 break;
2116 }
2117 }
2118
2119 if (LastDeducibleArgument) {
2120 // Some of the function template arguments cannot be deduced from a
2121 // function call, so we introduce an explicit template argument list
2122 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002123 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002124 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2125 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002126 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002127 }
2128
2129 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002130 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002131 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002132 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002133 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002134 return Result;
2135 }
2136
2137 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002138 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2139 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002140 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002141 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002142 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002143 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002144 return Result;
2145 }
2146
Douglas Gregor9630eb62009-11-17 16:44:22 +00002147 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002148 Selector Sel = Method->getSelector();
2149 if (Sel.isUnarySelector()) {
2150 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2151 return Result;
2152 }
2153
Douglas Gregord3c68542009-11-19 01:08:35 +00002154 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2155 SelName += ':';
2156 if (StartParameter == 0)
2157 Result->AddTypedTextChunk(SelName);
2158 else {
2159 Result->AddInformativeChunk(SelName);
2160
2161 // If there is only one parameter, and we're past it, add an empty
2162 // typed-text chunk since there is nothing to type.
2163 if (Method->param_size() == 1)
2164 Result->AddTypedTextChunk("");
2165 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002166 unsigned Idx = 0;
2167 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2168 PEnd = Method->param_end();
2169 P != PEnd; (void)++P, ++Idx) {
2170 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002171 std::string Keyword;
2172 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002173 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002174 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2175 Keyword += II->getName().str();
2176 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002177 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002178 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002179 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00002180 Result->AddTypedTextChunk(Keyword);
2181 else
2182 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002183 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002184
2185 // If we're before the starting parameter, skip the placeholder.
2186 if (Idx < StartParameter)
2187 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002188
2189 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002190
2191 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002192 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002193 else {
2194 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2195 Arg = "(" + Arg + ")";
2196 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002197 if (DeclaringEntity || AllParametersAreInformative)
2198 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002199 }
2200
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002201 if (DeclaringEntity)
2202 Result->AddTextChunk(Arg);
2203 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002204 Result->AddInformativeChunk(Arg);
2205 else
2206 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002207 }
2208
Douglas Gregor2a17af02009-12-23 00:21:46 +00002209 if (Method->isVariadic()) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002210 if (DeclaringEntity)
2211 Result->AddTextChunk(", ...");
2212 else if (AllParametersAreInformative)
Douglas Gregor2a17af02009-12-23 00:21:46 +00002213 Result->AddInformativeChunk(", ...");
2214 else
2215 Result->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002216
2217 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002218 }
2219
Douglas Gregor9630eb62009-11-17 16:44:22 +00002220 return Result;
2221 }
2222
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002223 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002224 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2225 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002226
2227 Result->AddTypedTextChunk(ND->getNameAsString());
2228 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002229}
2230
Douglas Gregor86d802e2009-09-23 00:34:09 +00002231CodeCompletionString *
2232CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2233 unsigned CurrentArg,
2234 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002235 typedef CodeCompletionString::Chunk Chunk;
2236
Douglas Gregor86d802e2009-09-23 00:34:09 +00002237 CodeCompletionString *Result = new CodeCompletionString;
2238 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002239 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002240 const FunctionProtoType *Proto
2241 = dyn_cast<FunctionProtoType>(getFunctionType());
2242 if (!FDecl && !Proto) {
2243 // Function without a prototype. Just give the return type and a
2244 // highlighted ellipsis.
2245 const FunctionType *FT = getFunctionType();
2246 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002247 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002248 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2249 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2250 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002251 return Result;
2252 }
2253
2254 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002255 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002256 else
2257 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002258 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002259
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002260 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002261 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2262 for (unsigned I = 0; I != NumParams; ++I) {
2263 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002264 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002265
2266 std::string ArgString;
2267 QualType ArgType;
2268
2269 if (FDecl) {
2270 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2271 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2272 } else {
2273 ArgType = Proto->getArgType(I);
2274 }
2275
2276 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2277
2278 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002279 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002280 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002281 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002282 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002283 }
2284
2285 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002286 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002287 if (CurrentArg < NumParams)
2288 Result->AddTextChunk("...");
2289 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002290 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002291 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002292 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002293
2294 return Result;
2295}
2296
Douglas Gregor1827e102010-08-16 16:18:59 +00002297unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2298 bool PreferredTypeIsPointer) {
2299 unsigned Priority = CCP_Macro;
2300
2301 // Treat the "nil" and "NULL" macros as null pointer constants.
2302 if (MacroName.equals("nil") || MacroName.equals("NULL")) {
2303 Priority = CCP_Constant;
2304 if (PreferredTypeIsPointer)
2305 Priority = Priority / CCF_SimilarTypeMatch;
2306 }
2307
2308 return Priority;
2309}
2310
Douglas Gregor590c7d52010-07-08 20:55:51 +00002311static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2312 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002313 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002314
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002315 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002316 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2317 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002318 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002319 Results.AddResult(Result(M->first,
2320 getMacroUsagePriority(M->first->getName(),
2321 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002322 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002323 Results.ExitScope();
2324}
2325
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002326static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2327 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002328 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002329
2330 Results.EnterNewScope();
2331 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2332 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2333 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2334 Results.AddResult(Result("__func__", CCP_Constant));
2335 Results.ExitScope();
2336}
2337
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002338static void HandleCodeCompleteResults(Sema *S,
2339 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002340 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002341 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002342 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002343 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002344 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002345
2346 for (unsigned I = 0; I != NumResults; ++I)
2347 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002348}
2349
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002350static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2351 Sema::ParserCompletionContext PCC) {
2352 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002353 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002354 return CodeCompletionContext::CCC_TopLevel;
2355
John McCallf312b1e2010-08-26 23:41:50 +00002356 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002357 return CodeCompletionContext::CCC_ClassStructUnion;
2358
John McCallf312b1e2010-08-26 23:41:50 +00002359 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002360 return CodeCompletionContext::CCC_ObjCInterface;
2361
John McCallf312b1e2010-08-26 23:41:50 +00002362 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002363 return CodeCompletionContext::CCC_ObjCImplementation;
2364
John McCallf312b1e2010-08-26 23:41:50 +00002365 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002366 return CodeCompletionContext::CCC_ObjCIvarList;
2367
John McCallf312b1e2010-08-26 23:41:50 +00002368 case Sema::PCC_Template:
2369 case Sema::PCC_MemberTemplate:
2370 case Sema::PCC_RecoveryInFunction:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002371 return CodeCompletionContext::CCC_Other;
2372
John McCallf312b1e2010-08-26 23:41:50 +00002373 case Sema::PCC_Expression:
2374 case Sema::PCC_ForInit:
2375 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002376 return CodeCompletionContext::CCC_Expression;
2377
John McCallf312b1e2010-08-26 23:41:50 +00002378 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002379 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002380
John McCallf312b1e2010-08-26 23:41:50 +00002381 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002382 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002383 }
2384
2385 return CodeCompletionContext::CCC_Other;
2386}
2387
Douglas Gregorf6961522010-08-27 21:18:54 +00002388/// \brief If we're in a C++ virtual member function, add completion results
2389/// that invoke the functions we override, since it's common to invoke the
2390/// overridden function as well as adding new functionality.
2391///
2392/// \param S The semantic analysis object for which we are generating results.
2393///
2394/// \param InContext This context in which the nested-name-specifier preceding
2395/// the code-completion point
2396static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2397 ResultBuilder &Results) {
2398 // Look through blocks.
2399 DeclContext *CurContext = S.CurContext;
2400 while (isa<BlockDecl>(CurContext))
2401 CurContext = CurContext->getParent();
2402
2403
2404 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2405 if (!Method || !Method->isVirtual())
2406 return;
2407
2408 // We need to have names for all of the parameters, if we're going to
2409 // generate a forwarding call.
2410 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2411 PEnd = Method->param_end();
2412 P != PEnd;
2413 ++P) {
2414 if (!(*P)->getDeclName())
2415 return;
2416 }
2417
2418 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2419 MEnd = Method->end_overridden_methods();
2420 M != MEnd; ++M) {
2421 CodeCompletionString *Pattern = new CodeCompletionString;
2422 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2423 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2424 continue;
2425
2426 // If we need a nested-name-specifier, add one now.
2427 if (!InContext) {
2428 NestedNameSpecifier *NNS
2429 = getRequiredQualification(S.Context, CurContext,
2430 Overridden->getDeclContext());
2431 if (NNS) {
2432 std::string Str;
2433 llvm::raw_string_ostream OS(Str);
2434 NNS->print(OS, S.Context.PrintingPolicy);
2435 Pattern->AddTextChunk(OS.str());
2436 }
2437 } else if (!InContext->Equals(Overridden->getDeclContext()))
2438 continue;
2439
2440 Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2441 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2442 bool FirstParam = true;
2443 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2444 PEnd = Method->param_end();
2445 P != PEnd; ++P) {
2446 if (FirstParam)
2447 FirstParam = false;
2448 else
2449 Pattern->AddChunk(CodeCompletionString::CK_Comma);
2450
2451 Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2452 }
2453 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2454 Results.AddResult(CodeCompletionResult(Pattern,
2455 CCP_SuperCompletion,
2456 CXCursor_CXXMethod));
2457 Results.Ignore(Overridden);
2458 }
2459}
2460
Douglas Gregor01dfea02010-01-10 23:08:15 +00002461void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002462 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002463 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002464 ResultBuilder Results(*this);
Douglas Gregorf6961522010-08-27 21:18:54 +00002465 Results.EnterNewScope();
Douglas Gregor01dfea02010-01-10 23:08:15 +00002466
2467 // Determine how to filter results, e.g., so that the names of
2468 // values (functions, enumerators, function templates, etc.) are
2469 // only allowed where we can have an expression.
2470 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002471 case PCC_Namespace:
2472 case PCC_Class:
2473 case PCC_ObjCInterface:
2474 case PCC_ObjCImplementation:
2475 case PCC_ObjCInstanceVariableList:
2476 case PCC_Template:
2477 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002478 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002479 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2480 break;
2481
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002482 case PCC_Statement:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002483 // For statements that are expressions, we prefer to call 'void' functions
2484 // rather than functions that return a result, since then the result would
2485 // be ignored.
2486 Results.setPreferredType(Context.VoidTy);
2487 // Fall through
2488
2489 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002490 case PCC_ForInit:
2491 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002492 if (WantTypesInContext(CompletionContext, getLangOptions()))
2493 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2494 else
2495 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002496
2497 if (getLangOptions().CPlusPlus)
2498 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002499 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002500
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002501 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002502 // Unfiltered
2503 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002504 }
2505
Douglas Gregor3cdee122010-08-26 16:36:48 +00002506 // If we are in a C++ non-static member function, check the qualifiers on
2507 // the member function to filter/prioritize the results list.
2508 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2509 if (CurMethod->isInstance())
2510 Results.setObjectTypeQualifiers(
2511 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2512
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002513 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002514 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2515 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002516
Douglas Gregorbca403c2010-01-13 23:51:12 +00002517 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002518 Results.ExitScope();
2519
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002520 switch (CompletionContext) {
Douglas Gregor72db1082010-08-24 01:11:00 +00002521 case PCC_Expression:
2522 case PCC_Statement:
2523 case PCC_RecoveryInFunction:
2524 if (S->getFnParent())
2525 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2526 break;
2527
2528 case PCC_Namespace:
2529 case PCC_Class:
2530 case PCC_ObjCInterface:
2531 case PCC_ObjCImplementation:
2532 case PCC_ObjCInstanceVariableList:
2533 case PCC_Template:
2534 case PCC_MemberTemplate:
2535 case PCC_ForInit:
2536 case PCC_Condition:
2537 case PCC_Type:
2538 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002539 }
2540
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002541 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002542 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002543
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002544 HandleCodeCompleteResults(this, CodeCompleter,
2545 mapCodeCompletionContext(*this, CompletionContext),
2546 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002547}
2548
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002549void Sema::CodeCompleteDeclarator(Scope *S,
2550 bool AllowNonIdentifiers,
2551 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002552 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002553 ResultBuilder Results(*this);
2554 Results.EnterNewScope();
2555
2556 // Type qualifiers can come after names.
2557 Results.AddResult(Result("const"));
2558 Results.AddResult(Result("volatile"));
2559 if (getLangOptions().C99)
2560 Results.AddResult(Result("restrict"));
2561
2562 if (getLangOptions().CPlusPlus) {
2563 if (AllowNonIdentifiers) {
2564 Results.AddResult(Result("operator"));
2565 }
2566
2567 // Add nested-name-specifiers.
2568 if (AllowNestedNameSpecifiers) {
2569 Results.allowNestedNameSpecifiers();
2570 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2571 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2572 CodeCompleter->includeGlobals());
2573 }
2574 }
2575 Results.ExitScope();
2576
Douglas Gregor4497dd42010-08-24 04:59:56 +00002577 // Note that we intentionally suppress macro results here, since we do not
2578 // encourage using macros to produce the names of entities.
2579
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002580 HandleCodeCompleteResults(this, CodeCompleter,
2581 AllowNestedNameSpecifiers
2582 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2583 : CodeCompletionContext::CCC_Name,
2584 Results.data(), Results.size());
2585}
2586
Douglas Gregorfb629412010-08-23 21:17:50 +00002587struct Sema::CodeCompleteExpressionData {
2588 CodeCompleteExpressionData(QualType PreferredType = QualType())
2589 : PreferredType(PreferredType), IntegralConstantExpression(false),
2590 ObjCCollection(false) { }
2591
2592 QualType PreferredType;
2593 bool IntegralConstantExpression;
2594 bool ObjCCollection;
2595 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2596};
2597
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002598/// \brief Perform code-completion in an expression context when we know what
2599/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002600///
2601/// \param IntegralConstantExpression Only permit integral constant
2602/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002603void Sema::CodeCompleteExpression(Scope *S,
2604 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002605 typedef CodeCompletionResult Result;
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002606 ResultBuilder Results(*this);
2607
Douglas Gregorfb629412010-08-23 21:17:50 +00002608 if (Data.ObjCCollection)
2609 Results.setFilter(&ResultBuilder::IsObjCCollection);
2610 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002611 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002612 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002613 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2614 else
2615 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002616
2617 if (!Data.PreferredType.isNull())
2618 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2619
2620 // Ignore any declarations that we were told that we don't care about.
2621 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2622 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002623
2624 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002625 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2626 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002627
2628 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002629 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002630 Results.ExitScope();
2631
Douglas Gregor590c7d52010-07-08 20:55:51 +00002632 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002633 if (!Data.PreferredType.isNull())
2634 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2635 || Data.PreferredType->isMemberPointerType()
2636 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002637
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002638 if (S->getFnParent() &&
2639 !Data.ObjCCollection &&
2640 !Data.IntegralConstantExpression)
2641 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2642
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002643 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002644 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002645 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002646 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2647 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002648 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002649}
2650
2651
Douglas Gregor95ac6552009-11-18 01:29:26 +00002652static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002653 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002654 DeclContext *CurContext,
2655 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002656 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002657
2658 // Add properties in this container.
2659 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2660 PEnd = Container->prop_end();
2661 P != PEnd;
2662 ++P)
2663 Results.MaybeAddResult(Result(*P, 0), CurContext);
2664
2665 // Add properties in referenced protocols.
2666 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2667 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2668 PEnd = Protocol->protocol_end();
2669 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002670 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002671 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002672 if (AllowCategories) {
2673 // Look through categories.
2674 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2675 Category; Category = Category->getNextClassCategory())
2676 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2677 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002678
2679 // Look through protocols.
2680 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2681 E = IFace->protocol_end();
2682 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002683 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002684
2685 // Look in the superclass.
2686 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002687 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2688 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002689 } else if (const ObjCCategoryDecl *Category
2690 = dyn_cast<ObjCCategoryDecl>(Container)) {
2691 // Look through protocols.
2692 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2693 PEnd = Category->protocol_end();
2694 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002695 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002696 }
2697}
2698
Douglas Gregor81b747b2009-09-17 21:32:03 +00002699void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2700 SourceLocation OpLoc,
2701 bool IsArrow) {
2702 if (!BaseE || !CodeCompleter)
2703 return;
2704
John McCall0a2c5e22010-08-25 06:19:51 +00002705 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002706
Douglas Gregor81b747b2009-09-17 21:32:03 +00002707 Expr *Base = static_cast<Expr *>(BaseE);
2708 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002709
2710 if (IsArrow) {
2711 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2712 BaseType = Ptr->getPointeeType();
2713 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00002714 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002715 else
2716 return;
2717 }
2718
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002719 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002720 Results.EnterNewScope();
2721 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00002722 // Indicate that we are performing a member access, and the cv-qualifiers
2723 // for the base object type.
2724 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
2725
Douglas Gregor95ac6552009-11-18 01:29:26 +00002726 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002727 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002728 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002729 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2730 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002731
Douglas Gregor95ac6552009-11-18 01:29:26 +00002732 if (getLangOptions().CPlusPlus) {
2733 if (!Results.empty()) {
2734 // The "template" keyword can follow "->" or "." in the grammar.
2735 // However, we only want to suggest the template keyword if something
2736 // is dependent.
2737 bool IsDependent = BaseType->isDependentType();
2738 if (!IsDependent) {
2739 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2740 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2741 IsDependent = Ctx->isDependentContext();
2742 break;
2743 }
2744 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002745
Douglas Gregor95ac6552009-11-18 01:29:26 +00002746 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002747 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002748 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002749 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002750 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2751 // Objective-C property reference.
2752
2753 // Add property results based on our interface.
2754 const ObjCObjectPointerType *ObjCPtr
2755 = BaseType->getAsObjCInterfacePointerType();
2756 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002757 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002758
2759 // Add properties from the protocols in a qualified interface.
2760 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2761 E = ObjCPtr->qual_end();
2762 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002763 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002764 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002765 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002766 // Objective-C instance variable access.
2767 ObjCInterfaceDecl *Class = 0;
2768 if (const ObjCObjectPointerType *ObjCPtr
2769 = BaseType->getAs<ObjCObjectPointerType>())
2770 Class = ObjCPtr->getInterfaceDecl();
2771 else
John McCallc12c5bb2010-05-15 11:32:37 +00002772 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002773
2774 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002775 if (Class) {
2776 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2777 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00002778 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2779 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00002780 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002781 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002782
2783 // FIXME: How do we cope with isa?
2784
2785 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002786
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002787 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002788 HandleCodeCompleteResults(this, CodeCompleter,
2789 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2790 BaseType),
2791 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002792}
2793
Douglas Gregor374929f2009-09-18 15:37:17 +00002794void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2795 if (!CodeCompleter)
2796 return;
2797
John McCall0a2c5e22010-08-25 06:19:51 +00002798 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002799 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002800 enum CodeCompletionContext::Kind ContextKind
2801 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00002802 switch ((DeclSpec::TST)TagSpec) {
2803 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002804 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002806 break;
2807
2808 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002809 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002810 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002811 break;
2812
2813 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002814 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002815 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002816 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002817 break;
2818
2819 default:
2820 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2821 return;
2822 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002823
John McCall0d6b1642010-04-23 18:46:30 +00002824 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002825 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002826
2827 // First pass: look for tags.
2828 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00002829 LookupVisibleDecls(S, LookupTagName, Consumer,
2830 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00002831
Douglas Gregor8071e422010-08-15 06:18:01 +00002832 if (CodeCompleter->includeGlobals()) {
2833 // Second pass: look for nested name specifiers.
2834 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2835 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2836 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002837
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002838 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2839 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002840}
2841
Douglas Gregor1a480c42010-08-27 17:35:51 +00002842void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
2843 ResultBuilder Results(*this);
2844 Results.EnterNewScope();
2845 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
2846 Results.AddResult("const");
2847 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
2848 Results.AddResult("volatile");
2849 if (getLangOptions().C99 &&
2850 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
2851 Results.AddResult("restrict");
2852 Results.ExitScope();
2853 HandleCodeCompleteResults(this, CodeCompleter,
2854 CodeCompletionContext::CCC_TypeQualifiers,
2855 Results.data(), Results.size());
2856}
2857
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002858void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00002859 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002860 return;
2861
John McCall781472f2010-08-25 08:40:02 +00002862 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00002863 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00002864 CodeCompleteExpressionData Data(Switch->getCond()->getType());
2865 Data.IntegralConstantExpression = true;
2866 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002867 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00002868 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002869
2870 // Code-complete the cases of a switch statement over an enumeration type
2871 // by providing the list of
2872 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2873
2874 // Determine which enumerators we have already seen in the switch statement.
2875 // FIXME: Ideally, we would also be able to look *past* the code-completion
2876 // token, in case we are code-completing in the middle of the switch and not
2877 // at the end. However, we aren't able to do so at the moment.
2878 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002879 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002880 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2881 SC = SC->getNextSwitchCase()) {
2882 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2883 if (!Case)
2884 continue;
2885
2886 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2888 if (EnumConstantDecl *Enumerator
2889 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2890 // We look into the AST of the case statement to determine which
2891 // enumerator was named. Alternatively, we could compute the value of
2892 // the integral constant expression, then compare it against the
2893 // values of each enumerator. However, value-based approach would not
2894 // work as well with C++ templates where enumerators declared within a
2895 // template are type- and value-dependent.
2896 EnumeratorsSeen.insert(Enumerator);
2897
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002898 // If this is a qualified-id, keep track of the nested-name-specifier
2899 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002900 //
2901 // switch (TagD.getKind()) {
2902 // case TagDecl::TK_enum:
2903 // break;
2904 // case XXX
2905 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002906 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002907 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2908 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002909 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002910 }
2911 }
2912
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002913 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2914 // If there are no prior enumerators in C++, check whether we have to
2915 // qualify the names of the enumerators that we suggest, because they
2916 // may not be visible in this scope.
2917 Qualifier = getRequiredQualification(Context, CurContext,
2918 Enum->getDeclContext());
2919
2920 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2921 }
2922
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002923 // Add any enumerators that have not yet been mentioned.
2924 ResultBuilder Results(*this);
2925 Results.EnterNewScope();
2926 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2927 EEnd = Enum->enumerator_end();
2928 E != EEnd; ++E) {
2929 if (EnumeratorsSeen.count(*E))
2930 continue;
2931
John McCall0a2c5e22010-08-25 06:19:51 +00002932 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00002933 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002934 }
2935 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002936
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002937 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002938 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002939 HandleCodeCompleteResults(this, CodeCompleter,
2940 CodeCompletionContext::CCC_Expression,
2941 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002942}
2943
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002944namespace {
2945 struct IsBetterOverloadCandidate {
2946 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002947 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002948
2949 public:
John McCall5769d612010-02-08 23:07:23 +00002950 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2951 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002952
2953 bool
2954 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00002955 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002956 }
2957 };
2958}
2959
Douglas Gregord28dcd72010-05-30 06:10:08 +00002960static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2961 if (NumArgs && !Args)
2962 return true;
2963
2964 for (unsigned I = 0; I != NumArgs; ++I)
2965 if (!Args[I])
2966 return true;
2967
2968 return false;
2969}
2970
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002971void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2972 ExprTy **ArgsIn, unsigned NumArgs) {
2973 if (!CodeCompleter)
2974 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002975
2976 // When we're code-completing for a call, we fall back to ordinary
2977 // name code-completion whenever we can't produce specific
2978 // results. We may want to revisit this strategy in the future,
2979 // e.g., by merging the two kinds of results.
2980
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002981 Expr *Fn = (Expr *)FnIn;
2982 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002983
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002984 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002985 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002986 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002987 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002988 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002989 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002990
John McCall3b4294e2009-12-16 12:17:52 +00002991 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002992 SourceLocation Loc = Fn->getExprLoc();
2993 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002994
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002995 // FIXME: What if we're calling something that isn't a function declaration?
2996 // FIXME: What if we're calling a pseudo-destructor?
2997 // FIXME: What if we're calling a member function?
2998
Douglas Gregorc0265402010-01-21 15:46:19 +00002999 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3000 llvm::SmallVector<ResultCandidate, 8> Results;
3001
John McCall3b4294e2009-12-16 12:17:52 +00003002 Expr *NakedFn = Fn->IgnoreParenCasts();
3003 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3004 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3005 /*PartialOverloading=*/ true);
3006 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3007 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003008 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003009 if (!getLangOptions().CPlusPlus ||
3010 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003011 Results.push_back(ResultCandidate(FDecl));
3012 else
John McCall86820f52010-01-26 01:37:31 +00003013 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003014 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3015 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003016 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003017 }
John McCall3b4294e2009-12-16 12:17:52 +00003018 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003019
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003020 QualType ParamType;
3021
Douglas Gregorc0265402010-01-21 15:46:19 +00003022 if (!CandidateSet.empty()) {
3023 // Sort the overload candidate set by placing the best overloads first.
3024 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003025 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003026
Douglas Gregorc0265402010-01-21 15:46:19 +00003027 // Add the remaining viable overload candidates as code-completion reslults.
3028 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3029 CandEnd = CandidateSet.end();
3030 Cand != CandEnd; ++Cand) {
3031 if (Cand->Viable)
3032 Results.push_back(ResultCandidate(Cand->Function));
3033 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003034
3035 // From the viable candidates, try to determine the type of this parameter.
3036 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3037 if (const FunctionType *FType = Results[I].getFunctionType())
3038 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3039 if (NumArgs < Proto->getNumArgs()) {
3040 if (ParamType.isNull())
3041 ParamType = Proto->getArgType(NumArgs);
3042 else if (!Context.hasSameUnqualifiedType(
3043 ParamType.getNonReferenceType(),
3044 Proto->getArgType(NumArgs).getNonReferenceType())) {
3045 ParamType = QualType();
3046 break;
3047 }
3048 }
3049 }
3050 } else {
3051 // Try to determine the parameter type from the type of the expression
3052 // being called.
3053 QualType FunctionType = Fn->getType();
3054 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3055 FunctionType = Ptr->getPointeeType();
3056 else if (const BlockPointerType *BlockPtr
3057 = FunctionType->getAs<BlockPointerType>())
3058 FunctionType = BlockPtr->getPointeeType();
3059 else if (const MemberPointerType *MemPtr
3060 = FunctionType->getAs<MemberPointerType>())
3061 FunctionType = MemPtr->getPointeeType();
3062
3063 if (const FunctionProtoType *Proto
3064 = FunctionType->getAs<FunctionProtoType>()) {
3065 if (NumArgs < Proto->getNumArgs())
3066 ParamType = Proto->getArgType(NumArgs);
3067 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003068 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003069
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003070 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003071 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003072 else
3073 CodeCompleteExpression(S, ParamType);
3074
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003075 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003076 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3077 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003078}
3079
John McCalld226f652010-08-21 09:40:31 +00003080void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3081 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003082 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003083 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003084 return;
3085 }
3086
3087 CodeCompleteExpression(S, VD->getType());
3088}
3089
3090void Sema::CodeCompleteReturn(Scope *S) {
3091 QualType ResultType;
3092 if (isa<BlockDecl>(CurContext)) {
3093 if (BlockScopeInfo *BSI = getCurBlock())
3094 ResultType = BSI->ReturnType;
3095 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3096 ResultType = Function->getResultType();
3097 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3098 ResultType = Method->getResultType();
3099
3100 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003101 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003102 else
3103 CodeCompleteExpression(S, ResultType);
3104}
3105
3106void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3107 if (LHS)
3108 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3109 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003110 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003111}
3112
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003113void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003114 bool EnteringContext) {
3115 if (!SS.getScopeRep() || !CodeCompleter)
3116 return;
3117
Douglas Gregor86d9a522009-09-21 16:56:56 +00003118 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3119 if (!Ctx)
3120 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003121
3122 // Try to instantiate any non-dependent declaration contexts before
3123 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003124 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003125 return;
3126
Douglas Gregor86d9a522009-09-21 16:56:56 +00003127 ResultBuilder Results(*this);
Douglas Gregor86d9a522009-09-21 16:56:56 +00003128
Douglas Gregorf6961522010-08-27 21:18:54 +00003129 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003130 // The "template" keyword can follow "::" in the grammar, but only
3131 // put it into the grammar if the nested-name-specifier is dependent.
3132 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3133 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003134 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003135
3136 // Add calls to overridden virtual functions, if there are any.
3137 //
3138 // FIXME: This isn't wonderful, because we don't know whether we're actually
3139 // in a context that permits expressions. This is a general issue with
3140 // qualified-id completions.
3141 if (!EnteringContext)
3142 MaybeAddOverrideCalls(*this, Ctx, Results);
3143 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003144
Douglas Gregorf6961522010-08-27 21:18:54 +00003145 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3146 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3147
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003148 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003149 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003150 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003151}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003152
3153void Sema::CodeCompleteUsing(Scope *S) {
3154 if (!CodeCompleter)
3155 return;
3156
Douglas Gregor86d9a522009-09-21 16:56:56 +00003157 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003158 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003159
3160 // If we aren't in class scope, we could see the "namespace" keyword.
3161 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003162 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003163
3164 // After "using", we can see anything that would start a
3165 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003166 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003167 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3168 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003169 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003170
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003171 HandleCodeCompleteResults(this, CodeCompleter,
3172 CodeCompletionContext::CCC_Other,
3173 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003174}
3175
3176void Sema::CodeCompleteUsingDirective(Scope *S) {
3177 if (!CodeCompleter)
3178 return;
3179
Douglas Gregor86d9a522009-09-21 16:56:56 +00003180 // After "using namespace", we expect to see a namespace name or namespace
3181 // alias.
3182 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003183 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003184 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003185 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3186 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003187 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003188 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003189 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003190 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003191}
3192
3193void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3194 if (!CodeCompleter)
3195 return;
3196
Douglas Gregor86d9a522009-09-21 16:56:56 +00003197 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
3198 DeclContext *Ctx = (DeclContext *)S->getEntity();
3199 if (!S->getParent())
3200 Ctx = Context.getTranslationUnitDecl();
3201
3202 if (Ctx && Ctx->isFileContext()) {
3203 // We only want to see those namespaces that have already been defined
3204 // within this scope, because its likely that the user is creating an
3205 // extended namespace declaration. Keep track of the most recent
3206 // definition of each namespace.
3207 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3208 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3209 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3210 NS != NSEnd; ++NS)
3211 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3212
3213 // Add the most recent definition (or extended definition) of each
3214 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003215 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003216 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3217 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3218 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003219 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003220 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003221 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003222 }
3223
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003224 HandleCodeCompleteResults(this, CodeCompleter,
3225 CodeCompletionContext::CCC_Other,
3226 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003227}
3228
3229void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3230 if (!CodeCompleter)
3231 return;
3232
Douglas Gregor86d9a522009-09-21 16:56:56 +00003233 // After "namespace", we expect to see a namespace or alias.
3234 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003235 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003236 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3237 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003238 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003239 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003240 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003241}
3242
Douglas Gregored8d3222009-09-18 20:05:18 +00003243void Sema::CodeCompleteOperatorName(Scope *S) {
3244 if (!CodeCompleter)
3245 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003246
John McCall0a2c5e22010-08-25 06:19:51 +00003247 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003248 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003249 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003250
Douglas Gregor86d9a522009-09-21 16:56:56 +00003251 // Add the names of overloadable operators.
3252#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3253 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003254 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003255#include "clang/Basic/OperatorKinds.def"
3256
3257 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003258 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003259 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003260 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3261 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003262
3263 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003264 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003265 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003266
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003267 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003268 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003269 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003270}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003271
Douglas Gregor0133f522010-08-28 00:00:50 +00003272void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3273 CXXBaseOrMemberInitializer** Initializers,
3274 unsigned NumInitializers) {
3275 CXXConstructorDecl *Constructor
3276 = static_cast<CXXConstructorDecl *>(ConstructorD);
3277 if (!Constructor)
3278 return;
3279
3280 ResultBuilder Results(*this);
3281 Results.EnterNewScope();
3282
3283 // Fill in any already-initialized fields or base classes.
3284 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3285 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3286 for (unsigned I = 0; I != NumInitializers; ++I) {
3287 if (Initializers[I]->isBaseInitializer())
3288 InitializedBases.insert(
3289 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3290 else
3291 InitializedFields.insert(cast<FieldDecl>(Initializers[I]->getMember()));
3292 }
3293
3294 // Add completions for base classes.
Douglas Gregor0c431c82010-08-29 19:27:27 +00003295 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003296 CXXRecordDecl *ClassDecl = Constructor->getParent();
3297 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3298 BaseEnd = ClassDecl->bases_end();
3299 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003300 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3301 SawLastInitializer
3302 = NumInitializers > 0 &&
3303 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3304 Context.hasSameUnqualifiedType(Base->getType(),
3305 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003306 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003307 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003308
3309 CodeCompletionString *Pattern = new CodeCompletionString;
3310 Pattern->AddTypedTextChunk(
3311 Base->getType().getAsString(Context.PrintingPolicy));
3312 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3313 Pattern->AddPlaceholderChunk("args");
3314 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003315 Results.AddResult(CodeCompletionResult(Pattern,
3316 SawLastInitializer? CCP_NextInitializer
3317 : CCP_MemberDeclaration));
3318 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003319 }
3320
3321 // Add completions for virtual base classes.
3322 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3323 BaseEnd = ClassDecl->vbases_end();
3324 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003325 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3326 SawLastInitializer
3327 = NumInitializers > 0 &&
3328 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3329 Context.hasSameUnqualifiedType(Base->getType(),
3330 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003331 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003332 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003333
3334 CodeCompletionString *Pattern = new CodeCompletionString;
3335 Pattern->AddTypedTextChunk(
3336 Base->getType().getAsString(Context.PrintingPolicy));
3337 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3338 Pattern->AddPlaceholderChunk("args");
3339 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003340 Results.AddResult(CodeCompletionResult(Pattern,
3341 SawLastInitializer? CCP_NextInitializer
3342 : CCP_MemberDeclaration));
3343 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003344 }
3345
3346 // Add completions for members.
3347 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3348 FieldEnd = ClassDecl->field_end();
3349 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003350 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3351 SawLastInitializer
3352 = NumInitializers > 0 &&
3353 Initializers[NumInitializers - 1]->isMemberInitializer() &&
3354 Initializers[NumInitializers - 1]->getMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003355 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003356 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003357
3358 if (!Field->getDeclName())
3359 continue;
3360
3361 CodeCompletionString *Pattern = new CodeCompletionString;
3362 Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3363 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3364 Pattern->AddPlaceholderChunk("args");
3365 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003366 Results.AddResult(CodeCompletionResult(Pattern,
3367 SawLastInitializer? CCP_NextInitializer
3368 : CCP_MemberDeclaration));
3369 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003370 }
3371 Results.ExitScope();
3372
3373 HandleCodeCompleteResults(this, CodeCompleter,
3374 CodeCompletionContext::CCC_Name,
3375 Results.data(), Results.size());
3376}
3377
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003378// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3379// true or false.
3380#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003381static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003382 ResultBuilder &Results,
3383 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003384 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003385 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003386 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003387
3388 CodeCompletionString *Pattern = 0;
3389 if (LangOpts.ObjC2) {
3390 // @dynamic
3391 Pattern = new CodeCompletionString;
3392 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3393 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3394 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003395 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003396
3397 // @synthesize
3398 Pattern = new CodeCompletionString;
3399 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3400 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3401 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003402 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003403 }
3404}
3405
Douglas Gregorbca403c2010-01-13 23:51:12 +00003406static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003407 ResultBuilder &Results,
3408 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003409 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003410
3411 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003412 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003413
3414 if (LangOpts.ObjC2) {
3415 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003416 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003417
3418 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003419 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003420
3421 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003422 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003423 }
3424}
3425
Douglas Gregorbca403c2010-01-13 23:51:12 +00003426static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003427 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003428 CodeCompletionString *Pattern = 0;
3429
3430 // @class name ;
3431 Pattern = new CodeCompletionString;
3432 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3433 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003434 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003435 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003436
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003437 if (Results.includeCodePatterns()) {
3438 // @interface name
3439 // FIXME: Could introduce the whole pattern, including superclasses and
3440 // such.
3441 Pattern = new CodeCompletionString;
3442 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3443 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3444 Pattern->AddPlaceholderChunk("class");
3445 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003446
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003447 // @protocol name
3448 Pattern = new CodeCompletionString;
3449 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3450 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3451 Pattern->AddPlaceholderChunk("protocol");
3452 Results.AddResult(Result(Pattern));
3453
3454 // @implementation name
3455 Pattern = new CodeCompletionString;
3456 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3457 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3458 Pattern->AddPlaceholderChunk("class");
3459 Results.AddResult(Result(Pattern));
3460 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003461
3462 // @compatibility_alias name
3463 Pattern = new CodeCompletionString;
3464 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3465 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3466 Pattern->AddPlaceholderChunk("alias");
3467 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3468 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003469 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003470}
3471
John McCalld226f652010-08-21 09:40:31 +00003472void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003473 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003474 typedef CodeCompletionResult Result;
Douglas Gregorc464ae82009-12-07 09:27:33 +00003475 ResultBuilder Results(*this);
3476 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003477 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003478 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003479 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003480 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003481 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003482 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003483 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003484 HandleCodeCompleteResults(this, CodeCompleter,
3485 CodeCompletionContext::CCC_Other,
3486 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003487}
3488
Douglas Gregorbca403c2010-01-13 23:51:12 +00003489static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003490 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003491 CodeCompletionString *Pattern = 0;
3492
3493 // @encode ( type-name )
3494 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003495 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003496 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3497 Pattern->AddPlaceholderChunk("type-name");
3498 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003499 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003500
3501 // @protocol ( protocol-name )
3502 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003503 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003504 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3505 Pattern->AddPlaceholderChunk("protocol-name");
3506 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003507 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003508
3509 // @selector ( selector )
3510 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003511 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003512 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3513 Pattern->AddPlaceholderChunk("selector");
3514 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003515 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003516}
3517
Douglas Gregorbca403c2010-01-13 23:51:12 +00003518static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003519 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003520 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003521
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003522 if (Results.includeCodePatterns()) {
3523 // @try { statements } @catch ( declaration ) { statements } @finally
3524 // { statements }
3525 Pattern = new CodeCompletionString;
3526 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3527 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3528 Pattern->AddPlaceholderChunk("statements");
3529 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3530 Pattern->AddTextChunk("@catch");
3531 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3532 Pattern->AddPlaceholderChunk("parameter");
3533 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3534 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3535 Pattern->AddPlaceholderChunk("statements");
3536 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3537 Pattern->AddTextChunk("@finally");
3538 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3539 Pattern->AddPlaceholderChunk("statements");
3540 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3541 Results.AddResult(Result(Pattern));
3542 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003543
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003544 // @throw
3545 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003546 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003547 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003548 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003549 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003550
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003551 if (Results.includeCodePatterns()) {
3552 // @synchronized ( expression ) { statements }
3553 Pattern = new CodeCompletionString;
3554 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3555 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3556 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3557 Pattern->AddPlaceholderChunk("expression");
3558 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3559 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3560 Pattern->AddPlaceholderChunk("statements");
3561 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3562 Results.AddResult(Result(Pattern));
3563 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003564}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003565
Douglas Gregorbca403c2010-01-13 23:51:12 +00003566static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003567 ResultBuilder &Results,
3568 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003569 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003570 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3571 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3572 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003573 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003574 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003575}
3576
3577void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3578 ResultBuilder Results(*this);
3579 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003580 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003581 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003582 HandleCodeCompleteResults(this, CodeCompleter,
3583 CodeCompletionContext::CCC_Other,
3584 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003585}
3586
3587void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003588 ResultBuilder Results(*this);
3589 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003590 AddObjCStatementResults(Results, false);
3591 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003592 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003593 HandleCodeCompleteResults(this, CodeCompleter,
3594 CodeCompletionContext::CCC_Other,
3595 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003596}
3597
3598void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3599 ResultBuilder Results(*this);
3600 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003601 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003602 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003603 HandleCodeCompleteResults(this, CodeCompleter,
3604 CodeCompletionContext::CCC_Other,
3605 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003606}
3607
Douglas Gregor988358f2009-11-19 00:14:45 +00003608/// \brief Determine whether the addition of the given flag to an Objective-C
3609/// property's attributes will cause a conflict.
3610static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3611 // Check if we've already added this flag.
3612 if (Attributes & NewFlag)
3613 return true;
3614
3615 Attributes |= NewFlag;
3616
3617 // Check for collisions with "readonly".
3618 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3619 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3620 ObjCDeclSpec::DQ_PR_assign |
3621 ObjCDeclSpec::DQ_PR_copy |
3622 ObjCDeclSpec::DQ_PR_retain)))
3623 return true;
3624
3625 // Check for more than one of { assign, copy, retain }.
3626 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3627 ObjCDeclSpec::DQ_PR_copy |
3628 ObjCDeclSpec::DQ_PR_retain);
3629 if (AssignCopyRetMask &&
3630 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3631 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3632 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3633 return true;
3634
3635 return false;
3636}
3637
Douglas Gregora93b1082009-11-18 23:08:07 +00003638void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003639 if (!CodeCompleter)
3640 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003641
Steve Naroffece8e712009-10-08 21:55:05 +00003642 unsigned Attributes = ODS.getPropertyAttributes();
3643
John McCall0a2c5e22010-08-25 06:19:51 +00003644 typedef CodeCompletionResult Result;
Steve Naroffece8e712009-10-08 21:55:05 +00003645 ResultBuilder Results(*this);
3646 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003647 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003648 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003649 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003650 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003651 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003652 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003653 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003654 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003655 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003656 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003657 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003658 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003659 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003660 CodeCompletionString *Setter = new CodeCompletionString;
3661 Setter->AddTypedTextChunk("setter");
3662 Setter->AddTextChunk(" = ");
3663 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003664 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003665 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003666 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003667 CodeCompletionString *Getter = new CodeCompletionString;
3668 Getter->AddTypedTextChunk("getter");
3669 Getter->AddTextChunk(" = ");
3670 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003671 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003672 }
Steve Naroffece8e712009-10-08 21:55:05 +00003673 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003674 HandleCodeCompleteResults(this, CodeCompleter,
3675 CodeCompletionContext::CCC_Other,
3676 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003677}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003678
Douglas Gregor4ad96852009-11-19 07:41:15 +00003679/// \brief Descripts the kind of Objective-C method that we want to find
3680/// via code completion.
3681enum ObjCMethodKind {
3682 MK_Any, //< Any kind of method, provided it means other specified criteria.
3683 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3684 MK_OneArgSelector //< One-argument selector.
3685};
3686
Douglas Gregor458433d2010-08-26 15:07:07 +00003687static bool isAcceptableObjCSelector(Selector Sel,
3688 ObjCMethodKind WantKind,
3689 IdentifierInfo **SelIdents,
3690 unsigned NumSelIdents) {
3691 if (NumSelIdents > Sel.getNumArgs())
3692 return false;
3693
3694 switch (WantKind) {
3695 case MK_Any: break;
3696 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3697 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3698 }
3699
3700 for (unsigned I = 0; I != NumSelIdents; ++I)
3701 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3702 return false;
3703
3704 return true;
3705}
3706
Douglas Gregor4ad96852009-11-19 07:41:15 +00003707static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3708 ObjCMethodKind WantKind,
3709 IdentifierInfo **SelIdents,
3710 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00003711 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3712 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003713}
3714
Douglas Gregor36ecb042009-11-17 23:22:23 +00003715/// \brief Add all of the Objective-C methods in the given Objective-C
3716/// container to the set of results.
3717///
3718/// The container will be a class, protocol, category, or implementation of
3719/// any of the above. This mether will recurse to include methods from
3720/// the superclasses of classes along with their categories, protocols, and
3721/// implementations.
3722///
3723/// \param Container the container in which we'll look to find methods.
3724///
3725/// \param WantInstance whether to add instance methods (only); if false, this
3726/// routine will add factory methods (only).
3727///
3728/// \param CurContext the context in which we're performing the lookup that
3729/// finds methods.
3730///
3731/// \param Results the structure into which we'll add results.
3732static void AddObjCMethods(ObjCContainerDecl *Container,
3733 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003734 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003735 IdentifierInfo **SelIdents,
3736 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003737 DeclContext *CurContext,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003738 ResultBuilder &Results,
3739 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00003740 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00003741 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3742 MEnd = Container->meth_end();
3743 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003744 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3745 // Check whether the selector identifiers we've been given are a
3746 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003747 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003748 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003749
Douglas Gregord3c68542009-11-19 01:08:35 +00003750 Result R = Result(*M, 0);
3751 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003752 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00003753 if (!InOriginalClass)
3754 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00003755 Results.MaybeAddResult(R, CurContext);
3756 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003757 }
3758
3759 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3760 if (!IFace)
3761 return;
3762
3763 // Add methods in protocols.
3764 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3765 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3766 E = Protocols.end();
3767 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003768 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003769 CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003770
3771 // Add methods in categories.
3772 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3773 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003774 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003775 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003776
3777 // Add a categories protocol methods.
3778 const ObjCList<ObjCProtocolDecl> &Protocols
3779 = CatDecl->getReferencedProtocols();
3780 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3781 E = Protocols.end();
3782 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003783 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003784 NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003785
3786 // Add methods in category implementations.
3787 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003788 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003789 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003790 }
3791
3792 // Add methods in superclass.
3793 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003794 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003795 SelIdents, NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003796
3797 // Add methods in our implementation, if any.
3798 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003799 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003800 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003801}
3802
3803
John McCalld226f652010-08-21 09:40:31 +00003804void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
3805 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003806 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003807 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003808
3809 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00003810 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003811 if (!Class) {
3812 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003813 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003814 Class = Category->getClassInterface();
3815
3816 if (!Class)
3817 return;
3818 }
3819
3820 // Find all of the potential getters.
3821 ResultBuilder Results(*this);
3822 Results.EnterNewScope();
3823
3824 // FIXME: We need to do this because Objective-C methods don't get
3825 // pushed into DeclContexts early enough. Argh!
3826 for (unsigned I = 0; I != NumMethods; ++I) {
3827 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003828 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003829 if (Method->isInstanceMethod() &&
3830 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3831 Result R = Result(Method, 0);
3832 R.AllParametersAreInformative = true;
3833 Results.MaybeAddResult(R, CurContext);
3834 }
3835 }
3836
3837 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3838 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003839 HandleCodeCompleteResults(this, CodeCompleter,
3840 CodeCompletionContext::CCC_Other,
3841 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00003842}
3843
John McCalld226f652010-08-21 09:40:31 +00003844void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
3845 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003846 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003847 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003848
3849 // Try to find the interface where setters might live.
3850 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00003851 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003852 if (!Class) {
3853 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003854 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003855 Class = Category->getClassInterface();
3856
3857 if (!Class)
3858 return;
3859 }
3860
3861 // Find all of the potential getters.
3862 ResultBuilder Results(*this);
3863 Results.EnterNewScope();
3864
3865 // FIXME: We need to do this because Objective-C methods don't get
3866 // pushed into DeclContexts early enough. Argh!
3867 for (unsigned I = 0; I != NumMethods; ++I) {
3868 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003869 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003870 if (Method->isInstanceMethod() &&
3871 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3872 Result R = Result(Method, 0);
3873 R.AllParametersAreInformative = true;
3874 Results.MaybeAddResult(R, CurContext);
3875 }
3876 }
3877
3878 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3879
3880 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003881 HandleCodeCompleteResults(this, CodeCompleter,
3882 CodeCompletionContext::CCC_Other,
3883 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003884}
3885
Douglas Gregord32b0222010-08-24 01:06:58 +00003886void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00003887 typedef CodeCompletionResult Result;
Douglas Gregord32b0222010-08-24 01:06:58 +00003888 ResultBuilder Results(*this);
3889 Results.EnterNewScope();
3890
3891 // Add context-sensitive, Objective-C parameter-passing keywords.
3892 bool AddedInOut = false;
3893 if ((DS.getObjCDeclQualifier() &
3894 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
3895 Results.AddResult("in");
3896 Results.AddResult("inout");
3897 AddedInOut = true;
3898 }
3899 if ((DS.getObjCDeclQualifier() &
3900 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
3901 Results.AddResult("out");
3902 if (!AddedInOut)
3903 Results.AddResult("inout");
3904 }
3905 if ((DS.getObjCDeclQualifier() &
3906 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
3907 ObjCDeclSpec::DQ_Oneway)) == 0) {
3908 Results.AddResult("bycopy");
3909 Results.AddResult("byref");
3910 Results.AddResult("oneway");
3911 }
3912
3913 // Add various builtin type names and specifiers.
3914 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
3915 Results.ExitScope();
3916
3917 // Add the various type names
3918 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3919 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3920 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3921 CodeCompleter->includeGlobals());
3922
3923 if (CodeCompleter->includeMacros())
3924 AddMacroResults(PP, Results);
3925
3926 HandleCodeCompleteResults(this, CodeCompleter,
3927 CodeCompletionContext::CCC_Type,
3928 Results.data(), Results.size());
3929}
3930
Douglas Gregor22f56992010-04-06 19:22:33 +00003931/// \brief When we have an expression with type "id", we may assume
3932/// that it has some more-specific class type based on knowledge of
3933/// common uses of Objective-C. This routine returns that class type,
3934/// or NULL if no better result could be determined.
3935static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3936 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3937 if (!Msg)
3938 return 0;
3939
3940 Selector Sel = Msg->getSelector();
3941 if (Sel.isNull())
3942 return 0;
3943
3944 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3945 if (!Id)
3946 return 0;
3947
3948 ObjCMethodDecl *Method = Msg->getMethodDecl();
3949 if (!Method)
3950 return 0;
3951
3952 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003953 ObjCInterfaceDecl *IFace = 0;
3954 switch (Msg->getReceiverKind()) {
3955 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003956 if (const ObjCObjectType *ObjType
3957 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3958 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003959 break;
3960
3961 case ObjCMessageExpr::Instance: {
3962 QualType T = Msg->getInstanceReceiver()->getType();
3963 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3964 IFace = Ptr->getInterfaceDecl();
3965 break;
3966 }
3967
3968 case ObjCMessageExpr::SuperInstance:
3969 case ObjCMessageExpr::SuperClass:
3970 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003971 }
3972
3973 if (!IFace)
3974 return 0;
3975
3976 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3977 if (Method->isInstanceMethod())
3978 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3979 .Case("retain", IFace)
3980 .Case("autorelease", IFace)
3981 .Case("copy", IFace)
3982 .Case("copyWithZone", IFace)
3983 .Case("mutableCopy", IFace)
3984 .Case("mutableCopyWithZone", IFace)
3985 .Case("awakeFromCoder", IFace)
3986 .Case("replacementObjectFromCoder", IFace)
3987 .Case("class", IFace)
3988 .Case("classForCoder", IFace)
3989 .Case("superclass", Super)
3990 .Default(0);
3991
3992 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3993 .Case("new", IFace)
3994 .Case("alloc", IFace)
3995 .Case("allocWithZone", IFace)
3996 .Case("class", IFace)
3997 .Case("superclass", Super)
3998 .Default(0);
3999}
4000
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004001// Add a special completion for a message send to "super", which fills in the
4002// most likely case of forwarding all of our arguments to the superclass
4003// function.
4004///
4005/// \param S The semantic analysis object.
4006///
4007/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4008/// the "super" keyword. Otherwise, we just need to provide the arguments.
4009///
4010/// \param SelIdents The identifiers in the selector that have already been
4011/// provided as arguments for a send to "super".
4012///
4013/// \param NumSelIdents The number of identifiers in \p SelIdents.
4014///
4015/// \param Results The set of results to augment.
4016///
4017/// \returns the Objective-C method declaration that would be invoked by
4018/// this "super" completion. If NULL, no completion was added.
4019static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4020 IdentifierInfo **SelIdents,
4021 unsigned NumSelIdents,
4022 ResultBuilder &Results) {
4023 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4024 if (!CurMethod)
4025 return 0;
4026
4027 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4028 if (!Class)
4029 return 0;
4030
4031 // Try to find a superclass method with the same selector.
4032 ObjCMethodDecl *SuperMethod = 0;
4033 while ((Class = Class->getSuperClass()) && !SuperMethod)
4034 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4035 CurMethod->isInstanceMethod());
4036
4037 if (!SuperMethod)
4038 return 0;
4039
4040 // Check whether the superclass method has the same signature.
4041 if (CurMethod->param_size() != SuperMethod->param_size() ||
4042 CurMethod->isVariadic() != SuperMethod->isVariadic())
4043 return 0;
4044
4045 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4046 CurPEnd = CurMethod->param_end(),
4047 SuperP = SuperMethod->param_begin();
4048 CurP != CurPEnd; ++CurP, ++SuperP) {
4049 // Make sure the parameter types are compatible.
4050 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4051 (*SuperP)->getType()))
4052 return 0;
4053
4054 // Make sure we have a parameter name to forward!
4055 if (!(*CurP)->getIdentifier())
4056 return 0;
4057 }
4058
4059 // We have a superclass method. Now, form the send-to-super completion.
4060 CodeCompletionString *Pattern = new CodeCompletionString;
4061
4062 // Give this completion a return type.
4063 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4064
4065 // If we need the "super" keyword, add it (plus some spacing).
4066 if (NeedSuperKeyword) {
4067 Pattern->AddTypedTextChunk("super");
4068 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4069 }
4070
4071 Selector Sel = CurMethod->getSelector();
4072 if (Sel.isUnarySelector()) {
4073 if (NeedSuperKeyword)
4074 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4075 else
4076 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4077 } else {
4078 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4079 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4080 if (I > NumSelIdents)
4081 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4082
4083 if (I < NumSelIdents)
4084 Pattern->AddInformativeChunk(
4085 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4086 else if (NeedSuperKeyword || I > NumSelIdents) {
4087 Pattern->AddTextChunk(
4088 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4089 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4090 } else {
4091 Pattern->AddTypedTextChunk(
4092 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4093 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4094 }
4095 }
4096 }
4097
4098 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4099 SuperMethod->isInstanceMethod()
4100 ? CXCursor_ObjCInstanceMethodDecl
4101 : CXCursor_ObjCClassMethodDecl));
4102 return SuperMethod;
4103}
4104
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004105void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004106 typedef CodeCompletionResult Result;
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004107 ResultBuilder Results(*this);
4108
4109 // Find anything that looks like it could be a message receiver.
4110 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
4111 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4112 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004113 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4114 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004115
4116 // If we are in an Objective-C method inside a class that has a superclass,
4117 // add "super" as an option.
4118 if (ObjCMethodDecl *Method = getCurMethodDecl())
4119 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004120 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004121 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004122
4123 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4124 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004125
4126 Results.ExitScope();
4127
4128 if (CodeCompleter->includeMacros())
4129 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004130 HandleCodeCompleteResults(this, CodeCompleter,
4131 CodeCompletionContext::CCC_ObjCMessageReceiver,
4132 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004133
4134}
4135
Douglas Gregor2725ca82010-04-21 19:57:20 +00004136void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4137 IdentifierInfo **SelIdents,
4138 unsigned NumSelIdents) {
4139 ObjCInterfaceDecl *CDecl = 0;
4140 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4141 // Figure out which interface we're in.
4142 CDecl = CurMethod->getClassInterface();
4143 if (!CDecl)
4144 return;
4145
4146 // Find the superclass of this class.
4147 CDecl = CDecl->getSuperClass();
4148 if (!CDecl)
4149 return;
4150
4151 if (CurMethod->isInstanceMethod()) {
4152 // We are inside an instance method, which means that the message
4153 // send [super ...] is actually calling an instance method on the
4154 // current object. Build the super expression and handle this like
4155 // an instance method.
4156 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
4157 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall60d7b3a2010-08-24 06:29:42 +00004158 ExprResult Super
Douglas Gregor2725ca82010-04-21 19:57:20 +00004159 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
4160 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004161 SelIdents, NumSelIdents,
4162 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004163 }
4164
4165 // Fall through to send to the superclass in CDecl.
4166 } else {
4167 // "super" may be the name of a type or variable. Figure out which
4168 // it is.
4169 IdentifierInfo *Super = &Context.Idents.get("super");
4170 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4171 LookupOrdinaryName);
4172 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4173 // "super" names an interface. Use it.
4174 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004175 if (const ObjCObjectType *Iface
4176 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4177 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004178 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4179 // "super" names an unresolved type; we can't be more specific.
4180 } else {
4181 // Assume that "super" names some kind of value and parse that way.
4182 CXXScopeSpec SS;
4183 UnqualifiedId id;
4184 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004185 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004186 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
4187 SelIdents, NumSelIdents);
4188 }
4189
4190 // Fall through
4191 }
4192
John McCallb3d87482010-08-24 05:47:05 +00004193 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004194 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004195 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004196 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004197 NumSelIdents, /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004198}
4199
John McCallb3d87482010-08-24 05:47:05 +00004200void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00004201 IdentifierInfo **SelIdents,
4202 unsigned NumSelIdents) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004203 CodeCompleteObjCClassMessage(S, Receiver, SelIdents, NumSelIdents, false);
4204}
4205
4206void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4207 IdentifierInfo **SelIdents,
4208 unsigned NumSelIdents,
4209 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004210 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004211 ObjCInterfaceDecl *CDecl = 0;
4212
Douglas Gregor24a069f2009-11-17 17:59:40 +00004213 // If the given name refers to an interface type, retrieve the
4214 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004215 if (Receiver) {
4216 QualType T = GetTypeFromParser(Receiver, 0);
4217 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004218 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4219 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004220 }
4221
Douglas Gregor36ecb042009-11-17 23:22:23 +00004222 // Add all of the factory methods in this Objective-C class, its protocols,
4223 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004224 ResultBuilder Results(*this);
4225 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00004226
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004227 // If this is a send-to-super, try to add the special "super" send
4228 // completion.
4229 if (IsSuper) {
4230 if (ObjCMethodDecl *SuperMethod
4231 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4232 Results))
4233 Results.Ignore(SuperMethod);
4234 }
4235
Douglas Gregor265f7492010-08-27 15:29:55 +00004236 // If we're inside an Objective-C method definition, prefer its selector to
4237 // others.
4238 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4239 Results.setPreferredSelector(CurMethod->getSelector());
4240
Douglas Gregor13438f92010-04-06 16:40:00 +00004241 if (CDecl)
4242 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
4243 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004244 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004245 // We're messaging "id" as a type; provide all class/factory methods.
4246
Douglas Gregor719770d2010-04-06 17:30:22 +00004247 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004248 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004249 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004250 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4251 I != N; ++I) {
4252 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004253 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004254 continue;
4255
Sebastian Redldb9d2142010-08-02 23:18:59 +00004256 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004257 }
4258 }
4259
Sebastian Redldb9d2142010-08-02 23:18:59 +00004260 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4261 MEnd = MethodPool.end();
4262 M != MEnd; ++M) {
4263 for (ObjCMethodList *MethList = &M->second.second;
4264 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004265 MethList = MethList->Next) {
4266 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4267 NumSelIdents))
4268 continue;
4269
4270 Result R(MethList->Method, 0);
4271 R.StartParameter = NumSelIdents;
4272 R.AllParametersAreInformative = false;
4273 Results.MaybeAddResult(R, CurContext);
4274 }
4275 }
4276 }
4277
Steve Naroffc4df6d22009-11-07 02:08:14 +00004278 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004279 HandleCodeCompleteResults(this, CodeCompleter,
4280 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004281 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004282}
4283
Douglas Gregord3c68542009-11-19 01:08:35 +00004284void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4285 IdentifierInfo **SelIdents,
4286 unsigned NumSelIdents) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004287 CodeCompleteObjCInstanceMessage(S, Receiver, SelIdents, NumSelIdents, false);
4288}
4289
4290void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4291 IdentifierInfo **SelIdents,
4292 unsigned NumSelIdents,
4293 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004294 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004295
4296 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004297
Douglas Gregor36ecb042009-11-17 23:22:23 +00004298 // If necessary, apply function/array conversion to the receiver.
4299 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00004300 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004301 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004302
Douglas Gregor36ecb042009-11-17 23:22:23 +00004303 // Build the set of methods we can see.
4304 ResultBuilder Results(*this);
4305 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004306
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004307 // If this is a send-to-super, try to add the special "super" send
4308 // completion.
4309 if (IsSuper) {
4310 if (ObjCMethodDecl *SuperMethod
4311 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4312 Results))
4313 Results.Ignore(SuperMethod);
4314 }
4315
Douglas Gregor265f7492010-08-27 15:29:55 +00004316 // If we're inside an Objective-C method definition, prefer its selector to
4317 // others.
4318 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4319 Results.setPreferredSelector(CurMethod->getSelector());
4320
Douglas Gregor22f56992010-04-06 19:22:33 +00004321 // If we're messaging an expression with type "id" or "Class", check
4322 // whether we know something special about the receiver that allows
4323 // us to assume a more-specific receiver type.
4324 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4325 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4326 ReceiverType = Context.getObjCObjectPointerType(
4327 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00004328
Douglas Gregorf74a4192009-11-18 00:06:18 +00004329 // Handle messages to Class. This really isn't a message to an instance
4330 // method, so we treat it the same way we would treat a message send to a
4331 // class method.
4332 if (ReceiverType->isObjCClassType() ||
4333 ReceiverType->isObjCQualifiedClassType()) {
4334 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4335 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004336 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
4337 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004338 }
4339 }
4340 // Handle messages to a qualified ID ("id<foo>").
4341 else if (const ObjCObjectPointerType *QualID
4342 = ReceiverType->getAsObjCQualifiedIdType()) {
4343 // Search protocols for instance methods.
4344 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4345 E = QualID->qual_end();
4346 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004347 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4348 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004349 }
4350 // Handle messages to a pointer to interface type.
4351 else if (const ObjCObjectPointerType *IFacePtr
4352 = ReceiverType->getAsObjCInterfacePointerType()) {
4353 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004354 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
4355 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004356
4357 // Search protocols for instance methods.
4358 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4359 E = IFacePtr->qual_end();
4360 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004361 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4362 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004363 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004364 // Handle messages to "id".
4365 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004366 // We're messaging "id", so provide all instance methods we know
4367 // about as code-completion results.
4368
4369 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004370 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004371 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004372 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4373 I != N; ++I) {
4374 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004375 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004376 continue;
4377
Sebastian Redldb9d2142010-08-02 23:18:59 +00004378 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004379 }
4380 }
4381
Sebastian Redldb9d2142010-08-02 23:18:59 +00004382 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4383 MEnd = MethodPool.end();
4384 M != MEnd; ++M) {
4385 for (ObjCMethodList *MethList = &M->second.first;
4386 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004387 MethList = MethList->Next) {
4388 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4389 NumSelIdents))
4390 continue;
4391
4392 Result R(MethList->Method, 0);
4393 R.StartParameter = NumSelIdents;
4394 R.AllParametersAreInformative = false;
4395 Results.MaybeAddResult(R, CurContext);
4396 }
4397 }
4398 }
4399
Steve Naroffc4df6d22009-11-07 02:08:14 +00004400 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004401 HandleCodeCompleteResults(this, CodeCompleter,
4402 CodeCompletionContext::CCC_Other,
4403 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004404}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004405
Douglas Gregorfb629412010-08-23 21:17:50 +00004406void Sema::CodeCompleteObjCForCollection(Scope *S,
4407 DeclGroupPtrTy IterationVar) {
4408 CodeCompleteExpressionData Data;
4409 Data.ObjCCollection = true;
4410
4411 if (IterationVar.getAsOpaquePtr()) {
4412 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4413 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4414 if (*I)
4415 Data.IgnoreDecls.push_back(*I);
4416 }
4417 }
4418
4419 CodeCompleteExpression(S, Data);
4420}
4421
Douglas Gregor458433d2010-08-26 15:07:07 +00004422void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4423 unsigned NumSelIdents) {
4424 // If we have an external source, load the entire class method
4425 // pool from the AST file.
4426 if (ExternalSource) {
4427 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4428 I != N; ++I) {
4429 Selector Sel = ExternalSource->GetExternalSelector(I);
4430 if (Sel.isNull() || MethodPool.count(Sel))
4431 continue;
4432
4433 ReadMethodPool(Sel);
4434 }
4435 }
4436
4437 ResultBuilder Results(*this);
4438 Results.EnterNewScope();
4439 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4440 MEnd = MethodPool.end();
4441 M != MEnd; ++M) {
4442
4443 Selector Sel = M->first;
4444 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4445 continue;
4446
4447 CodeCompletionString *Pattern = new CodeCompletionString;
4448 if (Sel.isUnarySelector()) {
4449 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4450 Results.AddResult(Pattern);
4451 continue;
4452 }
4453
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004454 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004455 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004456 if (I == NumSelIdents) {
4457 if (!Accumulator.empty()) {
4458 Pattern->AddInformativeChunk(Accumulator);
4459 Accumulator.clear();
4460 }
4461 }
4462
4463 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4464 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004465 }
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004466 Pattern->AddTypedTextChunk(Accumulator);
Douglas Gregor458433d2010-08-26 15:07:07 +00004467 Results.AddResult(Pattern);
4468 }
4469 Results.ExitScope();
4470
4471 HandleCodeCompleteResults(this, CodeCompleter,
4472 CodeCompletionContext::CCC_SelectorName,
4473 Results.data(), Results.size());
4474}
4475
Douglas Gregor55385fe2009-11-18 04:19:12 +00004476/// \brief Add all of the protocol declarations that we find in the given
4477/// (translation unit) context.
4478static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004479 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004480 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004481 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004482
4483 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4484 DEnd = Ctx->decls_end();
4485 D != DEnd; ++D) {
4486 // Record any protocols we find.
4487 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004488 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004489 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004490
4491 // Record any forward-declared protocols we find.
4492 if (ObjCForwardProtocolDecl *Forward
4493 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4494 for (ObjCForwardProtocolDecl::protocol_iterator
4495 P = Forward->protocol_begin(),
4496 PEnd = Forward->protocol_end();
4497 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004498 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004499 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004500 }
4501 }
4502}
4503
4504void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4505 unsigned NumProtocols) {
4506 ResultBuilder Results(*this);
4507 Results.EnterNewScope();
4508
4509 // Tell the result set to ignore all of the protocols we have
4510 // already seen.
4511 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004512 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4513 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004514 Results.Ignore(Protocol);
4515
4516 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004517 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4518 Results);
4519
4520 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004521 HandleCodeCompleteResults(this, CodeCompleter,
4522 CodeCompletionContext::CCC_ObjCProtocolName,
4523 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004524}
4525
4526void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4527 ResultBuilder Results(*this);
4528 Results.EnterNewScope();
4529
4530 // Add all protocols.
4531 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4532 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004533
4534 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004535 HandleCodeCompleteResults(this, CodeCompleter,
4536 CodeCompletionContext::CCC_ObjCProtocolName,
4537 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004538}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004539
4540/// \brief Add all of the Objective-C interface declarations that we find in
4541/// the given (translation unit) context.
4542static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4543 bool OnlyForwardDeclarations,
4544 bool OnlyUnimplemented,
4545 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004546 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004547
4548 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4549 DEnd = Ctx->decls_end();
4550 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004551 // Record any interfaces we find.
4552 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4553 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4554 (!OnlyUnimplemented || !Class->getImplementation()))
4555 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004556
4557 // Record any forward-declared interfaces we find.
4558 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4559 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004560 C != CEnd; ++C)
4561 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4562 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4563 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004564 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004565 }
4566 }
4567}
4568
4569void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
4570 ResultBuilder Results(*this);
4571 Results.EnterNewScope();
4572
4573 // Add all classes.
4574 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4575 false, Results);
4576
4577 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004578 HandleCodeCompleteResults(this, CodeCompleter,
4579 CodeCompletionContext::CCC_Other,
4580 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004581}
4582
Douglas Gregorc83c6872010-04-15 22:33:43 +00004583void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4584 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004585 ResultBuilder Results(*this);
4586 Results.EnterNewScope();
4587
4588 // Make sure that we ignore the class we're currently defining.
4589 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004590 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004591 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004592 Results.Ignore(CurClass);
4593
4594 // Add all classes.
4595 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4596 false, Results);
4597
4598 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004599 HandleCodeCompleteResults(this, CodeCompleter,
4600 CodeCompletionContext::CCC_Other,
4601 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004602}
4603
4604void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
4605 ResultBuilder Results(*this);
4606 Results.EnterNewScope();
4607
4608 // Add all unimplemented classes.
4609 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4610 true, Results);
4611
4612 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004613 HandleCodeCompleteResults(this, CodeCompleter,
4614 CodeCompletionContext::CCC_Other,
4615 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004616}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004617
4618void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004619 IdentifierInfo *ClassName,
4620 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004621 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004622
4623 ResultBuilder Results(*this);
4624
4625 // Ignore any categories we find that have already been implemented by this
4626 // interface.
4627 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4628 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004629 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004630 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
4631 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4632 Category = Category->getNextClassCategory())
4633 CategoryNames.insert(Category->getIdentifier());
4634
4635 // Add all of the categories we know about.
4636 Results.EnterNewScope();
4637 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4638 for (DeclContext::decl_iterator D = TU->decls_begin(),
4639 DEnd = TU->decls_end();
4640 D != DEnd; ++D)
4641 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
4642 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004643 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004644 Results.ExitScope();
4645
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004646 HandleCodeCompleteResults(this, CodeCompleter,
4647 CodeCompletionContext::CCC_Other,
4648 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004649}
4650
4651void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004652 IdentifierInfo *ClassName,
4653 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004654 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004655
4656 // Find the corresponding interface. If we couldn't find the interface, the
4657 // program itself is ill-formed. However, we'll try to be helpful still by
4658 // providing the list of all of the categories we know about.
4659 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004660 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004661 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
4662 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004663 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004664
4665 ResultBuilder Results(*this);
4666
4667 // Add all of the categories that have have corresponding interface
4668 // declarations in this class and any of its superclasses, except for
4669 // already-implemented categories in the class itself.
4670 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4671 Results.EnterNewScope();
4672 bool IgnoreImplemented = true;
4673 while (Class) {
4674 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4675 Category = Category->getNextClassCategory())
4676 if ((!IgnoreImplemented || !Category->getImplementation()) &&
4677 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004678 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004679
4680 Class = Class->getSuperClass();
4681 IgnoreImplemented = false;
4682 }
4683 Results.ExitScope();
4684
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004685 HandleCodeCompleteResults(this, CodeCompleter,
4686 CodeCompletionContext::CCC_Other,
4687 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004688}
Douglas Gregor322328b2009-11-18 22:32:06 +00004689
John McCalld226f652010-08-21 09:40:31 +00004690void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004691 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004692 ResultBuilder Results(*this);
4693
4694 // Figure out where this @synthesize lives.
4695 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004696 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004697 if (!Container ||
4698 (!isa<ObjCImplementationDecl>(Container) &&
4699 !isa<ObjCCategoryImplDecl>(Container)))
4700 return;
4701
4702 // Ignore any properties that have already been implemented.
4703 for (DeclContext::decl_iterator D = Container->decls_begin(),
4704 DEnd = Container->decls_end();
4705 D != DEnd; ++D)
4706 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4707 Results.Ignore(PropertyImpl->getPropertyDecl());
4708
4709 // Add any properties that we find.
4710 Results.EnterNewScope();
4711 if (ObjCImplementationDecl *ClassImpl
4712 = dyn_cast<ObjCImplementationDecl>(Container))
4713 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4714 Results);
4715 else
4716 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4717 false, CurContext, Results);
4718 Results.ExitScope();
4719
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004720 HandleCodeCompleteResults(this, CodeCompleter,
4721 CodeCompletionContext::CCC_Other,
4722 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004723}
4724
4725void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4726 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00004727 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004728 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004729 ResultBuilder Results(*this);
4730
4731 // Figure out where this @synthesize lives.
4732 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004733 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004734 if (!Container ||
4735 (!isa<ObjCImplementationDecl>(Container) &&
4736 !isa<ObjCCategoryImplDecl>(Container)))
4737 return;
4738
4739 // Figure out which interface we're looking into.
4740 ObjCInterfaceDecl *Class = 0;
4741 if (ObjCImplementationDecl *ClassImpl
4742 = dyn_cast<ObjCImplementationDecl>(Container))
4743 Class = ClassImpl->getClassInterface();
4744 else
4745 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4746 ->getClassInterface();
4747
4748 // Add all of the instance variables in this class and its superclasses.
4749 Results.EnterNewScope();
4750 for(; Class; Class = Class->getSuperClass()) {
4751 // FIXME: We could screen the type of each ivar for compatibility with
4752 // the property, but is that being too paternal?
4753 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4754 IVarEnd = Class->ivar_end();
4755 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00004756 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00004757 }
4758 Results.ExitScope();
4759
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004760 HandleCodeCompleteResults(this, CodeCompleter,
4761 CodeCompletionContext::CCC_Other,
4762 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004763}
Douglas Gregore8f5a172010-04-07 00:21:17 +00004764
Douglas Gregor408be5a2010-08-25 01:08:01 +00004765// Mapping from selectors to the methods that implement that selector, along
4766// with the "in original class" flag.
4767typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
4768 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004769
4770/// \brief Find all of the methods that reside in the given container
4771/// (and its superclasses, protocols, etc.) that meet the given
4772/// criteria. Insert those methods into the map of known methods,
4773/// indexed by selector so they can be easily found.
4774static void FindImplementableMethods(ASTContext &Context,
4775 ObjCContainerDecl *Container,
4776 bool WantInstanceMethods,
4777 QualType ReturnType,
4778 bool IsInImplementation,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004779 KnownMethodsMap &KnownMethods,
4780 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004781 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4782 // Recurse into protocols.
4783 const ObjCList<ObjCProtocolDecl> &Protocols
4784 = IFace->getReferencedProtocols();
4785 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4786 E = Protocols.end();
4787 I != E; ++I)
4788 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004789 IsInImplementation, KnownMethods,
4790 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004791
4792 // If we're not in the implementation of a class, also visit the
4793 // superclass.
4794 if (!IsInImplementation && IFace->getSuperClass())
4795 FindImplementableMethods(Context, IFace->getSuperClass(),
4796 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004797 IsInImplementation, KnownMethods,
4798 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004799
4800 // Add methods from any class extensions (but not from categories;
4801 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00004802 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4803 Cat = Cat->getNextClassExtension())
4804 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4805 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004806 IsInImplementation, KnownMethods,
4807 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004808 }
4809
4810 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4811 // Recurse into protocols.
4812 const ObjCList<ObjCProtocolDecl> &Protocols
4813 = Category->getReferencedProtocols();
4814 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4815 E = Protocols.end();
4816 I != E; ++I)
4817 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004818 IsInImplementation, KnownMethods,
4819 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004820 }
4821
4822 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4823 // Recurse into protocols.
4824 const ObjCList<ObjCProtocolDecl> &Protocols
4825 = Protocol->getReferencedProtocols();
4826 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4827 E = Protocols.end();
4828 I != E; ++I)
4829 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004830 IsInImplementation, KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004831 }
4832
4833 // Add methods in this container. This operation occurs last because
4834 // we want the methods from this container to override any methods
4835 // we've previously seen with the same selector.
4836 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4837 MEnd = Container->meth_end();
4838 M != MEnd; ++M) {
4839 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4840 if (!ReturnType.isNull() &&
4841 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4842 continue;
4843
Douglas Gregor408be5a2010-08-25 01:08:01 +00004844 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004845 }
4846 }
4847}
4848
4849void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4850 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00004851 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00004852 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004853 // Determine the return type of the method we're declaring, if
4854 // provided.
4855 QualType ReturnType = GetTypeFromParser(ReturnTy);
4856
4857 // Determine where we should start searching for methods, and where we
4858 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4859 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00004860 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004861 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4862 SearchDecl = Impl->getClassInterface();
4863 CurrentDecl = Impl;
4864 IsInImplementation = true;
4865 } else if (ObjCCategoryImplDecl *CatImpl
4866 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4867 SearchDecl = CatImpl->getCategoryDecl();
4868 CurrentDecl = CatImpl;
4869 IsInImplementation = true;
4870 } else {
4871 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4872 CurrentDecl = SearchDecl;
4873 }
4874 }
4875
4876 if (!SearchDecl && S) {
4877 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4878 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4879 CurrentDecl = SearchDecl;
4880 }
4881 }
4882
4883 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004884 HandleCodeCompleteResults(this, CodeCompleter,
4885 CodeCompletionContext::CCC_Other,
4886 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004887 return;
4888 }
4889
4890 // Find all of the methods that we could declare/implement here.
4891 KnownMethodsMap KnownMethods;
4892 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4893 ReturnType, IsInImplementation, KnownMethods);
4894
4895 // Erase any methods that have already been declared or
4896 // implemented here.
4897 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4898 MEnd = CurrentDecl->meth_end();
4899 M != MEnd; ++M) {
4900 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4901 continue;
4902
4903 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4904 if (Pos != KnownMethods.end())
4905 KnownMethods.erase(Pos);
4906 }
4907
4908 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00004909 typedef CodeCompletionResult Result;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004910 ResultBuilder Results(*this);
4911 Results.EnterNewScope();
4912 PrintingPolicy Policy(Context.PrintingPolicy);
4913 Policy.AnonymousTagLocations = false;
4914 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4915 MEnd = KnownMethods.end();
4916 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00004917 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004918 CodeCompletionString *Pattern = new CodeCompletionString;
4919
4920 // If the result type was not already provided, add it to the
4921 // pattern as (type).
4922 if (ReturnType.isNull()) {
4923 std::string TypeStr;
4924 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4925 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4926 Pattern->AddTextChunk(TypeStr);
4927 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4928 }
4929
4930 Selector Sel = Method->getSelector();
4931
4932 // Add the first part of the selector to the pattern.
4933 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4934
4935 // Add parameters to the pattern.
4936 unsigned I = 0;
4937 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4938 PEnd = Method->param_end();
4939 P != PEnd; (void)++P, ++I) {
4940 // Add the part of the selector name.
4941 if (I == 0)
4942 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4943 else if (I < Sel.getNumArgs()) {
4944 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor47c03a72010-08-17 15:53:35 +00004945 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004946 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4947 } else
4948 break;
4949
4950 // Add the parameter type.
4951 std::string TypeStr;
4952 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4953 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4954 Pattern->AddTextChunk(TypeStr);
4955 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4956
4957 if (IdentifierInfo *Id = (*P)->getIdentifier())
4958 Pattern->AddTextChunk(Id->getName());
4959 }
4960
4961 if (Method->isVariadic()) {
4962 if (Method->param_size() > 0)
4963 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4964 Pattern->AddTextChunk("...");
4965 }
4966
Douglas Gregor447107d2010-05-28 00:57:46 +00004967 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004968 // We will be defining the method here, so add a compound statement.
4969 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4970 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4971 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4972 if (!Method->getResultType()->isVoidType()) {
4973 // If the result type is not void, add a return clause.
4974 Pattern->AddTextChunk("return");
4975 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4976 Pattern->AddPlaceholderChunk("expression");
4977 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4978 } else
4979 Pattern->AddPlaceholderChunk("statements");
4980
4981 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4982 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4983 }
4984
Douglas Gregor408be5a2010-08-25 01:08:01 +00004985 unsigned Priority = CCP_CodePattern;
4986 if (!M->second.second)
4987 Priority += CCD_InBaseClass;
4988
4989 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00004990 Method->isInstanceMethod()
4991 ? CXCursor_ObjCInstanceMethodDecl
4992 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00004993 }
4994
4995 Results.ExitScope();
4996
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004997 HandleCodeCompleteResults(this, CodeCompleter,
4998 CodeCompletionContext::CCC_Other,
4999 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005000}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005001
5002void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5003 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005004 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00005005 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005006 IdentifierInfo **SelIdents,
5007 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005008 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005009 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005010 if (ExternalSource) {
5011 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5012 I != N; ++I) {
5013 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005014 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005015 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00005016
5017 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005018 }
5019 }
5020
5021 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00005022 typedef CodeCompletionResult Result;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005023 ResultBuilder Results(*this);
5024
5025 if (ReturnTy)
5026 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00005027
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005028 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005029 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5030 MEnd = MethodPool.end();
5031 M != MEnd; ++M) {
5032 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5033 &M->second.second;
5034 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005035 MethList = MethList->Next) {
5036 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5037 NumSelIdents))
5038 continue;
5039
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005040 if (AtParameterName) {
5041 // Suggest parameter names we've seen before.
5042 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5043 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5044 if (Param->getIdentifier()) {
5045 CodeCompletionString *Pattern = new CodeCompletionString;
5046 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5047 Results.AddResult(Pattern);
5048 }
5049 }
5050
5051 continue;
5052 }
5053
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005054 Result R(MethList->Method, 0);
5055 R.StartParameter = NumSelIdents;
5056 R.AllParametersAreInformative = false;
5057 R.DeclaringEntity = true;
5058 Results.MaybeAddResult(R, CurContext);
5059 }
5060 }
5061
5062 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005063 HandleCodeCompleteResults(this, CodeCompleter,
5064 CodeCompletionContext::CCC_Other,
5065 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005066}
Douglas Gregor87c08a52010-08-13 22:48:40 +00005067
Douglas Gregorf29c5232010-08-24 22:20:20 +00005068void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00005069 ResultBuilder Results(*this);
5070 Results.EnterNewScope();
5071
5072 // #if <condition>
5073 CodeCompletionString *Pattern = new CodeCompletionString;
5074 Pattern->AddTypedTextChunk("if");
5075 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5076 Pattern->AddPlaceholderChunk("condition");
5077 Results.AddResult(Pattern);
5078
5079 // #ifdef <macro>
5080 Pattern = new CodeCompletionString;
5081 Pattern->AddTypedTextChunk("ifdef");
5082 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5083 Pattern->AddPlaceholderChunk("macro");
5084 Results.AddResult(Pattern);
5085
5086 // #ifndef <macro>
5087 Pattern = new CodeCompletionString;
5088 Pattern->AddTypedTextChunk("ifndef");
5089 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5090 Pattern->AddPlaceholderChunk("macro");
5091 Results.AddResult(Pattern);
5092
5093 if (InConditional) {
5094 // #elif <condition>
5095 Pattern = new CodeCompletionString;
5096 Pattern->AddTypedTextChunk("elif");
5097 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5098 Pattern->AddPlaceholderChunk("condition");
5099 Results.AddResult(Pattern);
5100
5101 // #else
5102 Pattern = new CodeCompletionString;
5103 Pattern->AddTypedTextChunk("else");
5104 Results.AddResult(Pattern);
5105
5106 // #endif
5107 Pattern = new CodeCompletionString;
5108 Pattern->AddTypedTextChunk("endif");
5109 Results.AddResult(Pattern);
5110 }
5111
5112 // #include "header"
5113 Pattern = new CodeCompletionString;
5114 Pattern->AddTypedTextChunk("include");
5115 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5116 Pattern->AddTextChunk("\"");
5117 Pattern->AddPlaceholderChunk("header");
5118 Pattern->AddTextChunk("\"");
5119 Results.AddResult(Pattern);
5120
5121 // #include <header>
5122 Pattern = new CodeCompletionString;
5123 Pattern->AddTypedTextChunk("include");
5124 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5125 Pattern->AddTextChunk("<");
5126 Pattern->AddPlaceholderChunk("header");
5127 Pattern->AddTextChunk(">");
5128 Results.AddResult(Pattern);
5129
5130 // #define <macro>
5131 Pattern = new CodeCompletionString;
5132 Pattern->AddTypedTextChunk("define");
5133 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5134 Pattern->AddPlaceholderChunk("macro");
5135 Results.AddResult(Pattern);
5136
5137 // #define <macro>(<args>)
5138 Pattern = new CodeCompletionString;
5139 Pattern->AddTypedTextChunk("define");
5140 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5141 Pattern->AddPlaceholderChunk("macro");
5142 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5143 Pattern->AddPlaceholderChunk("args");
5144 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5145 Results.AddResult(Pattern);
5146
5147 // #undef <macro>
5148 Pattern = new CodeCompletionString;
5149 Pattern->AddTypedTextChunk("undef");
5150 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5151 Pattern->AddPlaceholderChunk("macro");
5152 Results.AddResult(Pattern);
5153
5154 // #line <number>
5155 Pattern = new CodeCompletionString;
5156 Pattern->AddTypedTextChunk("line");
5157 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5158 Pattern->AddPlaceholderChunk("number");
5159 Results.AddResult(Pattern);
5160
5161 // #line <number> "filename"
5162 Pattern = new CodeCompletionString;
5163 Pattern->AddTypedTextChunk("line");
5164 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5165 Pattern->AddPlaceholderChunk("number");
5166 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5167 Pattern->AddTextChunk("\"");
5168 Pattern->AddPlaceholderChunk("filename");
5169 Pattern->AddTextChunk("\"");
5170 Results.AddResult(Pattern);
5171
5172 // #error <message>
5173 Pattern = new CodeCompletionString;
5174 Pattern->AddTypedTextChunk("error");
5175 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5176 Pattern->AddPlaceholderChunk("message");
5177 Results.AddResult(Pattern);
5178
5179 // #pragma <arguments>
5180 Pattern = new CodeCompletionString;
5181 Pattern->AddTypedTextChunk("pragma");
5182 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5183 Pattern->AddPlaceholderChunk("arguments");
5184 Results.AddResult(Pattern);
5185
5186 if (getLangOptions().ObjC1) {
5187 // #import "header"
5188 Pattern = new CodeCompletionString;
5189 Pattern->AddTypedTextChunk("import");
5190 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5191 Pattern->AddTextChunk("\"");
5192 Pattern->AddPlaceholderChunk("header");
5193 Pattern->AddTextChunk("\"");
5194 Results.AddResult(Pattern);
5195
5196 // #import <header>
5197 Pattern = new CodeCompletionString;
5198 Pattern->AddTypedTextChunk("import");
5199 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5200 Pattern->AddTextChunk("<");
5201 Pattern->AddPlaceholderChunk("header");
5202 Pattern->AddTextChunk(">");
5203 Results.AddResult(Pattern);
5204 }
5205
5206 // #include_next "header"
5207 Pattern = new CodeCompletionString;
5208 Pattern->AddTypedTextChunk("include_next");
5209 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5210 Pattern->AddTextChunk("\"");
5211 Pattern->AddPlaceholderChunk("header");
5212 Pattern->AddTextChunk("\"");
5213 Results.AddResult(Pattern);
5214
5215 // #include_next <header>
5216 Pattern = new CodeCompletionString;
5217 Pattern->AddTypedTextChunk("include_next");
5218 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5219 Pattern->AddTextChunk("<");
5220 Pattern->AddPlaceholderChunk("header");
5221 Pattern->AddTextChunk(">");
5222 Results.AddResult(Pattern);
5223
5224 // #warning <message>
5225 Pattern = new CodeCompletionString;
5226 Pattern->AddTypedTextChunk("warning");
5227 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5228 Pattern->AddPlaceholderChunk("message");
5229 Results.AddResult(Pattern);
5230
5231 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5232 // completions for them. And __include_macros is a Clang-internal extension
5233 // that we don't want to encourage anyone to use.
5234
5235 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5236 Results.ExitScope();
5237
Douglas Gregorf44e8542010-08-24 19:08:16 +00005238 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005239 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005240 Results.data(), Results.size());
5241}
5242
5243void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005244 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005245 S->getFnParent()? Sema::PCC_RecoveryInFunction
5246 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005247}
5248
Douglas Gregorf29c5232010-08-24 22:20:20 +00005249void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005250 ResultBuilder Results(*this);
5251 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5252 // Add just the names of macros, not their arguments.
5253 Results.EnterNewScope();
5254 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5255 MEnd = PP.macro_end();
5256 M != MEnd; ++M) {
5257 CodeCompletionString *Pattern = new CodeCompletionString;
5258 Pattern->AddTypedTextChunk(M->first->getName());
5259 Results.AddResult(Pattern);
5260 }
5261 Results.ExitScope();
5262 } else if (IsDefinition) {
5263 // FIXME: Can we detect when the user just wrote an include guard above?
5264 }
5265
5266 HandleCodeCompleteResults(this, CodeCompleter,
5267 IsDefinition? CodeCompletionContext::CCC_MacroName
5268 : CodeCompletionContext::CCC_MacroNameUse,
5269 Results.data(), Results.size());
5270}
5271
Douglas Gregorf29c5232010-08-24 22:20:20 +00005272void Sema::CodeCompletePreprocessorExpression() {
5273 ResultBuilder Results(*this);
5274
5275 if (!CodeCompleter || CodeCompleter->includeMacros())
5276 AddMacroResults(PP, Results);
5277
5278 // defined (<macro>)
5279 Results.EnterNewScope();
5280 CodeCompletionString *Pattern = new CodeCompletionString;
5281 Pattern->AddTypedTextChunk("defined");
5282 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5283 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5284 Pattern->AddPlaceholderChunk("macro");
5285 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5286 Results.AddResult(Pattern);
5287 Results.ExitScope();
5288
5289 HandleCodeCompleteResults(this, CodeCompleter,
5290 CodeCompletionContext::CCC_PreprocessorExpression,
5291 Results.data(), Results.size());
5292}
5293
5294void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5295 IdentifierInfo *Macro,
5296 MacroInfo *MacroInfo,
5297 unsigned Argument) {
5298 // FIXME: In the future, we could provide "overload" results, much like we
5299 // do for function calls.
5300
5301 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005302 S->getFnParent()? Sema::PCC_RecoveryInFunction
5303 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005304}
5305
Douglas Gregor55817af2010-08-25 17:04:25 +00005306void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005307 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005308 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005309 0, 0);
5310}
5311
Douglas Gregor87c08a52010-08-13 22:48:40 +00005312void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00005313 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor87c08a52010-08-13 22:48:40 +00005314 ResultBuilder Builder(*this);
5315
Douglas Gregor8071e422010-08-15 06:18:01 +00005316 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5317 CodeCompletionDeclConsumer Consumer(Builder,
5318 Context.getTranslationUnitDecl());
5319 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5320 Consumer);
5321 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005322
5323 if (!CodeCompleter || CodeCompleter->includeMacros())
5324 AddMacroResults(PP, Builder);
5325
5326 Results.clear();
5327 Results.insert(Results.end(),
5328 Builder.data(), Builder.data() + Builder.size());
5329}