blob: b75a7d05bba9946a7d7595e267f5086c4d3ef25f [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 Gregor1f5537a2010-07-08 23:20:03 +0000139 void AdjustResultPriorityForPreferredType(Result &R);
140
Douglas Gregor86d9a522009-09-21 16:56:56 +0000141 public:
142 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor45bcd432010-01-14 03:21:49 +0000143 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000144
Douglas Gregord8e8a582010-05-25 21:41:55 +0000145 /// \brief Whether we should include code patterns in the completion
146 /// results.
147 bool includeCodePatterns() const {
148 return SemaRef.CodeCompleter &&
149 SemaRef.CodeCompleter->includeCodePatterns();
150 }
151
Douglas Gregor86d9a522009-09-21 16:56:56 +0000152 /// \brief Set the filter used for code-completion results.
153 void setFilter(LookupFilter Filter) {
154 this->Filter = Filter;
155 }
156
157 typedef std::vector<Result>::iterator iterator;
158 iterator begin() { return Results.begin(); }
159 iterator end() { return Results.end(); }
160
161 Result *data() { return Results.empty()? 0 : &Results.front(); }
162 unsigned size() const { return Results.size(); }
163 bool empty() const { return Results.empty(); }
164
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000165 /// \brief Specify the preferred type.
166 void setPreferredType(QualType T) {
167 PreferredType = SemaRef.Context.getCanonicalType(T);
168 }
169
Douglas Gregor45bcd432010-01-14 03:21:49 +0000170 /// \brief Specify whether nested-name-specifiers are allowed.
171 void allowNestedNameSpecifiers(bool Allow = true) {
172 AllowNestedNameSpecifiers = Allow;
173 }
174
Douglas Gregore495b7f2010-01-14 00:20:49 +0000175 /// \brief Determine whether the given declaration is at all interesting
176 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000177 ///
178 /// \param ND the declaration that we are inspecting.
179 ///
180 /// \param AsNestedNameSpecifier will be set true if this declaration is
181 /// only interesting when it is a nested-name-specifier.
182 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000183
184 /// \brief Check whether the result is hidden by the Hiding declaration.
185 ///
186 /// \returns true if the result is hidden and cannot be found, false if
187 /// the hidden result could still be found. When false, \p R may be
188 /// modified to describe how the result can be found (e.g., via extra
189 /// qualification).
190 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
191 NamedDecl *Hiding);
192
Douglas Gregor86d9a522009-09-21 16:56:56 +0000193 /// \brief Add a new result to this result set (if it isn't already in one
194 /// of the shadow maps), or replace an existing result (for, e.g., a
195 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000196 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000197 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000198 ///
199 /// \param R the context in which this result will be named.
200 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000201
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000202 /// \brief Add a new result to this result set, where we already know
203 /// the hiding declation (if any).
204 ///
205 /// \param R the result to add (if it is unique).
206 ///
207 /// \param CurContext the context in which this result will be named.
208 ///
209 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000210 ///
211 /// \param InBaseClass whether the result was found in a base
212 /// class of the searched context.
213 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
214 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000215
Douglas Gregora4477812010-01-14 16:01:26 +0000216 /// \brief Add a new non-declaration result to this result set.
217 void AddResult(Result R);
218
Douglas Gregor86d9a522009-09-21 16:56:56 +0000219 /// \brief Enter into a new scope.
220 void EnterNewScope();
221
222 /// \brief Exit from the current scope.
223 void ExitScope();
224
Douglas Gregor55385fe2009-11-18 04:19:12 +0000225 /// \brief Ignore this declaration, if it is seen again.
226 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
227
Douglas Gregor86d9a522009-09-21 16:56:56 +0000228 /// \name Name lookup predicates
229 ///
230 /// These predicates can be passed to the name lookup functions to filter the
231 /// results of name lookup. All of the predicates have the same type, so that
232 ///
233 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000234 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000235 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000236 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000237 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000238 bool IsNestedNameSpecifier(NamedDecl *ND) const;
239 bool IsEnum(NamedDecl *ND) const;
240 bool IsClassOrStruct(NamedDecl *ND) const;
241 bool IsUnion(NamedDecl *ND) const;
242 bool IsNamespace(NamedDecl *ND) const;
243 bool IsNamespaceOrAlias(NamedDecl *ND) const;
244 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000245 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000246 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000247 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000248 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000249 //@}
250 };
251}
252
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000253class ResultBuilder::ShadowMapEntry::iterator {
254 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
255 unsigned SingleDeclIndex;
256
257public:
258 typedef DeclIndexPair value_type;
259 typedef value_type reference;
260 typedef std::ptrdiff_t difference_type;
261 typedef std::input_iterator_tag iterator_category;
262
263 class pointer {
264 DeclIndexPair Value;
265
266 public:
267 pointer(const DeclIndexPair &Value) : Value(Value) { }
268
269 const DeclIndexPair *operator->() const {
270 return &Value;
271 }
272 };
273
274 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
275
276 iterator(NamedDecl *SingleDecl, unsigned Index)
277 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
278
279 iterator(const DeclIndexPair *Iterator)
280 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
281
282 iterator &operator++() {
283 if (DeclOrIterator.is<NamedDecl *>()) {
284 DeclOrIterator = (NamedDecl *)0;
285 SingleDeclIndex = 0;
286 return *this;
287 }
288
289 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
290 ++I;
291 DeclOrIterator = I;
292 return *this;
293 }
294
295 iterator operator++(int) {
296 iterator tmp(*this);
297 ++(*this);
298 return tmp;
299 }
300
301 reference operator*() const {
302 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
303 return reference(ND, SingleDeclIndex);
304
Douglas Gregord490f952009-12-06 21:27:58 +0000305 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000306 }
307
308 pointer operator->() const {
309 return pointer(**this);
310 }
311
312 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000313 return X.DeclOrIterator.getOpaqueValue()
314 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000315 X.SingleDeclIndex == Y.SingleDeclIndex;
316 }
317
318 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000319 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000320 }
321};
322
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000323ResultBuilder::ShadowMapEntry::iterator
324ResultBuilder::ShadowMapEntry::begin() const {
325 if (DeclOrVector.isNull())
326 return iterator();
327
328 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
329 return iterator(ND, SingleDeclIndex);
330
331 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
332}
333
334ResultBuilder::ShadowMapEntry::iterator
335ResultBuilder::ShadowMapEntry::end() const {
336 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
337 return iterator();
338
339 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
340}
341
Douglas Gregor456c4a12009-09-21 20:12:40 +0000342/// \brief Compute the qualification required to get from the current context
343/// (\p CurContext) to the target context (\p TargetContext).
344///
345/// \param Context the AST context in which the qualification will be used.
346///
347/// \param CurContext the context where an entity is being named, which is
348/// typically based on the current scope.
349///
350/// \param TargetContext the context in which the named entity actually
351/// resides.
352///
353/// \returns a nested name specifier that refers into the target context, or
354/// NULL if no qualification is needed.
355static NestedNameSpecifier *
356getRequiredQualification(ASTContext &Context,
357 DeclContext *CurContext,
358 DeclContext *TargetContext) {
359 llvm::SmallVector<DeclContext *, 4> TargetParents;
360
361 for (DeclContext *CommonAncestor = TargetContext;
362 CommonAncestor && !CommonAncestor->Encloses(CurContext);
363 CommonAncestor = CommonAncestor->getLookupParent()) {
364 if (CommonAncestor->isTransparentContext() ||
365 CommonAncestor->isFunctionOrMethod())
366 continue;
367
368 TargetParents.push_back(CommonAncestor);
369 }
370
371 NestedNameSpecifier *Result = 0;
372 while (!TargetParents.empty()) {
373 DeclContext *Parent = TargetParents.back();
374 TargetParents.pop_back();
375
Douglas Gregorfb629412010-08-23 21:17:50 +0000376 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
377 if (!Namespace->getIdentifier())
378 continue;
379
Douglas Gregor456c4a12009-09-21 20:12:40 +0000380 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000381 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000382 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
383 Result = NestedNameSpecifier::Create(Context, Result,
384 false,
385 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000386 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000387 return Result;
388}
389
Douglas Gregor45bcd432010-01-14 03:21:49 +0000390bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
391 bool &AsNestedNameSpecifier) const {
392 AsNestedNameSpecifier = false;
393
Douglas Gregore495b7f2010-01-14 00:20:49 +0000394 ND = ND->getUnderlyingDecl();
395 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000396
397 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000398 if (!ND->getDeclName())
399 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000400
401 // Friend declarations and declarations introduced due to friends are never
402 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000403 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000404 return false;
405
Douglas Gregor76282942009-12-11 17:31:05 +0000406 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000407 if (isa<ClassTemplateSpecializationDecl>(ND) ||
408 isa<ClassTemplatePartialSpecializationDecl>(ND))
409 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000410
Douglas Gregor76282942009-12-11 17:31:05 +0000411 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000412 if (isa<UsingDecl>(ND))
413 return false;
414
415 // Some declarations have reserved names that we don't want to ever show.
416 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000417 // __va_list_tag is a freak of nature. Find it and skip it.
418 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000419 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000420
Douglas Gregorf52cede2009-10-09 22:16:47 +0000421 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000422 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000423 //
424 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000425 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000426 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000427 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000428 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
429 (ND->getLocation().isInvalid() ||
430 SemaRef.SourceMgr.isInSystemHeader(
431 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000432 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000433 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000434 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000435
Douglas Gregor86d9a522009-09-21 16:56:56 +0000436 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000437 if (isa<CXXConstructorDecl>(ND))
438 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000439
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000440 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
441 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
442 Filter != &ResultBuilder::IsNamespace &&
443 Filter != &ResultBuilder::IsNamespaceOrAlias))
444 AsNestedNameSpecifier = true;
445
Douglas Gregor86d9a522009-09-21 16:56:56 +0000446 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000447 if (Filter && !(this->*Filter)(ND)) {
448 // Check whether it is interesting as a nested-name-specifier.
449 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
450 IsNestedNameSpecifier(ND) &&
451 (Filter != &ResultBuilder::IsMember ||
452 (isa<CXXRecordDecl>(ND) &&
453 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
454 AsNestedNameSpecifier = true;
455 return true;
456 }
457
Douglas Gregore495b7f2010-01-14 00:20:49 +0000458 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000459 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000460 // ... then it must be interesting!
461 return true;
462}
463
Douglas Gregor6660d842010-01-14 00:41:07 +0000464bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
465 NamedDecl *Hiding) {
466 // In C, there is no way to refer to a hidden name.
467 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
468 // name if we introduce the tag type.
469 if (!SemaRef.getLangOptions().CPlusPlus)
470 return true;
471
472 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
473
474 // There is no way to qualify a name declared in a function or method.
475 if (HiddenCtx->isFunctionOrMethod())
476 return true;
477
478 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
479 return true;
480
481 // We can refer to the result with the appropriate qualification. Do it.
482 R.Hidden = true;
483 R.QualifierIsInformative = false;
484
485 if (!R.Qualifier)
486 R.Qualifier = getRequiredQualification(SemaRef.Context,
487 CurContext,
488 R.Declaration->getDeclContext());
489 return false;
490}
491
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000492/// \brief A simplified classification of types used to determine whether two
493/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000494SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000495 switch (T->getTypeClass()) {
496 case Type::Builtin:
497 switch (cast<BuiltinType>(T)->getKind()) {
498 case BuiltinType::Void:
499 return STC_Void;
500
501 case BuiltinType::NullPtr:
502 return STC_Pointer;
503
504 case BuiltinType::Overload:
505 case BuiltinType::Dependent:
506 case BuiltinType::UndeducedAuto:
507 return STC_Other;
508
509 case BuiltinType::ObjCId:
510 case BuiltinType::ObjCClass:
511 case BuiltinType::ObjCSel:
512 return STC_ObjectiveC;
513
514 default:
515 return STC_Arithmetic;
516 }
517 return STC_Other;
518
519 case Type::Complex:
520 return STC_Arithmetic;
521
522 case Type::Pointer:
523 return STC_Pointer;
524
525 case Type::BlockPointer:
526 return STC_Block;
527
528 case Type::LValueReference:
529 case Type::RValueReference:
530 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
531
532 case Type::ConstantArray:
533 case Type::IncompleteArray:
534 case Type::VariableArray:
535 case Type::DependentSizedArray:
536 return STC_Array;
537
538 case Type::DependentSizedExtVector:
539 case Type::Vector:
540 case Type::ExtVector:
541 return STC_Arithmetic;
542
543 case Type::FunctionProto:
544 case Type::FunctionNoProto:
545 return STC_Function;
546
547 case Type::Record:
548 return STC_Record;
549
550 case Type::Enum:
551 return STC_Arithmetic;
552
553 case Type::ObjCObject:
554 case Type::ObjCInterface:
555 case Type::ObjCObjectPointer:
556 return STC_ObjectiveC;
557
558 default:
559 return STC_Other;
560 }
561}
562
563/// \brief Get the type that a given expression will have if this declaration
564/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000565QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000566 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
567
568 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
569 return C.getTypeDeclType(Type);
570 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
571 return C.getObjCInterfaceType(Iface);
572
573 QualType T;
574 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000575 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000576 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000577 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000579 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000580 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
581 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
582 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
583 T = Property->getType();
584 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
585 T = Value->getType();
586 else
587 return QualType();
588
589 return T.getNonReferenceType();
590}
591
592void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
593 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
594 if (T.isNull())
595 return;
596
597 CanQualType TC = SemaRef.Context.getCanonicalType(T);
598 // Check for exactly-matching types (modulo qualifiers).
Douglas Gregoreb0d0142010-08-24 23:58:17 +0000599 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) {
600 if (PreferredType->isVoidType())
601 R.Priority += CCD_VoidMatch;
602 else
603 R.Priority /= CCF_ExactTypeMatch;
604 } // Check for nearly-matching types, based on classification of each.
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000605 else if ((getSimplifiedTypeClass(PreferredType)
606 == getSimplifiedTypeClass(TC)) &&
607 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
608 R.Priority /= CCF_SimilarTypeMatch;
609}
610
Douglas Gregore495b7f2010-01-14 00:20:49 +0000611void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
612 assert(!ShadowMaps.empty() && "Must enter into a results scope");
613
614 if (R.Kind != Result::RK_Declaration) {
615 // For non-declaration results, just add the result.
616 Results.push_back(R);
617 return;
618 }
619
620 // Look through using declarations.
621 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
622 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
623 return;
624 }
625
626 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
627 unsigned IDNS = CanonDecl->getIdentifierNamespace();
628
Douglas Gregor45bcd432010-01-14 03:21:49 +0000629 bool AsNestedNameSpecifier = false;
630 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000631 return;
632
Douglas Gregor86d9a522009-09-21 16:56:56 +0000633 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000634 ShadowMapEntry::iterator I, IEnd;
635 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
636 if (NamePos != SMap.end()) {
637 I = NamePos->second.begin();
638 IEnd = NamePos->second.end();
639 }
640
641 for (; I != IEnd; ++I) {
642 NamedDecl *ND = I->first;
643 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000644 if (ND->getCanonicalDecl() == CanonDecl) {
645 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000646 Results[Index].Declaration = R.Declaration;
647
Douglas Gregor86d9a522009-09-21 16:56:56 +0000648 // We're done.
649 return;
650 }
651 }
652
653 // This is a new declaration in this scope. However, check whether this
654 // declaration name is hidden by a similarly-named declaration in an outer
655 // scope.
656 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
657 --SMEnd;
658 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000659 ShadowMapEntry::iterator I, IEnd;
660 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
661 if (NamePos != SM->end()) {
662 I = NamePos->second.begin();
663 IEnd = NamePos->second.end();
664 }
665 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000666 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000667 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000668 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
669 Decl::IDNS_ObjCProtocol)))
670 continue;
671
672 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000673 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000674 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000675 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000676 continue;
677
678 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000679 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000680 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000681
682 break;
683 }
684 }
685
686 // Make sure that any given declaration only shows up in the result set once.
687 if (!AllDeclsFound.insert(CanonDecl))
688 return;
689
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000690 // If the filter is for nested-name-specifiers, then this result starts a
691 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000692 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000693 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000694 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000695 } else if (!PreferredType.isNull())
696 AdjustResultPriorityForPreferredType(R);
697
Douglas Gregor0563c262009-09-22 23:15:58 +0000698 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000699 if (R.QualifierIsInformative && !R.Qualifier &&
700 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000701 DeclContext *Ctx = R.Declaration->getDeclContext();
702 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
703 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
704 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
705 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
706 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
707 else
708 R.QualifierIsInformative = false;
709 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000710
Douglas Gregor86d9a522009-09-21 16:56:56 +0000711 // Insert this result into the set of results and into the current shadow
712 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000713 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000714 Results.push_back(R);
715}
716
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000717void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000718 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000719 if (R.Kind != Result::RK_Declaration) {
720 // For non-declaration results, just add the result.
721 Results.push_back(R);
722 return;
723 }
724
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000725 // Look through using declarations.
726 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
727 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
728 return;
729 }
730
Douglas Gregor45bcd432010-01-14 03:21:49 +0000731 bool AsNestedNameSpecifier = false;
732 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000733 return;
734
735 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
736 return;
737
738 // Make sure that any given declaration only shows up in the result set once.
739 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
740 return;
741
742 // If the filter is for nested-name-specifiers, then this result starts a
743 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000744 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000745 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000746 R.Priority = CCP_NestedNameSpecifier;
747 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000748 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
749 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
750 ->getLookupContext()))
751 R.QualifierIsInformative = true;
752
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000753 // If this result is supposed to have an informative qualifier, add one.
754 if (R.QualifierIsInformative && !R.Qualifier &&
755 !R.StartsNestedNameSpecifier) {
756 DeclContext *Ctx = R.Declaration->getDeclContext();
757 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
758 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
759 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
760 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000761 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000762 else
763 R.QualifierIsInformative = false;
764 }
765
Douglas Gregor12e13132010-05-26 22:00:08 +0000766 // Adjust the priority if this result comes from a base class.
767 if (InBaseClass)
768 R.Priority += CCD_InBaseClass;
769
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000770 if (!PreferredType.isNull())
771 AdjustResultPriorityForPreferredType(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000772
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000773 // Insert this result into the set of results.
774 Results.push_back(R);
775}
776
Douglas Gregora4477812010-01-14 16:01:26 +0000777void ResultBuilder::AddResult(Result R) {
778 assert(R.Kind != Result::RK_Declaration &&
779 "Declaration results need more context");
780 Results.push_back(R);
781}
782
Douglas Gregor86d9a522009-09-21 16:56:56 +0000783/// \brief Enter into a new scope.
784void ResultBuilder::EnterNewScope() {
785 ShadowMaps.push_back(ShadowMap());
786}
787
788/// \brief Exit from the current scope.
789void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000790 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
791 EEnd = ShadowMaps.back().end();
792 E != EEnd;
793 ++E)
794 E->second.Destroy();
795
Douglas Gregor86d9a522009-09-21 16:56:56 +0000796 ShadowMaps.pop_back();
797}
798
Douglas Gregor791215b2009-09-21 20:51:25 +0000799/// \brief Determines whether this given declaration will be found by
800/// ordinary name lookup.
801bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000802 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
803
Douglas Gregor791215b2009-09-21 20:51:25 +0000804 unsigned IDNS = Decl::IDNS_Ordinary;
805 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000806 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000807 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
808 return true;
809
Douglas Gregor791215b2009-09-21 20:51:25 +0000810 return ND->getIdentifierNamespace() & IDNS;
811}
812
Douglas Gregor01dfea02010-01-10 23:08:15 +0000813/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000814/// ordinary name lookup but is not a type name.
815bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
816 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
817 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
818 return false;
819
820 unsigned IDNS = Decl::IDNS_Ordinary;
821 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000822 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000823 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
824 return true;
825
826 return ND->getIdentifierNamespace() & IDNS;
827}
828
Douglas Gregorf9578432010-07-28 21:50:18 +0000829bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
830 if (!IsOrdinaryNonTypeName(ND))
831 return 0;
832
833 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
834 if (VD->getType()->isIntegralOrEnumerationType())
835 return true;
836
837 return false;
838}
839
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000840/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000841/// ordinary name lookup.
842bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000843 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
844
Douglas Gregor01dfea02010-01-10 23:08:15 +0000845 unsigned IDNS = Decl::IDNS_Ordinary;
846 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000847 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000848
849 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000850 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
851 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000852}
853
Douglas Gregor86d9a522009-09-21 16:56:56 +0000854/// \brief Determines whether the given declaration is suitable as the
855/// start of a C++ nested-name-specifier, e.g., a class or namespace.
856bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
857 // Allow us to find class templates, too.
858 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
859 ND = ClassTemplate->getTemplatedDecl();
860
861 return SemaRef.isAcceptableNestedNameSpecifier(ND);
862}
863
864/// \brief Determines whether the given declaration is an enumeration.
865bool ResultBuilder::IsEnum(NamedDecl *ND) const {
866 return isa<EnumDecl>(ND);
867}
868
869/// \brief Determines whether the given declaration is a class or struct.
870bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
871 // Allow us to find class templates, too.
872 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
873 ND = ClassTemplate->getTemplatedDecl();
874
875 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000876 return RD->getTagKind() == TTK_Class ||
877 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878
879 return false;
880}
881
882/// \brief Determines whether the given declaration is a union.
883bool ResultBuilder::IsUnion(NamedDecl *ND) const {
884 // Allow us to find class templates, too.
885 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
886 ND = ClassTemplate->getTemplatedDecl();
887
888 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000889 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000890
891 return false;
892}
893
894/// \brief Determines whether the given declaration is a namespace.
895bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
896 return isa<NamespaceDecl>(ND);
897}
898
899/// \brief Determines whether the given declaration is a namespace or
900/// namespace alias.
901bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
902 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
903}
904
Douglas Gregor76282942009-12-11 17:31:05 +0000905/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000906bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +0000907 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
908 ND = Using->getTargetDecl();
909
910 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000911}
912
Douglas Gregor76282942009-12-11 17:31:05 +0000913/// \brief Determines which members of a class should be visible via
914/// "." or "->". Only value declarations, nested name specifiers, and
915/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000916bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000917 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
918 ND = Using->getTargetDecl();
919
Douglas Gregorce821962009-12-11 18:14:22 +0000920 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
921 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000922}
923
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000924static bool isObjCReceiverType(ASTContext &C, QualType T) {
925 T = C.getCanonicalType(T);
926 switch (T->getTypeClass()) {
927 case Type::ObjCObject:
928 case Type::ObjCInterface:
929 case Type::ObjCObjectPointer:
930 return true;
931
932 case Type::Builtin:
933 switch (cast<BuiltinType>(T)->getKind()) {
934 case BuiltinType::ObjCId:
935 case BuiltinType::ObjCClass:
936 case BuiltinType::ObjCSel:
937 return true;
938
939 default:
940 break;
941 }
942 return false;
943
944 default:
945 break;
946 }
947
948 if (!C.getLangOptions().CPlusPlus)
949 return false;
950
951 // FIXME: We could perform more analysis here to determine whether a
952 // particular class type has any conversions to Objective-C types. For now,
953 // just accept all class types.
954 return T->isDependentType() || T->isRecordType();
955}
956
957bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
958 QualType T = getDeclUsageType(SemaRef.Context, ND);
959 if (T.isNull())
960 return false;
961
962 T = SemaRef.Context.getBaseElementType(T);
963 return isObjCReceiverType(SemaRef.Context, T);
964}
965
Douglas Gregorfb629412010-08-23 21:17:50 +0000966bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
967 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
968 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
969 return false;
970
971 QualType T = getDeclUsageType(SemaRef.Context, ND);
972 if (T.isNull())
973 return false;
974
975 T = SemaRef.Context.getBaseElementType(T);
976 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
977 T->isObjCIdType() ||
978 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
979}
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000980
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000981/// \rief Determines whether the given declaration is an Objective-C
982/// instance variable.
983bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
984 return isa<ObjCIvarDecl>(ND);
985}
986
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000987namespace {
988 /// \brief Visible declaration consumer that adds a code-completion result
989 /// for each visible declaration.
990 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
991 ResultBuilder &Results;
992 DeclContext *CurContext;
993
994 public:
995 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
996 : Results(Results), CurContext(CurContext) { }
997
Douglas Gregor0cc84042010-01-14 15:47:35 +0000998 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
999 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001000 }
1001 };
1002}
1003
Douglas Gregor86d9a522009-09-21 16:56:56 +00001004/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001005static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001006 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001007 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001008 Results.AddResult(Result("short", CCP_Type));
1009 Results.AddResult(Result("long", CCP_Type));
1010 Results.AddResult(Result("signed", CCP_Type));
1011 Results.AddResult(Result("unsigned", CCP_Type));
1012 Results.AddResult(Result("void", CCP_Type));
1013 Results.AddResult(Result("char", CCP_Type));
1014 Results.AddResult(Result("int", CCP_Type));
1015 Results.AddResult(Result("float", CCP_Type));
1016 Results.AddResult(Result("double", CCP_Type));
1017 Results.AddResult(Result("enum", CCP_Type));
1018 Results.AddResult(Result("struct", CCP_Type));
1019 Results.AddResult(Result("union", CCP_Type));
1020 Results.AddResult(Result("const", CCP_Type));
1021 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001022
Douglas Gregor86d9a522009-09-21 16:56:56 +00001023 if (LangOpts.C99) {
1024 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001025 Results.AddResult(Result("_Complex", CCP_Type));
1026 Results.AddResult(Result("_Imaginary", CCP_Type));
1027 Results.AddResult(Result("_Bool", CCP_Type));
1028 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001029 }
1030
1031 if (LangOpts.CPlusPlus) {
1032 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001033 Results.AddResult(Result("bool", CCP_Type));
1034 Results.AddResult(Result("class", CCP_Type));
1035 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001036
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001037 // typename qualified-id
1038 CodeCompletionString *Pattern = new CodeCompletionString;
1039 Pattern->AddTypedTextChunk("typename");
1040 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1041 Pattern->AddPlaceholderChunk("qualifier");
1042 Pattern->AddTextChunk("::");
1043 Pattern->AddPlaceholderChunk("name");
1044 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001045
Douglas Gregor86d9a522009-09-21 16:56:56 +00001046 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001047 Results.AddResult(Result("auto", CCP_Type));
1048 Results.AddResult(Result("char16_t", CCP_Type));
1049 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001050
1051 CodeCompletionString *Pattern = new CodeCompletionString;
1052 Pattern->AddTypedTextChunk("decltype");
1053 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1054 Pattern->AddPlaceholderChunk("expression");
1055 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1056 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001057 }
1058 }
1059
1060 // GNU extensions
1061 if (LangOpts.GNUMode) {
1062 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001063 // Results.AddResult(Result("_Decimal32"));
1064 // Results.AddResult(Result("_Decimal64"));
1065 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001066
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001067 CodeCompletionString *Pattern = new CodeCompletionString;
1068 Pattern->AddTypedTextChunk("typeof");
1069 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1070 Pattern->AddPlaceholderChunk("expression");
1071 Results.AddResult(Result(Pattern));
1072
1073 Pattern = new CodeCompletionString;
1074 Pattern->AddTypedTextChunk("typeof");
1075 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1076 Pattern->AddPlaceholderChunk("type");
1077 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1078 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001079 }
1080}
1081
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001082static void AddStorageSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001083 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001084 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001085 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001086 // Note: we don't suggest either "auto" or "register", because both
1087 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1088 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001089 Results.AddResult(Result("extern"));
1090 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001091}
1092
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001093static void AddFunctionSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001094 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001095 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001096 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001097 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001098 case Action::PCC_Class:
1099 case Action::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001100 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001101 Results.AddResult(Result("explicit"));
1102 Results.AddResult(Result("friend"));
1103 Results.AddResult(Result("mutable"));
1104 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001105 }
1106 // Fall through
1107
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001108 case Action::PCC_ObjCInterface:
1109 case Action::PCC_ObjCImplementation:
1110 case Action::PCC_Namespace:
1111 case Action::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001112 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001113 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001114 break;
1115
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001116 case Action::PCC_ObjCInstanceVariableList:
1117 case Action::PCC_Expression:
1118 case Action::PCC_Statement:
1119 case Action::PCC_ForInit:
1120 case Action::PCC_Condition:
1121 case Action::PCC_RecoveryInFunction:
Douglas Gregord32b0222010-08-24 01:06:58 +00001122 case Action::PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001123 break;
1124 }
1125}
1126
Douglas Gregorbca403c2010-01-13 23:51:12 +00001127static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1128static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1129static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001130 ResultBuilder &Results,
1131 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001132static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001133 ResultBuilder &Results,
1134 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001135static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001136 ResultBuilder &Results,
1137 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001138static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001139
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001140static void AddTypedefResult(ResultBuilder &Results) {
1141 CodeCompletionString *Pattern = new CodeCompletionString;
1142 Pattern->AddTypedTextChunk("typedef");
1143 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1144 Pattern->AddPlaceholderChunk("type");
1145 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1146 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001147 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001148}
1149
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001150static bool WantTypesInContext(Action::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001151 const LangOptions &LangOpts) {
1152 if (LangOpts.CPlusPlus)
1153 return true;
1154
1155 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001156 case Action::PCC_Namespace:
1157 case Action::PCC_Class:
1158 case Action::PCC_ObjCInstanceVariableList:
1159 case Action::PCC_Template:
1160 case Action::PCC_MemberTemplate:
1161 case Action::PCC_Statement:
1162 case Action::PCC_RecoveryInFunction:
Douglas Gregord32b0222010-08-24 01:06:58 +00001163 case Action::PCC_Type:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001164 return true;
1165
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001166 case Action::PCC_ObjCInterface:
1167 case Action::PCC_ObjCImplementation:
1168 case Action::PCC_Expression:
1169 case Action::PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001170 return false;
1171
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001172 case Action::PCC_ForInit:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001173 return LangOpts.ObjC1 || LangOpts.C99;
1174 }
1175
1176 return false;
1177}
1178
Douglas Gregor01dfea02010-01-10 23:08:15 +00001179/// \brief Add language constructs that show up for "ordinary" names.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001180static void AddOrdinaryNameResults(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001181 Scope *S,
1182 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001183 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001184 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001185 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001186 case Action::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001187 if (SemaRef.getLangOptions().CPlusPlus) {
1188 CodeCompletionString *Pattern = 0;
1189
1190 if (Results.includeCodePatterns()) {
1191 // namespace <identifier> { declarations }
1192 CodeCompletionString *Pattern = new CodeCompletionString;
1193 Pattern->AddTypedTextChunk("namespace");
1194 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1195 Pattern->AddPlaceholderChunk("identifier");
1196 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1197 Pattern->AddPlaceholderChunk("declarations");
1198 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1199 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1200 Results.AddResult(Result(Pattern));
1201 }
1202
Douglas Gregor01dfea02010-01-10 23:08:15 +00001203 // namespace identifier = identifier ;
1204 Pattern = new CodeCompletionString;
1205 Pattern->AddTypedTextChunk("namespace");
1206 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001207 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001208 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001209 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001210 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001211
1212 // Using directives
1213 Pattern = new CodeCompletionString;
1214 Pattern->AddTypedTextChunk("using");
1215 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1216 Pattern->AddTextChunk("namespace");
1217 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1218 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001219 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001220
1221 // asm(string-literal)
1222 Pattern = new CodeCompletionString;
1223 Pattern->AddTypedTextChunk("asm");
1224 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1225 Pattern->AddPlaceholderChunk("string-literal");
1226 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001227 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001228
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001229 if (Results.includeCodePatterns()) {
1230 // Explicit template instantiation
1231 Pattern = new CodeCompletionString;
1232 Pattern->AddTypedTextChunk("template");
1233 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1234 Pattern->AddPlaceholderChunk("declaration");
1235 Results.AddResult(Result(Pattern));
1236 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001237 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001238
1239 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001240 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001241
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001242 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001243 // Fall through
1244
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001245 case Action::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001246 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001247 // Using declaration
1248 CodeCompletionString *Pattern = new CodeCompletionString;
1249 Pattern->AddTypedTextChunk("using");
1250 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001251 Pattern->AddPlaceholderChunk("qualifier");
1252 Pattern->AddTextChunk("::");
1253 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001254 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001255
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001256 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001257 if (SemaRef.CurContext->isDependentContext()) {
1258 Pattern = new CodeCompletionString;
1259 Pattern->AddTypedTextChunk("using");
1260 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1261 Pattern->AddTextChunk("typename");
1262 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001263 Pattern->AddPlaceholderChunk("qualifier");
1264 Pattern->AddTextChunk("::");
1265 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001266 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001267 }
1268
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001269 if (CCC == Action::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001270 AddTypedefResult(Results);
1271
Douglas Gregor01dfea02010-01-10 23:08:15 +00001272 // public:
1273 Pattern = new CodeCompletionString;
1274 Pattern->AddTypedTextChunk("public");
1275 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001276 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001277
1278 // protected:
1279 Pattern = new CodeCompletionString;
1280 Pattern->AddTypedTextChunk("protected");
1281 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001282 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283
1284 // private:
1285 Pattern = new CodeCompletionString;
1286 Pattern->AddTypedTextChunk("private");
1287 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001288 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 }
1290 }
1291 // Fall through
1292
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001293 case Action::PCC_Template:
1294 case Action::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001295 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001296 // template < parameters >
1297 CodeCompletionString *Pattern = new CodeCompletionString;
1298 Pattern->AddTypedTextChunk("template");
1299 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1300 Pattern->AddPlaceholderChunk("parameters");
1301 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001302 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001303 }
1304
Douglas Gregorbca403c2010-01-13 23:51:12 +00001305 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1306 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 break;
1308
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001309 case Action::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001310 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1311 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1312 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001313 break;
1314
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001315 case Action::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001316 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1317 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1318 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001319 break;
1320
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001321 case Action::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001322 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001323 break;
1324
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001325 case Action::PCC_RecoveryInFunction:
1326 case Action::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001327 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001328
1329 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001330 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001331 Pattern = new CodeCompletionString;
1332 Pattern->AddTypedTextChunk("try");
1333 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1334 Pattern->AddPlaceholderChunk("statements");
1335 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1336 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1337 Pattern->AddTextChunk("catch");
1338 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1339 Pattern->AddPlaceholderChunk("declaration");
1340 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1341 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1342 Pattern->AddPlaceholderChunk("statements");
1343 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1344 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001345 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001346 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001347 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001348 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001349
Douglas Gregord8e8a582010-05-25 21:41:55 +00001350 if (Results.includeCodePatterns()) {
1351 // if (condition) { statements }
1352 Pattern = new CodeCompletionString;
1353 Pattern->AddTypedTextChunk("if");
1354 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1355 if (SemaRef.getLangOptions().CPlusPlus)
1356 Pattern->AddPlaceholderChunk("condition");
1357 else
1358 Pattern->AddPlaceholderChunk("expression");
1359 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1360 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1361 Pattern->AddPlaceholderChunk("statements");
1362 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1363 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1364 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001365
Douglas Gregord8e8a582010-05-25 21:41:55 +00001366 // switch (condition) { }
1367 Pattern = new CodeCompletionString;
1368 Pattern->AddTypedTextChunk("switch");
1369 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1370 if (SemaRef.getLangOptions().CPlusPlus)
1371 Pattern->AddPlaceholderChunk("condition");
1372 else
1373 Pattern->AddPlaceholderChunk("expression");
1374 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1375 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1376 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1377 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1378 Results.AddResult(Result(Pattern));
1379 }
1380
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001382 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001383 // case expression:
1384 Pattern = new CodeCompletionString;
1385 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001386 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001387 Pattern->AddPlaceholderChunk("expression");
1388 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001389 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001390
1391 // default:
1392 Pattern = new CodeCompletionString;
1393 Pattern->AddTypedTextChunk("default");
1394 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001395 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001396 }
1397
Douglas Gregord8e8a582010-05-25 21:41:55 +00001398 if (Results.includeCodePatterns()) {
1399 /// while (condition) { statements }
1400 Pattern = new CodeCompletionString;
1401 Pattern->AddTypedTextChunk("while");
1402 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1403 if (SemaRef.getLangOptions().CPlusPlus)
1404 Pattern->AddPlaceholderChunk("condition");
1405 else
1406 Pattern->AddPlaceholderChunk("expression");
1407 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1408 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1409 Pattern->AddPlaceholderChunk("statements");
1410 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1411 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1412 Results.AddResult(Result(Pattern));
1413
1414 // do { statements } while ( expression );
1415 Pattern = new CodeCompletionString;
1416 Pattern->AddTypedTextChunk("do");
1417 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1418 Pattern->AddPlaceholderChunk("statements");
1419 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1420 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1421 Pattern->AddTextChunk("while");
1422 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001423 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001424 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1425 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001426
Douglas Gregord8e8a582010-05-25 21:41:55 +00001427 // for ( for-init-statement ; condition ; expression ) { statements }
1428 Pattern = new CodeCompletionString;
1429 Pattern->AddTypedTextChunk("for");
1430 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1431 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1432 Pattern->AddPlaceholderChunk("init-statement");
1433 else
1434 Pattern->AddPlaceholderChunk("init-expression");
1435 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1436 Pattern->AddPlaceholderChunk("condition");
1437 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1438 Pattern->AddPlaceholderChunk("inc-expression");
1439 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1440 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1441 Pattern->AddPlaceholderChunk("statements");
1442 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1443 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1444 Results.AddResult(Result(Pattern));
1445 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001446
1447 if (S->getContinueParent()) {
1448 // continue ;
1449 Pattern = new CodeCompletionString;
1450 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001451 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001452 }
1453
1454 if (S->getBreakParent()) {
1455 // break ;
1456 Pattern = new CodeCompletionString;
1457 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001458 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001459 }
1460
1461 // "return expression ;" or "return ;", depending on whether we
1462 // know the function is void or not.
1463 bool isVoid = false;
1464 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1465 isVoid = Function->getResultType()->isVoidType();
1466 else if (ObjCMethodDecl *Method
1467 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1468 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001469 else if (SemaRef.getCurBlock() &&
1470 !SemaRef.getCurBlock()->ReturnType.isNull())
1471 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001472 Pattern = new CodeCompletionString;
1473 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001474 if (!isVoid) {
1475 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001476 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001477 }
Douglas Gregora4477812010-01-14 16:01:26 +00001478 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001479
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001480 // goto identifier ;
1481 Pattern = new CodeCompletionString;
1482 Pattern->AddTypedTextChunk("goto");
1483 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1484 Pattern->AddPlaceholderChunk("label");
1485 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001487 // Using directives
1488 Pattern = new CodeCompletionString;
1489 Pattern->AddTypedTextChunk("using");
1490 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1491 Pattern->AddTextChunk("namespace");
1492 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1493 Pattern->AddPlaceholderChunk("identifier");
1494 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001495 }
1496
1497 // Fall through (for statement expressions).
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001498 case Action::PCC_ForInit:
1499 case Action::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001500 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001501 // Fall through: conditions and statements can have expressions.
1502
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001503 case Action::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001504 CodeCompletionString *Pattern = 0;
1505 if (SemaRef.getLangOptions().CPlusPlus) {
1506 // 'this', if we're in a non-static member function.
1507 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1508 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001509 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001510
1511 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001512 Results.AddResult(Result("true"));
1513 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001514
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001515 // dynamic_cast < type-id > ( expression )
1516 Pattern = new CodeCompletionString;
1517 Pattern->AddTypedTextChunk("dynamic_cast");
1518 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1519 Pattern->AddPlaceholderChunk("type");
1520 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1521 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1522 Pattern->AddPlaceholderChunk("expression");
1523 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1524 Results.AddResult(Result(Pattern));
1525
1526 // static_cast < type-id > ( expression )
1527 Pattern = new CodeCompletionString;
1528 Pattern->AddTypedTextChunk("static_cast");
1529 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1530 Pattern->AddPlaceholderChunk("type");
1531 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1532 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1533 Pattern->AddPlaceholderChunk("expression");
1534 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1535 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001537 // reinterpret_cast < type-id > ( expression )
1538 Pattern = new CodeCompletionString;
1539 Pattern->AddTypedTextChunk("reinterpret_cast");
1540 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1541 Pattern->AddPlaceholderChunk("type");
1542 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1543 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1544 Pattern->AddPlaceholderChunk("expression");
1545 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1546 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001547
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001548 // const_cast < type-id > ( expression )
1549 Pattern = new CodeCompletionString;
1550 Pattern->AddTypedTextChunk("const_cast");
1551 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1552 Pattern->AddPlaceholderChunk("type");
1553 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1554 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1555 Pattern->AddPlaceholderChunk("expression");
1556 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1557 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001558
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001559 // typeid ( expression-or-type )
1560 Pattern = new CodeCompletionString;
1561 Pattern->AddTypedTextChunk("typeid");
1562 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1563 Pattern->AddPlaceholderChunk("expression-or-type");
1564 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1565 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001566
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001567 // new T ( ... )
1568 Pattern = new CodeCompletionString;
1569 Pattern->AddTypedTextChunk("new");
1570 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1571 Pattern->AddPlaceholderChunk("type");
1572 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1573 Pattern->AddPlaceholderChunk("expressions");
1574 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1575 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001576
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001577 // new T [ ] ( ... )
1578 Pattern = new CodeCompletionString;
1579 Pattern->AddTypedTextChunk("new");
1580 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1581 Pattern->AddPlaceholderChunk("type");
1582 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1583 Pattern->AddPlaceholderChunk("size");
1584 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1585 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1586 Pattern->AddPlaceholderChunk("expressions");
1587 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1588 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001589
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001590 // delete expression
1591 Pattern = new CodeCompletionString;
1592 Pattern->AddTypedTextChunk("delete");
1593 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1594 Pattern->AddPlaceholderChunk("expression");
1595 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001596
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001597 // delete [] expression
1598 Pattern = new CodeCompletionString;
1599 Pattern->AddTypedTextChunk("delete");
1600 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1601 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1602 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1603 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1604 Pattern->AddPlaceholderChunk("expression");
1605 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001607 // throw expression
1608 Pattern = new CodeCompletionString;
1609 Pattern->AddTypedTextChunk("throw");
1610 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1611 Pattern->AddPlaceholderChunk("expression");
1612 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001613
1614 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001615 }
1616
1617 if (SemaRef.getLangOptions().ObjC1) {
1618 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001619 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1620 // The interface can be NULL.
1621 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1622 if (ID->getSuperClass())
1623 Results.AddResult(Result("super"));
1624 }
1625
Douglas Gregorbca403c2010-01-13 23:51:12 +00001626 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001627 }
1628
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001629 // sizeof expression
1630 Pattern = new CodeCompletionString;
1631 Pattern->AddTypedTextChunk("sizeof");
1632 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1633 Pattern->AddPlaceholderChunk("expression-or-type");
1634 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1635 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001636 break;
1637 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001638
1639 case Action::PCC_Type:
1640 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001641 }
1642
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001643 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1644 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001645
Douglas Gregord32b0222010-08-24 01:06:58 +00001646 if (SemaRef.getLangOptions().CPlusPlus && CCC != Action::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001647 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001648}
1649
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001650/// \brief If the given declaration has an associated type, add it as a result
1651/// type chunk.
1652static void AddResultTypeChunk(ASTContext &Context,
1653 NamedDecl *ND,
1654 CodeCompletionString *Result) {
1655 if (!ND)
1656 return;
1657
1658 // Determine the type of the declaration (if it has a type).
1659 QualType T;
1660 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1661 T = Function->getResultType();
1662 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1663 T = Method->getResultType();
1664 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1665 T = FunTmpl->getTemplatedDecl()->getResultType();
1666 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1667 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1668 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1669 /* Do nothing: ignore unresolved using declarations*/
1670 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1671 T = Value->getType();
1672 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1673 T = Property->getType();
1674
1675 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1676 return;
1677
Douglas Gregor84139d62010-04-05 21:25:31 +00001678 PrintingPolicy Policy(Context.PrintingPolicy);
1679 Policy.AnonymousTagLocations = false;
1680
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001681 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001682 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001683 Result->AddResultTypeChunk(TypeStr);
1684}
1685
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001686static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1687 CodeCompletionString *Result) {
1688 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1689 if (Sentinel->getSentinel() == 0) {
1690 if (Context.getLangOptions().ObjC1 &&
1691 Context.Idents.get("nil").hasMacroDefinition())
1692 Result->AddTextChunk(", nil");
1693 else if (Context.Idents.get("NULL").hasMacroDefinition())
1694 Result->AddTextChunk(", NULL");
1695 else
1696 Result->AddTextChunk(", (void*)0");
1697 }
1698}
1699
Douglas Gregor83482d12010-08-24 16:15:59 +00001700static std::string FormatFunctionParameter(ASTContext &Context,
1701 ParmVarDecl *Param) {
1702 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1703 if (Param->getType()->isDependentType() ||
1704 !Param->getType()->isBlockPointerType()) {
1705 // The argument for a dependent or non-block parameter is a placeholder
1706 // containing that parameter's type.
1707 std::string Result;
1708
1709 if (Param->getIdentifier() && !ObjCMethodParam)
1710 Result = Param->getIdentifier()->getName();
1711
1712 Param->getType().getAsStringInternal(Result,
1713 Context.PrintingPolicy);
1714
1715 if (ObjCMethodParam) {
1716 Result = "(" + Result;
1717 Result += ")";
1718 if (Param->getIdentifier())
1719 Result += Param->getIdentifier()->getName();
1720 }
1721 return Result;
1722 }
1723
1724 // The argument for a block pointer parameter is a block literal with
1725 // the appropriate type.
1726 FunctionProtoTypeLoc *Block = 0;
1727 TypeLoc TL;
1728 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1729 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1730 while (true) {
1731 // Look through typedefs.
1732 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1733 if (TypeSourceInfo *InnerTSInfo
1734 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1735 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1736 continue;
1737 }
1738 }
1739
1740 // Look through qualified types
1741 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1742 TL = QualifiedTL->getUnqualifiedLoc();
1743 continue;
1744 }
1745
1746 // Try to get the function prototype behind the block pointer type,
1747 // then we're done.
1748 if (BlockPointerTypeLoc *BlockPtr
1749 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1750 TL = BlockPtr->getPointeeLoc();
1751 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1752 }
1753 break;
1754 }
1755 }
1756
1757 if (!Block) {
1758 // We were unable to find a FunctionProtoTypeLoc with parameter names
1759 // for the block; just use the parameter type as a placeholder.
1760 std::string Result;
1761 Param->getType().getUnqualifiedType().
1762 getAsStringInternal(Result, Context.PrintingPolicy);
1763
1764 if (ObjCMethodParam) {
1765 Result = "(" + Result;
1766 Result += ")";
1767 if (Param->getIdentifier())
1768 Result += Param->getIdentifier()->getName();
1769 }
1770
1771 return Result;
1772 }
1773
1774 // We have the function prototype behind the block pointer type, as it was
1775 // written in the source.
1776 std::string Result = "(^)(";
1777 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1778 if (I)
1779 Result += ", ";
1780 Result += FormatFunctionParameter(Context, Block->getArg(I));
1781 }
1782 if (Block->getTypePtr()->isVariadic()) {
1783 if (Block->getNumArgs() > 0)
1784 Result += ", ...";
1785 else
1786 Result += "...";
1787 } else if (Block->getNumArgs() == 0 && !Context.getLangOptions().CPlusPlus)
1788 Result += "void";
1789
1790 Result += ")";
1791 Block->getTypePtr()->getResultType().getAsStringInternal(Result,
1792 Context.PrintingPolicy);
1793 return Result;
1794}
1795
Douglas Gregor86d9a522009-09-21 16:56:56 +00001796/// \brief Add function parameter chunks to the given code completion string.
1797static void AddFunctionParameterChunks(ASTContext &Context,
1798 FunctionDecl *Function,
1799 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001800 typedef CodeCompletionString::Chunk Chunk;
1801
Douglas Gregor86d9a522009-09-21 16:56:56 +00001802 CodeCompletionString *CCStr = Result;
1803
1804 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1805 ParmVarDecl *Param = Function->getParamDecl(P);
1806
1807 if (Param->hasDefaultArg()) {
1808 // When we see an optional default argument, put that argument and
1809 // the remaining default arguments into a new, optional string.
1810 CodeCompletionString *Opt = new CodeCompletionString;
1811 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1812 CCStr = Opt;
1813 }
1814
1815 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001816 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001817
1818 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001819 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1820
Douglas Gregor86d9a522009-09-21 16:56:56 +00001821 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001822 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001823 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001824
1825 if (const FunctionProtoType *Proto
1826 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001827 if (Proto->isVariadic()) {
Douglas Gregorb3d45252009-09-22 21:42:17 +00001828 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001829
1830 MaybeAddSentinel(Context, Function, CCStr);
1831 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001832}
1833
1834/// \brief Add template parameter chunks to the given code completion string.
1835static void AddTemplateParameterChunks(ASTContext &Context,
1836 TemplateDecl *Template,
1837 CodeCompletionString *Result,
1838 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001839 typedef CodeCompletionString::Chunk Chunk;
1840
Douglas Gregor86d9a522009-09-21 16:56:56 +00001841 CodeCompletionString *CCStr = Result;
1842 bool FirstParameter = true;
1843
1844 TemplateParameterList *Params = Template->getTemplateParameters();
1845 TemplateParameterList::iterator PEnd = Params->end();
1846 if (MaxParameters)
1847 PEnd = Params->begin() + MaxParameters;
1848 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1849 bool HasDefaultArg = false;
1850 std::string PlaceholderStr;
1851 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1852 if (TTP->wasDeclaredWithTypename())
1853 PlaceholderStr = "typename";
1854 else
1855 PlaceholderStr = "class";
1856
1857 if (TTP->getIdentifier()) {
1858 PlaceholderStr += ' ';
1859 PlaceholderStr += TTP->getIdentifier()->getName();
1860 }
1861
1862 HasDefaultArg = TTP->hasDefaultArgument();
1863 } else if (NonTypeTemplateParmDecl *NTTP
1864 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1865 if (NTTP->getIdentifier())
1866 PlaceholderStr = NTTP->getIdentifier()->getName();
1867 NTTP->getType().getAsStringInternal(PlaceholderStr,
1868 Context.PrintingPolicy);
1869 HasDefaultArg = NTTP->hasDefaultArgument();
1870 } else {
1871 assert(isa<TemplateTemplateParmDecl>(*P));
1872 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1873
1874 // Since putting the template argument list into the placeholder would
1875 // be very, very long, we just use an abbreviation.
1876 PlaceholderStr = "template<...> class";
1877 if (TTP->getIdentifier()) {
1878 PlaceholderStr += ' ';
1879 PlaceholderStr += TTP->getIdentifier()->getName();
1880 }
1881
1882 HasDefaultArg = TTP->hasDefaultArgument();
1883 }
1884
1885 if (HasDefaultArg) {
1886 // When we see an optional default argument, put that argument and
1887 // the remaining default arguments into a new, optional string.
1888 CodeCompletionString *Opt = new CodeCompletionString;
1889 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1890 CCStr = Opt;
1891 }
1892
1893 if (FirstParameter)
1894 FirstParameter = false;
1895 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001896 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001897
1898 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001899 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001900 }
1901}
1902
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001903/// \brief Add a qualifier to the given code-completion string, if the
1904/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001905static void
1906AddQualifierToCompletionString(CodeCompletionString *Result,
1907 NestedNameSpecifier *Qualifier,
1908 bool QualifierIsInformative,
1909 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001910 if (!Qualifier)
1911 return;
1912
1913 std::string PrintedNNS;
1914 {
1915 llvm::raw_string_ostream OS(PrintedNNS);
1916 Qualifier->print(OS, Context.PrintingPolicy);
1917 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001918 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001919 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001920 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001921 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001922}
1923
Douglas Gregora61a8792009-12-11 18:44:16 +00001924static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1925 FunctionDecl *Function) {
1926 const FunctionProtoType *Proto
1927 = Function->getType()->getAs<FunctionProtoType>();
1928 if (!Proto || !Proto->getTypeQuals())
1929 return;
1930
1931 std::string QualsStr;
1932 if (Proto->getTypeQuals() & Qualifiers::Const)
1933 QualsStr += " const";
1934 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1935 QualsStr += " volatile";
1936 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1937 QualsStr += " restrict";
1938 Result->AddInformativeChunk(QualsStr);
1939}
1940
Douglas Gregor86d9a522009-09-21 16:56:56 +00001941/// \brief If possible, create a new code completion string for the given
1942/// result.
1943///
1944/// \returns Either a new, heap-allocated code completion string describing
1945/// how to use this result, or NULL to indicate that the string or name of the
1946/// result is all that is needed.
1947CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00001948CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001949 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001950 typedef CodeCompletionString::Chunk Chunk;
1951
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001952 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001953 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001954
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001955 if (!Result)
1956 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001957
1958 if (Kind == RK_Keyword) {
1959 Result->AddTypedTextChunk(Keyword);
1960 return Result;
1961 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001962
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001963 if (Kind == RK_Macro) {
1964 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001965 assert(MI && "Not a macro?");
1966
1967 Result->AddTypedTextChunk(Macro->getName());
1968
1969 if (!MI->isFunctionLike())
1970 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001971
1972 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001973 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001974 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1975 A != AEnd; ++A) {
1976 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001977 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001978
1979 if (!MI->isVariadic() || A != AEnd - 1) {
1980 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001981 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001982 continue;
1983 }
1984
1985 // Variadic argument; cope with the different between GNU and C99
1986 // variadic macros, providing a single placeholder for the rest of the
1987 // arguments.
1988 if ((*A)->isStr("__VA_ARGS__"))
1989 Result->AddPlaceholderChunk("...");
1990 else {
1991 std::string Arg = (*A)->getName();
1992 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001993 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001994 }
1995 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001996 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001997 return Result;
1998 }
1999
Douglas Gregord8e8a582010-05-25 21:41:55 +00002000 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002001 NamedDecl *ND = Declaration;
2002
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002003 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002004 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002005 Result->AddTextChunk("::");
2006 return Result;
2007 }
2008
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002009 AddResultTypeChunk(S.Context, ND, Result);
2010
Douglas Gregor86d9a522009-09-21 16:56:56 +00002011 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002012 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2013 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002014 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002015 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002016 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002017 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002018 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002019 return Result;
2020 }
2021
2022 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002023 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2024 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002025 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00002026 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00002027
2028 // Figure out which template parameters are deduced (or have default
2029 // arguments).
2030 llvm::SmallVector<bool, 16> Deduced;
2031 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2032 unsigned LastDeducibleArgument;
2033 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2034 --LastDeducibleArgument) {
2035 if (!Deduced[LastDeducibleArgument - 1]) {
2036 // C++0x: Figure out if the template argument has a default. If so,
2037 // the user doesn't need to type this argument.
2038 // FIXME: We need to abstract template parameters better!
2039 bool HasDefaultArg = false;
2040 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2041 LastDeducibleArgument - 1);
2042 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2043 HasDefaultArg = TTP->hasDefaultArgument();
2044 else if (NonTypeTemplateParmDecl *NTTP
2045 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2046 HasDefaultArg = NTTP->hasDefaultArgument();
2047 else {
2048 assert(isa<TemplateTemplateParmDecl>(Param));
2049 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002050 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002051 }
2052
2053 if (!HasDefaultArg)
2054 break;
2055 }
2056 }
2057
2058 if (LastDeducibleArgument) {
2059 // Some of the function template arguments cannot be deduced from a
2060 // function call, so we introduce an explicit template argument list
2061 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002062 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002063 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2064 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002065 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002066 }
2067
2068 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002069 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002070 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002071 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002072 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002073 return Result;
2074 }
2075
2076 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002077 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2078 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002079 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002080 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002081 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002082 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002083 return Result;
2084 }
2085
Douglas Gregor9630eb62009-11-17 16:44:22 +00002086 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002087 Selector Sel = Method->getSelector();
2088 if (Sel.isUnarySelector()) {
2089 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2090 return Result;
2091 }
2092
Douglas Gregord3c68542009-11-19 01:08:35 +00002093 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2094 SelName += ':';
2095 if (StartParameter == 0)
2096 Result->AddTypedTextChunk(SelName);
2097 else {
2098 Result->AddInformativeChunk(SelName);
2099
2100 // If there is only one parameter, and we're past it, add an empty
2101 // typed-text chunk since there is nothing to type.
2102 if (Method->param_size() == 1)
2103 Result->AddTypedTextChunk("");
2104 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002105 unsigned Idx = 0;
2106 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2107 PEnd = Method->param_end();
2108 P != PEnd; (void)++P, ++Idx) {
2109 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002110 std::string Keyword;
2111 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002112 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002113 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2114 Keyword += II->getName().str();
2115 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002116 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002117 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002118 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00002119 Result->AddTypedTextChunk(Keyword);
2120 else
2121 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002122 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002123
2124 // If we're before the starting parameter, skip the placeholder.
2125 if (Idx < StartParameter)
2126 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002127
2128 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002129
2130 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2131 Arg = FormatFunctionParameter(S.Context, *P);
2132 else {
2133 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2134 Arg = "(" + Arg + ")";
2135 if (IdentifierInfo *II = (*P)->getIdentifier())
2136 Arg += II->getName().str();
2137 }
2138
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002139 if (DeclaringEntity)
2140 Result->AddTextChunk(Arg);
2141 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002142 Result->AddInformativeChunk(Arg);
2143 else
2144 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002145 }
2146
Douglas Gregor2a17af02009-12-23 00:21:46 +00002147 if (Method->isVariadic()) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002148 if (DeclaringEntity)
2149 Result->AddTextChunk(", ...");
2150 else if (AllParametersAreInformative)
Douglas Gregor2a17af02009-12-23 00:21:46 +00002151 Result->AddInformativeChunk(", ...");
2152 else
2153 Result->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002154
2155 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002156 }
2157
Douglas Gregor9630eb62009-11-17 16:44:22 +00002158 return Result;
2159 }
2160
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002161 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002162 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2163 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002164
2165 Result->AddTypedTextChunk(ND->getNameAsString());
2166 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002167}
2168
Douglas Gregor86d802e2009-09-23 00:34:09 +00002169CodeCompletionString *
2170CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2171 unsigned CurrentArg,
2172 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002173 typedef CodeCompletionString::Chunk Chunk;
2174
Douglas Gregor86d802e2009-09-23 00:34:09 +00002175 CodeCompletionString *Result = new CodeCompletionString;
2176 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002177 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002178 const FunctionProtoType *Proto
2179 = dyn_cast<FunctionProtoType>(getFunctionType());
2180 if (!FDecl && !Proto) {
2181 // Function without a prototype. Just give the return type and a
2182 // highlighted ellipsis.
2183 const FunctionType *FT = getFunctionType();
2184 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002185 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002186 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2187 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2188 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002189 return Result;
2190 }
2191
2192 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002193 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002194 else
2195 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002196 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002197
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002198 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002199 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2200 for (unsigned I = 0; I != NumParams; ++I) {
2201 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002202 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002203
2204 std::string ArgString;
2205 QualType ArgType;
2206
2207 if (FDecl) {
2208 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2209 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2210 } else {
2211 ArgType = Proto->getArgType(I);
2212 }
2213
2214 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2215
2216 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002217 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002218 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002219 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002220 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002221 }
2222
2223 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002224 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002225 if (CurrentArg < NumParams)
2226 Result->AddTextChunk("...");
2227 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002228 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002229 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002230 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002231
2232 return Result;
2233}
2234
Douglas Gregor1827e102010-08-16 16:18:59 +00002235unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2236 bool PreferredTypeIsPointer) {
2237 unsigned Priority = CCP_Macro;
2238
2239 // Treat the "nil" and "NULL" macros as null pointer constants.
2240 if (MacroName.equals("nil") || MacroName.equals("NULL")) {
2241 Priority = CCP_Constant;
2242 if (PreferredTypeIsPointer)
2243 Priority = Priority / CCF_SimilarTypeMatch;
2244 }
2245
2246 return Priority;
2247}
2248
Douglas Gregor590c7d52010-07-08 20:55:51 +00002249static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2250 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002251 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002252
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002253 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002254 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2255 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002256 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002257 Results.AddResult(Result(M->first,
2258 getMacroUsagePriority(M->first->getName(),
2259 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002260 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002261 Results.ExitScope();
2262}
2263
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002264static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2265 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002266 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002267
2268 Results.EnterNewScope();
2269 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2270 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2271 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2272 Results.AddResult(Result("__func__", CCP_Constant));
2273 Results.ExitScope();
2274}
2275
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002276static void HandleCodeCompleteResults(Sema *S,
2277 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002278 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002279 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002280 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002281 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002282 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002283
2284 for (unsigned I = 0; I != NumResults; ++I)
2285 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002286}
2287
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002288static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2289 Sema::ParserCompletionContext PCC) {
2290 switch (PCC) {
2291 case Action::PCC_Namespace:
2292 return CodeCompletionContext::CCC_TopLevel;
2293
2294 case Action::PCC_Class:
2295 return CodeCompletionContext::CCC_ClassStructUnion;
2296
2297 case Action::PCC_ObjCInterface:
2298 return CodeCompletionContext::CCC_ObjCInterface;
2299
2300 case Action::PCC_ObjCImplementation:
2301 return CodeCompletionContext::CCC_ObjCImplementation;
2302
2303 case Action::PCC_ObjCInstanceVariableList:
2304 return CodeCompletionContext::CCC_ObjCIvarList;
2305
2306 case Action::PCC_Template:
2307 case Action::PCC_MemberTemplate:
2308 case Action::PCC_RecoveryInFunction:
2309 return CodeCompletionContext::CCC_Other;
2310
2311 case Action::PCC_Expression:
2312 case Action::PCC_ForInit:
2313 case Action::PCC_Condition:
2314 return CodeCompletionContext::CCC_Expression;
2315
2316 case Action::PCC_Statement:
2317 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002318
2319 case Action::PCC_Type:
2320 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002321 }
2322
2323 return CodeCompletionContext::CCC_Other;
2324}
2325
Douglas Gregor01dfea02010-01-10 23:08:15 +00002326void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002327 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002328 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002329 ResultBuilder Results(*this);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002330
2331 // Determine how to filter results, e.g., so that the names of
2332 // values (functions, enumerators, function templates, etc.) are
2333 // only allowed where we can have an expression.
2334 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002335 case PCC_Namespace:
2336 case PCC_Class:
2337 case PCC_ObjCInterface:
2338 case PCC_ObjCImplementation:
2339 case PCC_ObjCInstanceVariableList:
2340 case PCC_Template:
2341 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002342 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002343 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2344 break;
2345
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002346 case PCC_Statement:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002347 // For statements that are expressions, we prefer to call 'void' functions
2348 // rather than functions that return a result, since then the result would
2349 // be ignored.
2350 Results.setPreferredType(Context.VoidTy);
2351 // Fall through
2352
2353 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002354 case PCC_ForInit:
2355 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002356 if (WantTypesInContext(CompletionContext, getLangOptions()))
2357 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2358 else
2359 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002360 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002361
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002362 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002363 // Unfiltered
2364 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002365 }
2366
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002367 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002368 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2369 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002370
2371 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002372 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002373 Results.ExitScope();
2374
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002375 switch (CompletionContext) {
Douglas Gregor72db1082010-08-24 01:11:00 +00002376 case PCC_Expression:
2377 case PCC_Statement:
2378 case PCC_RecoveryInFunction:
2379 if (S->getFnParent())
2380 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2381 break;
2382
2383 case PCC_Namespace:
2384 case PCC_Class:
2385 case PCC_ObjCInterface:
2386 case PCC_ObjCImplementation:
2387 case PCC_ObjCInstanceVariableList:
2388 case PCC_Template:
2389 case PCC_MemberTemplate:
2390 case PCC_ForInit:
2391 case PCC_Condition:
2392 case PCC_Type:
2393 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002394 }
2395
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002396 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002397 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002398
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002399 HandleCodeCompleteResults(this, CodeCompleter,
2400 mapCodeCompletionContext(*this, CompletionContext),
2401 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002402}
2403
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002404void Sema::CodeCompleteDeclarator(Scope *S,
2405 bool AllowNonIdentifiers,
2406 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002407 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002408 ResultBuilder Results(*this);
2409 Results.EnterNewScope();
2410
2411 // Type qualifiers can come after names.
2412 Results.AddResult(Result("const"));
2413 Results.AddResult(Result("volatile"));
2414 if (getLangOptions().C99)
2415 Results.AddResult(Result("restrict"));
2416
2417 if (getLangOptions().CPlusPlus) {
2418 if (AllowNonIdentifiers) {
2419 Results.AddResult(Result("operator"));
2420 }
2421
2422 // Add nested-name-specifiers.
2423 if (AllowNestedNameSpecifiers) {
2424 Results.allowNestedNameSpecifiers();
2425 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2426 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2427 CodeCompleter->includeGlobals());
2428 }
2429 }
2430 Results.ExitScope();
2431
Douglas Gregor4497dd42010-08-24 04:59:56 +00002432 // Note that we intentionally suppress macro results here, since we do not
2433 // encourage using macros to produce the names of entities.
2434
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002435 HandleCodeCompleteResults(this, CodeCompleter,
2436 AllowNestedNameSpecifiers
2437 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2438 : CodeCompletionContext::CCC_Name,
2439 Results.data(), Results.size());
2440}
2441
Douglas Gregorfb629412010-08-23 21:17:50 +00002442struct Sema::CodeCompleteExpressionData {
2443 CodeCompleteExpressionData(QualType PreferredType = QualType())
2444 : PreferredType(PreferredType), IntegralConstantExpression(false),
2445 ObjCCollection(false) { }
2446
2447 QualType PreferredType;
2448 bool IntegralConstantExpression;
2449 bool ObjCCollection;
2450 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2451};
2452
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002453/// \brief Perform code-completion in an expression context when we know what
2454/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002455///
2456/// \param IntegralConstantExpression Only permit integral constant
2457/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002458void Sema::CodeCompleteExpression(Scope *S,
2459 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002460 typedef CodeCompletionResult Result;
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002461 ResultBuilder Results(*this);
2462
Douglas Gregorfb629412010-08-23 21:17:50 +00002463 if (Data.ObjCCollection)
2464 Results.setFilter(&ResultBuilder::IsObjCCollection);
2465 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002466 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002467 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002468 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2469 else
2470 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002471
2472 if (!Data.PreferredType.isNull())
2473 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2474
2475 // Ignore any declarations that we were told that we don't care about.
2476 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2477 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002478
2479 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002480 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2481 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002482
2483 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002484 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002485 Results.ExitScope();
2486
Douglas Gregor590c7d52010-07-08 20:55:51 +00002487 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002488 if (!Data.PreferredType.isNull())
2489 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2490 || Data.PreferredType->isMemberPointerType()
2491 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002492
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002493 if (S->getFnParent() &&
2494 !Data.ObjCCollection &&
2495 !Data.IntegralConstantExpression)
2496 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2497
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002498 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002499 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002500 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002501 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2502 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002503 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002504}
2505
2506
Douglas Gregor95ac6552009-11-18 01:29:26 +00002507static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002508 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002509 DeclContext *CurContext,
2510 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002511 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002512
2513 // Add properties in this container.
2514 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2515 PEnd = Container->prop_end();
2516 P != PEnd;
2517 ++P)
2518 Results.MaybeAddResult(Result(*P, 0), CurContext);
2519
2520 // Add properties in referenced protocols.
2521 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2522 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2523 PEnd = Protocol->protocol_end();
2524 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002525 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002526 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002527 if (AllowCategories) {
2528 // Look through categories.
2529 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2530 Category; Category = Category->getNextClassCategory())
2531 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2532 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002533
2534 // Look through protocols.
2535 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2536 E = IFace->protocol_end();
2537 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002538 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002539
2540 // Look in the superclass.
2541 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002542 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2543 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002544 } else if (const ObjCCategoryDecl *Category
2545 = dyn_cast<ObjCCategoryDecl>(Container)) {
2546 // Look through protocols.
2547 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2548 PEnd = Category->protocol_end();
2549 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002550 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002551 }
2552}
2553
Douglas Gregor81b747b2009-09-17 21:32:03 +00002554void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2555 SourceLocation OpLoc,
2556 bool IsArrow) {
2557 if (!BaseE || !CodeCompleter)
2558 return;
2559
John McCall0a2c5e22010-08-25 06:19:51 +00002560 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002561
Douglas Gregor81b747b2009-09-17 21:32:03 +00002562 Expr *Base = static_cast<Expr *>(BaseE);
2563 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002564
2565 if (IsArrow) {
2566 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2567 BaseType = Ptr->getPointeeType();
2568 else if (BaseType->isObjCObjectPointerType())
2569 /*Do nothing*/ ;
2570 else
2571 return;
2572 }
2573
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002574 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002575 Results.EnterNewScope();
2576 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2577 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002578 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002579 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002580 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2581 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002582
Douglas Gregor95ac6552009-11-18 01:29:26 +00002583 if (getLangOptions().CPlusPlus) {
2584 if (!Results.empty()) {
2585 // The "template" keyword can follow "->" or "." in the grammar.
2586 // However, we only want to suggest the template keyword if something
2587 // is dependent.
2588 bool IsDependent = BaseType->isDependentType();
2589 if (!IsDependent) {
2590 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2591 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2592 IsDependent = Ctx->isDependentContext();
2593 break;
2594 }
2595 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002596
Douglas Gregor95ac6552009-11-18 01:29:26 +00002597 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002598 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002599 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002600 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002601 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2602 // Objective-C property reference.
2603
2604 // Add property results based on our interface.
2605 const ObjCObjectPointerType *ObjCPtr
2606 = BaseType->getAsObjCInterfacePointerType();
2607 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002608 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002609
2610 // Add properties from the protocols in a qualified interface.
2611 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2612 E = ObjCPtr->qual_end();
2613 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002614 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002615 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002616 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002617 // Objective-C instance variable access.
2618 ObjCInterfaceDecl *Class = 0;
2619 if (const ObjCObjectPointerType *ObjCPtr
2620 = BaseType->getAs<ObjCObjectPointerType>())
2621 Class = ObjCPtr->getInterfaceDecl();
2622 else
John McCallc12c5bb2010-05-15 11:32:37 +00002623 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002624
2625 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002626 if (Class) {
2627 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2628 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00002629 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2630 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00002631 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002632 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002633
2634 // FIXME: How do we cope with isa?
2635
2636 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002637
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002638 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002639 HandleCodeCompleteResults(this, CodeCompleter,
2640 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2641 BaseType),
2642 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002643}
2644
Douglas Gregor374929f2009-09-18 15:37:17 +00002645void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2646 if (!CodeCompleter)
2647 return;
2648
John McCall0a2c5e22010-08-25 06:19:51 +00002649 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002650 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002651 enum CodeCompletionContext::Kind ContextKind
2652 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00002653 switch ((DeclSpec::TST)TagSpec) {
2654 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002655 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002656 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002657 break;
2658
2659 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002660 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002661 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002662 break;
2663
2664 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002665 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002666 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002667 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002668 break;
2669
2670 default:
2671 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2672 return;
2673 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002674
John McCall0d6b1642010-04-23 18:46:30 +00002675 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002676 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002677
2678 // First pass: look for tags.
2679 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00002680 LookupVisibleDecls(S, LookupTagName, Consumer,
2681 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00002682
Douglas Gregor8071e422010-08-15 06:18:01 +00002683 if (CodeCompleter->includeGlobals()) {
2684 // Second pass: look for nested name specifiers.
2685 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2686 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2687 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002688
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002689 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2690 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002691}
2692
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002693void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00002694 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002695 return;
2696
John McCall781472f2010-08-25 08:40:02 +00002697 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00002698 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00002699 CodeCompleteExpressionData Data(Switch->getCond()->getType());
2700 Data.IntegralConstantExpression = true;
2701 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002702 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00002703 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002704
2705 // Code-complete the cases of a switch statement over an enumeration type
2706 // by providing the list of
2707 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2708
2709 // Determine which enumerators we have already seen in the switch statement.
2710 // FIXME: Ideally, we would also be able to look *past* the code-completion
2711 // token, in case we are code-completing in the middle of the switch and not
2712 // at the end. However, we aren't able to do so at the moment.
2713 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002714 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002715 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2716 SC = SC->getNextSwitchCase()) {
2717 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2718 if (!Case)
2719 continue;
2720
2721 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2722 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2723 if (EnumConstantDecl *Enumerator
2724 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2725 // We look into the AST of the case statement to determine which
2726 // enumerator was named. Alternatively, we could compute the value of
2727 // the integral constant expression, then compare it against the
2728 // values of each enumerator. However, value-based approach would not
2729 // work as well with C++ templates where enumerators declared within a
2730 // template are type- and value-dependent.
2731 EnumeratorsSeen.insert(Enumerator);
2732
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002733 // If this is a qualified-id, keep track of the nested-name-specifier
2734 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002735 //
2736 // switch (TagD.getKind()) {
2737 // case TagDecl::TK_enum:
2738 // break;
2739 // case XXX
2740 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002741 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002742 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2743 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002744 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002745 }
2746 }
2747
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002748 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2749 // If there are no prior enumerators in C++, check whether we have to
2750 // qualify the names of the enumerators that we suggest, because they
2751 // may not be visible in this scope.
2752 Qualifier = getRequiredQualification(Context, CurContext,
2753 Enum->getDeclContext());
2754
2755 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2756 }
2757
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002758 // Add any enumerators that have not yet been mentioned.
2759 ResultBuilder Results(*this);
2760 Results.EnterNewScope();
2761 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2762 EEnd = Enum->enumerator_end();
2763 E != EEnd; ++E) {
2764 if (EnumeratorsSeen.count(*E))
2765 continue;
2766
John McCall0a2c5e22010-08-25 06:19:51 +00002767 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00002768 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002769 }
2770 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002771
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002772 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002773 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002774 HandleCodeCompleteResults(this, CodeCompleter,
2775 CodeCompletionContext::CCC_Expression,
2776 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002777}
2778
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002779namespace {
2780 struct IsBetterOverloadCandidate {
2781 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002782 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002783
2784 public:
John McCall5769d612010-02-08 23:07:23 +00002785 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2786 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002787
2788 bool
2789 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00002790 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002791 }
2792 };
2793}
2794
Douglas Gregord28dcd72010-05-30 06:10:08 +00002795static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2796 if (NumArgs && !Args)
2797 return true;
2798
2799 for (unsigned I = 0; I != NumArgs; ++I)
2800 if (!Args[I])
2801 return true;
2802
2803 return false;
2804}
2805
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002806void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2807 ExprTy **ArgsIn, unsigned NumArgs) {
2808 if (!CodeCompleter)
2809 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002810
2811 // When we're code-completing for a call, we fall back to ordinary
2812 // name code-completion whenever we can't produce specific
2813 // results. We may want to revisit this strategy in the future,
2814 // e.g., by merging the two kinds of results.
2815
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002816 Expr *Fn = (Expr *)FnIn;
2817 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002818
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002819 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002820 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002821 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002822 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002823 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002824 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002825
John McCall3b4294e2009-12-16 12:17:52 +00002826 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002827 SourceLocation Loc = Fn->getExprLoc();
2828 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002829
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002830 // FIXME: What if we're calling something that isn't a function declaration?
2831 // FIXME: What if we're calling a pseudo-destructor?
2832 // FIXME: What if we're calling a member function?
2833
Douglas Gregorc0265402010-01-21 15:46:19 +00002834 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2835 llvm::SmallVector<ResultCandidate, 8> Results;
2836
John McCall3b4294e2009-12-16 12:17:52 +00002837 Expr *NakedFn = Fn->IgnoreParenCasts();
2838 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2839 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2840 /*PartialOverloading=*/ true);
2841 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2842 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002843 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00002844 if (!getLangOptions().CPlusPlus ||
2845 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00002846 Results.push_back(ResultCandidate(FDecl));
2847 else
John McCall86820f52010-01-26 01:37:31 +00002848 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00002849 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2850 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00002851 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00002852 }
John McCall3b4294e2009-12-16 12:17:52 +00002853 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002854
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002855 QualType ParamType;
2856
Douglas Gregorc0265402010-01-21 15:46:19 +00002857 if (!CandidateSet.empty()) {
2858 // Sort the overload candidate set by placing the best overloads first.
2859 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00002860 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002861
Douglas Gregorc0265402010-01-21 15:46:19 +00002862 // Add the remaining viable overload candidates as code-completion reslults.
2863 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2864 CandEnd = CandidateSet.end();
2865 Cand != CandEnd; ++Cand) {
2866 if (Cand->Viable)
2867 Results.push_back(ResultCandidate(Cand->Function));
2868 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002869
2870 // From the viable candidates, try to determine the type of this parameter.
2871 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2872 if (const FunctionType *FType = Results[I].getFunctionType())
2873 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2874 if (NumArgs < Proto->getNumArgs()) {
2875 if (ParamType.isNull())
2876 ParamType = Proto->getArgType(NumArgs);
2877 else if (!Context.hasSameUnqualifiedType(
2878 ParamType.getNonReferenceType(),
2879 Proto->getArgType(NumArgs).getNonReferenceType())) {
2880 ParamType = QualType();
2881 break;
2882 }
2883 }
2884 }
2885 } else {
2886 // Try to determine the parameter type from the type of the expression
2887 // being called.
2888 QualType FunctionType = Fn->getType();
2889 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2890 FunctionType = Ptr->getPointeeType();
2891 else if (const BlockPointerType *BlockPtr
2892 = FunctionType->getAs<BlockPointerType>())
2893 FunctionType = BlockPtr->getPointeeType();
2894 else if (const MemberPointerType *MemPtr
2895 = FunctionType->getAs<MemberPointerType>())
2896 FunctionType = MemPtr->getPointeeType();
2897
2898 if (const FunctionProtoType *Proto
2899 = FunctionType->getAs<FunctionProtoType>()) {
2900 if (NumArgs < Proto->getNumArgs())
2901 ParamType = Proto->getArgType(NumArgs);
2902 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002903 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002904
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002905 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002906 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002907 else
2908 CodeCompleteExpression(S, ParamType);
2909
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00002910 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00002911 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2912 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002913}
2914
John McCalld226f652010-08-21 09:40:31 +00002915void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
2916 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002917 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002918 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002919 return;
2920 }
2921
2922 CodeCompleteExpression(S, VD->getType());
2923}
2924
2925void Sema::CodeCompleteReturn(Scope *S) {
2926 QualType ResultType;
2927 if (isa<BlockDecl>(CurContext)) {
2928 if (BlockScopeInfo *BSI = getCurBlock())
2929 ResultType = BSI->ReturnType;
2930 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2931 ResultType = Function->getResultType();
2932 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2933 ResultType = Method->getResultType();
2934
2935 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002936 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002937 else
2938 CodeCompleteExpression(S, ResultType);
2939}
2940
2941void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2942 if (LHS)
2943 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2944 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002945 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002946}
2947
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002948void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002949 bool EnteringContext) {
2950 if (!SS.getScopeRep() || !CodeCompleter)
2951 return;
2952
Douglas Gregor86d9a522009-09-21 16:56:56 +00002953 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2954 if (!Ctx)
2955 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002956
2957 // Try to instantiate any non-dependent declaration contexts before
2958 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00002959 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002960 return;
2961
Douglas Gregor86d9a522009-09-21 16:56:56 +00002962 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00002963 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2964 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002965
2966 // The "template" keyword can follow "::" in the grammar, but only
2967 // put it into the grammar if the nested-name-specifier is dependent.
2968 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2969 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00002970 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002971
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002972 HandleCodeCompleteResults(this, CodeCompleter,
2973 CodeCompletionContext::CCC_Other,
2974 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002975}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002976
2977void Sema::CodeCompleteUsing(Scope *S) {
2978 if (!CodeCompleter)
2979 return;
2980
Douglas Gregor86d9a522009-09-21 16:56:56 +00002981 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002982 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002983
2984 // If we aren't in class scope, we could see the "namespace" keyword.
2985 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00002986 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002987
2988 // After "using", we can see anything that would start a
2989 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002990 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002991 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2992 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002993 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002994
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002995 HandleCodeCompleteResults(this, CodeCompleter,
2996 CodeCompletionContext::CCC_Other,
2997 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002998}
2999
3000void Sema::CodeCompleteUsingDirective(Scope *S) {
3001 if (!CodeCompleter)
3002 return;
3003
Douglas Gregor86d9a522009-09-21 16:56:56 +00003004 // After "using namespace", we expect to see a namespace name or namespace
3005 // alias.
3006 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003007 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003008 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003009 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3010 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003011 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003012 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003013 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003014 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003015}
3016
3017void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3018 if (!CodeCompleter)
3019 return;
3020
Douglas Gregor86d9a522009-09-21 16:56:56 +00003021 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
3022 DeclContext *Ctx = (DeclContext *)S->getEntity();
3023 if (!S->getParent())
3024 Ctx = Context.getTranslationUnitDecl();
3025
3026 if (Ctx && Ctx->isFileContext()) {
3027 // We only want to see those namespaces that have already been defined
3028 // within this scope, because its likely that the user is creating an
3029 // extended namespace declaration. Keep track of the most recent
3030 // definition of each namespace.
3031 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3032 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3033 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3034 NS != NSEnd; ++NS)
3035 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3036
3037 // Add the most recent definition (or extended definition) of each
3038 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003039 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003040 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3041 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3042 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003043 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003044 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003045 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003046 }
3047
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003048 HandleCodeCompleteResults(this, CodeCompleter,
3049 CodeCompletionContext::CCC_Other,
3050 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003051}
3052
3053void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3054 if (!CodeCompleter)
3055 return;
3056
Douglas Gregor86d9a522009-09-21 16:56:56 +00003057 // After "namespace", we expect to see a namespace or alias.
3058 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003059 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003060 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3061 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003062 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003063 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003064 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003065}
3066
Douglas Gregored8d3222009-09-18 20:05:18 +00003067void Sema::CodeCompleteOperatorName(Scope *S) {
3068 if (!CodeCompleter)
3069 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003070
John McCall0a2c5e22010-08-25 06:19:51 +00003071 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003072 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003073 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003074
Douglas Gregor86d9a522009-09-21 16:56:56 +00003075 // Add the names of overloadable operators.
3076#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3077 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003078 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003079#include "clang/Basic/OperatorKinds.def"
3080
3081 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003082 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003083 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003084 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3085 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003086
3087 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003088 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003089 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003090
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003091 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003092 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003093 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003094}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003095
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003096// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3097// true or false.
3098#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003099static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003100 ResultBuilder &Results,
3101 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003102 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003103 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003104 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003105
3106 CodeCompletionString *Pattern = 0;
3107 if (LangOpts.ObjC2) {
3108 // @dynamic
3109 Pattern = new CodeCompletionString;
3110 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3111 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3112 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003113 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003114
3115 // @synthesize
3116 Pattern = new CodeCompletionString;
3117 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3118 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3119 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003120 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003121 }
3122}
3123
Douglas Gregorbca403c2010-01-13 23:51:12 +00003124static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003125 ResultBuilder &Results,
3126 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003127 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003128
3129 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003130 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003131
3132 if (LangOpts.ObjC2) {
3133 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003134 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003135
3136 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003137 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003138
3139 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003140 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003141 }
3142}
3143
Douglas Gregorbca403c2010-01-13 23:51:12 +00003144static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003145 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003146 CodeCompletionString *Pattern = 0;
3147
3148 // @class name ;
3149 Pattern = new CodeCompletionString;
3150 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3151 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003152 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003153 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003154
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003155 if (Results.includeCodePatterns()) {
3156 // @interface name
3157 // FIXME: Could introduce the whole pattern, including superclasses and
3158 // such.
3159 Pattern = new CodeCompletionString;
3160 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3161 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3162 Pattern->AddPlaceholderChunk("class");
3163 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003164
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003165 // @protocol name
3166 Pattern = new CodeCompletionString;
3167 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3168 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3169 Pattern->AddPlaceholderChunk("protocol");
3170 Results.AddResult(Result(Pattern));
3171
3172 // @implementation name
3173 Pattern = new CodeCompletionString;
3174 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3175 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3176 Pattern->AddPlaceholderChunk("class");
3177 Results.AddResult(Result(Pattern));
3178 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003179
3180 // @compatibility_alias name
3181 Pattern = new CodeCompletionString;
3182 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3183 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3184 Pattern->AddPlaceholderChunk("alias");
3185 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3186 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003187 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003188}
3189
John McCalld226f652010-08-21 09:40:31 +00003190void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003191 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003192 typedef CodeCompletionResult Result;
Douglas Gregorc464ae82009-12-07 09:27:33 +00003193 ResultBuilder Results(*this);
3194 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003195 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003196 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003197 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003198 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003199 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003200 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003201 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003202 HandleCodeCompleteResults(this, CodeCompleter,
3203 CodeCompletionContext::CCC_Other,
3204 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003205}
3206
Douglas Gregorbca403c2010-01-13 23:51:12 +00003207static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003208 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003209 CodeCompletionString *Pattern = 0;
3210
3211 // @encode ( type-name )
3212 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003213 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003214 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3215 Pattern->AddPlaceholderChunk("type-name");
3216 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003217 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003218
3219 // @protocol ( protocol-name )
3220 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003221 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003222 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3223 Pattern->AddPlaceholderChunk("protocol-name");
3224 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003225 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003226
3227 // @selector ( selector )
3228 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003229 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003230 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3231 Pattern->AddPlaceholderChunk("selector");
3232 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003233 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003234}
3235
Douglas Gregorbca403c2010-01-13 23:51:12 +00003236static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003237 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003238 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003239
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003240 if (Results.includeCodePatterns()) {
3241 // @try { statements } @catch ( declaration ) { statements } @finally
3242 // { statements }
3243 Pattern = new CodeCompletionString;
3244 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3245 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3246 Pattern->AddPlaceholderChunk("statements");
3247 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3248 Pattern->AddTextChunk("@catch");
3249 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3250 Pattern->AddPlaceholderChunk("parameter");
3251 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3252 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3253 Pattern->AddPlaceholderChunk("statements");
3254 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3255 Pattern->AddTextChunk("@finally");
3256 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3257 Pattern->AddPlaceholderChunk("statements");
3258 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3259 Results.AddResult(Result(Pattern));
3260 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003261
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003262 // @throw
3263 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003264 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003265 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003266 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003267 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003268
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003269 if (Results.includeCodePatterns()) {
3270 // @synchronized ( expression ) { statements }
3271 Pattern = new CodeCompletionString;
3272 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3273 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3274 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3275 Pattern->AddPlaceholderChunk("expression");
3276 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3277 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3278 Pattern->AddPlaceholderChunk("statements");
3279 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3280 Results.AddResult(Result(Pattern));
3281 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003282}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003283
Douglas Gregorbca403c2010-01-13 23:51:12 +00003284static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003285 ResultBuilder &Results,
3286 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003287 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003288 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3289 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3290 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003291 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003292 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003293}
3294
3295void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3296 ResultBuilder Results(*this);
3297 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003298 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003299 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003300 HandleCodeCompleteResults(this, CodeCompleter,
3301 CodeCompletionContext::CCC_Other,
3302 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003303}
3304
3305void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003306 ResultBuilder Results(*this);
3307 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003308 AddObjCStatementResults(Results, false);
3309 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003310 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003311 HandleCodeCompleteResults(this, CodeCompleter,
3312 CodeCompletionContext::CCC_Other,
3313 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003314}
3315
3316void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3317 ResultBuilder Results(*this);
3318 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003319 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003320 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003321 HandleCodeCompleteResults(this, CodeCompleter,
3322 CodeCompletionContext::CCC_Other,
3323 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003324}
3325
Douglas Gregor988358f2009-11-19 00:14:45 +00003326/// \brief Determine whether the addition of the given flag to an Objective-C
3327/// property's attributes will cause a conflict.
3328static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3329 // Check if we've already added this flag.
3330 if (Attributes & NewFlag)
3331 return true;
3332
3333 Attributes |= NewFlag;
3334
3335 // Check for collisions with "readonly".
3336 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3337 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3338 ObjCDeclSpec::DQ_PR_assign |
3339 ObjCDeclSpec::DQ_PR_copy |
3340 ObjCDeclSpec::DQ_PR_retain)))
3341 return true;
3342
3343 // Check for more than one of { assign, copy, retain }.
3344 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3345 ObjCDeclSpec::DQ_PR_copy |
3346 ObjCDeclSpec::DQ_PR_retain);
3347 if (AssignCopyRetMask &&
3348 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3349 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3350 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3351 return true;
3352
3353 return false;
3354}
3355
Douglas Gregora93b1082009-11-18 23:08:07 +00003356void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003357 if (!CodeCompleter)
3358 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003359
Steve Naroffece8e712009-10-08 21:55:05 +00003360 unsigned Attributes = ODS.getPropertyAttributes();
3361
John McCall0a2c5e22010-08-25 06:19:51 +00003362 typedef CodeCompletionResult Result;
Steve Naroffece8e712009-10-08 21:55:05 +00003363 ResultBuilder Results(*this);
3364 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003365 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003366 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003367 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003368 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003369 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003370 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003371 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003372 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003373 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003374 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003375 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003376 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003377 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003378 CodeCompletionString *Setter = new CodeCompletionString;
3379 Setter->AddTypedTextChunk("setter");
3380 Setter->AddTextChunk(" = ");
3381 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003382 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003383 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003384 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003385 CodeCompletionString *Getter = new CodeCompletionString;
3386 Getter->AddTypedTextChunk("getter");
3387 Getter->AddTextChunk(" = ");
3388 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003389 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003390 }
Steve Naroffece8e712009-10-08 21:55:05 +00003391 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003392 HandleCodeCompleteResults(this, CodeCompleter,
3393 CodeCompletionContext::CCC_Other,
3394 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003395}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003396
Douglas Gregor4ad96852009-11-19 07:41:15 +00003397/// \brief Descripts the kind of Objective-C method that we want to find
3398/// via code completion.
3399enum ObjCMethodKind {
3400 MK_Any, //< Any kind of method, provided it means other specified criteria.
3401 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3402 MK_OneArgSelector //< One-argument selector.
3403};
3404
Douglas Gregor458433d2010-08-26 15:07:07 +00003405static bool isAcceptableObjCSelector(Selector Sel,
3406 ObjCMethodKind WantKind,
3407 IdentifierInfo **SelIdents,
3408 unsigned NumSelIdents) {
3409 if (NumSelIdents > Sel.getNumArgs())
3410 return false;
3411
3412 switch (WantKind) {
3413 case MK_Any: break;
3414 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3415 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3416 }
3417
3418 for (unsigned I = 0; I != NumSelIdents; ++I)
3419 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3420 return false;
3421
3422 return true;
3423}
3424
Douglas Gregor4ad96852009-11-19 07:41:15 +00003425static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3426 ObjCMethodKind WantKind,
3427 IdentifierInfo **SelIdents,
3428 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00003429 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3430 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003431}
3432
Douglas Gregor36ecb042009-11-17 23:22:23 +00003433/// \brief Add all of the Objective-C methods in the given Objective-C
3434/// container to the set of results.
3435///
3436/// The container will be a class, protocol, category, or implementation of
3437/// any of the above. This mether will recurse to include methods from
3438/// the superclasses of classes along with their categories, protocols, and
3439/// implementations.
3440///
3441/// \param Container the container in which we'll look to find methods.
3442///
3443/// \param WantInstance whether to add instance methods (only); if false, this
3444/// routine will add factory methods (only).
3445///
3446/// \param CurContext the context in which we're performing the lookup that
3447/// finds methods.
3448///
3449/// \param Results the structure into which we'll add results.
3450static void AddObjCMethods(ObjCContainerDecl *Container,
3451 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003452 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003453 IdentifierInfo **SelIdents,
3454 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003455 DeclContext *CurContext,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003456 ResultBuilder &Results,
3457 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00003458 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00003459 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3460 MEnd = Container->meth_end();
3461 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003462 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3463 // Check whether the selector identifiers we've been given are a
3464 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003465 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003466 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003467
Douglas Gregord3c68542009-11-19 01:08:35 +00003468 Result R = Result(*M, 0);
3469 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003470 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00003471 if (!InOriginalClass)
3472 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00003473 Results.MaybeAddResult(R, CurContext);
3474 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003475 }
3476
3477 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3478 if (!IFace)
3479 return;
3480
3481 // Add methods in protocols.
3482 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3483 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3484 E = Protocols.end();
3485 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003486 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003487 CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003488
3489 // Add methods in categories.
3490 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3491 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003492 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003493 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003494
3495 // Add a categories protocol methods.
3496 const ObjCList<ObjCProtocolDecl> &Protocols
3497 = CatDecl->getReferencedProtocols();
3498 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3499 E = Protocols.end();
3500 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003501 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003502 NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003503
3504 // Add methods in category implementations.
3505 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003506 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003507 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003508 }
3509
3510 // Add methods in superclass.
3511 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003512 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003513 SelIdents, NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003514
3515 // Add methods in our implementation, if any.
3516 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003517 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003518 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003519}
3520
3521
John McCalld226f652010-08-21 09:40:31 +00003522void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
3523 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003524 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003525 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003526
3527 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00003528 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003529 if (!Class) {
3530 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003531 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003532 Class = Category->getClassInterface();
3533
3534 if (!Class)
3535 return;
3536 }
3537
3538 // Find all of the potential getters.
3539 ResultBuilder Results(*this);
3540 Results.EnterNewScope();
3541
3542 // FIXME: We need to do this because Objective-C methods don't get
3543 // pushed into DeclContexts early enough. Argh!
3544 for (unsigned I = 0; I != NumMethods; ++I) {
3545 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003546 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003547 if (Method->isInstanceMethod() &&
3548 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3549 Result R = Result(Method, 0);
3550 R.AllParametersAreInformative = true;
3551 Results.MaybeAddResult(R, CurContext);
3552 }
3553 }
3554
3555 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3556 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003557 HandleCodeCompleteResults(this, CodeCompleter,
3558 CodeCompletionContext::CCC_Other,
3559 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00003560}
3561
John McCalld226f652010-08-21 09:40:31 +00003562void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
3563 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003564 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003565 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003566
3567 // Try to find the interface where setters might live.
3568 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00003569 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003570 if (!Class) {
3571 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003572 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003573 Class = Category->getClassInterface();
3574
3575 if (!Class)
3576 return;
3577 }
3578
3579 // Find all of the potential getters.
3580 ResultBuilder Results(*this);
3581 Results.EnterNewScope();
3582
3583 // FIXME: We need to do this because Objective-C methods don't get
3584 // pushed into DeclContexts early enough. Argh!
3585 for (unsigned I = 0; I != NumMethods; ++I) {
3586 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003587 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003588 if (Method->isInstanceMethod() &&
3589 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3590 Result R = Result(Method, 0);
3591 R.AllParametersAreInformative = true;
3592 Results.MaybeAddResult(R, CurContext);
3593 }
3594 }
3595
3596 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3597
3598 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003599 HandleCodeCompleteResults(this, CodeCompleter,
3600 CodeCompletionContext::CCC_Other,
3601 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003602}
3603
Douglas Gregord32b0222010-08-24 01:06:58 +00003604void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00003605 typedef CodeCompletionResult Result;
Douglas Gregord32b0222010-08-24 01:06:58 +00003606 ResultBuilder Results(*this);
3607 Results.EnterNewScope();
3608
3609 // Add context-sensitive, Objective-C parameter-passing keywords.
3610 bool AddedInOut = false;
3611 if ((DS.getObjCDeclQualifier() &
3612 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
3613 Results.AddResult("in");
3614 Results.AddResult("inout");
3615 AddedInOut = true;
3616 }
3617 if ((DS.getObjCDeclQualifier() &
3618 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
3619 Results.AddResult("out");
3620 if (!AddedInOut)
3621 Results.AddResult("inout");
3622 }
3623 if ((DS.getObjCDeclQualifier() &
3624 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
3625 ObjCDeclSpec::DQ_Oneway)) == 0) {
3626 Results.AddResult("bycopy");
3627 Results.AddResult("byref");
3628 Results.AddResult("oneway");
3629 }
3630
3631 // Add various builtin type names and specifiers.
3632 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
3633 Results.ExitScope();
3634
3635 // Add the various type names
3636 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3637 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3638 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3639 CodeCompleter->includeGlobals());
3640
3641 if (CodeCompleter->includeMacros())
3642 AddMacroResults(PP, Results);
3643
3644 HandleCodeCompleteResults(this, CodeCompleter,
3645 CodeCompletionContext::CCC_Type,
3646 Results.data(), Results.size());
3647}
3648
Douglas Gregor22f56992010-04-06 19:22:33 +00003649/// \brief When we have an expression with type "id", we may assume
3650/// that it has some more-specific class type based on knowledge of
3651/// common uses of Objective-C. This routine returns that class type,
3652/// or NULL if no better result could be determined.
3653static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3654 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3655 if (!Msg)
3656 return 0;
3657
3658 Selector Sel = Msg->getSelector();
3659 if (Sel.isNull())
3660 return 0;
3661
3662 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3663 if (!Id)
3664 return 0;
3665
3666 ObjCMethodDecl *Method = Msg->getMethodDecl();
3667 if (!Method)
3668 return 0;
3669
3670 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003671 ObjCInterfaceDecl *IFace = 0;
3672 switch (Msg->getReceiverKind()) {
3673 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003674 if (const ObjCObjectType *ObjType
3675 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3676 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003677 break;
3678
3679 case ObjCMessageExpr::Instance: {
3680 QualType T = Msg->getInstanceReceiver()->getType();
3681 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3682 IFace = Ptr->getInterfaceDecl();
3683 break;
3684 }
3685
3686 case ObjCMessageExpr::SuperInstance:
3687 case ObjCMessageExpr::SuperClass:
3688 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003689 }
3690
3691 if (!IFace)
3692 return 0;
3693
3694 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3695 if (Method->isInstanceMethod())
3696 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3697 .Case("retain", IFace)
3698 .Case("autorelease", IFace)
3699 .Case("copy", IFace)
3700 .Case("copyWithZone", IFace)
3701 .Case("mutableCopy", IFace)
3702 .Case("mutableCopyWithZone", IFace)
3703 .Case("awakeFromCoder", IFace)
3704 .Case("replacementObjectFromCoder", IFace)
3705 .Case("class", IFace)
3706 .Case("classForCoder", IFace)
3707 .Case("superclass", Super)
3708 .Default(0);
3709
3710 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3711 .Case("new", IFace)
3712 .Case("alloc", IFace)
3713 .Case("allocWithZone", IFace)
3714 .Case("class", IFace)
3715 .Case("superclass", Super)
3716 .Default(0);
3717}
3718
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003719void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00003720 typedef CodeCompletionResult Result;
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003721 ResultBuilder Results(*this);
3722
3723 // Find anything that looks like it could be a message receiver.
3724 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3725 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3726 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00003727 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3728 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003729
3730 // If we are in an Objective-C method inside a class that has a superclass,
3731 // add "super" as an option.
3732 if (ObjCMethodDecl *Method = getCurMethodDecl())
3733 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3734 if (Iface->getSuperClass())
3735 Results.AddResult(Result("super"));
3736
3737 Results.ExitScope();
3738
3739 if (CodeCompleter->includeMacros())
3740 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003741 HandleCodeCompleteResults(this, CodeCompleter,
3742 CodeCompletionContext::CCC_ObjCMessageReceiver,
3743 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003744
3745}
3746
Douglas Gregor2725ca82010-04-21 19:57:20 +00003747void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3748 IdentifierInfo **SelIdents,
3749 unsigned NumSelIdents) {
3750 ObjCInterfaceDecl *CDecl = 0;
3751 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3752 // Figure out which interface we're in.
3753 CDecl = CurMethod->getClassInterface();
3754 if (!CDecl)
3755 return;
3756
3757 // Find the superclass of this class.
3758 CDecl = CDecl->getSuperClass();
3759 if (!CDecl)
3760 return;
3761
3762 if (CurMethod->isInstanceMethod()) {
3763 // We are inside an instance method, which means that the message
3764 // send [super ...] is actually calling an instance method on the
3765 // current object. Build the super expression and handle this like
3766 // an instance method.
3767 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3768 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall60d7b3a2010-08-24 06:29:42 +00003769 ExprResult Super
Douglas Gregor2725ca82010-04-21 19:57:20 +00003770 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3771 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3772 SelIdents, NumSelIdents);
3773 }
3774
3775 // Fall through to send to the superclass in CDecl.
3776 } else {
3777 // "super" may be the name of a type or variable. Figure out which
3778 // it is.
3779 IdentifierInfo *Super = &Context.Idents.get("super");
3780 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3781 LookupOrdinaryName);
3782 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3783 // "super" names an interface. Use it.
3784 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00003785 if (const ObjCObjectType *Iface
3786 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3787 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00003788 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3789 // "super" names an unresolved type; we can't be more specific.
3790 } else {
3791 // Assume that "super" names some kind of value and parse that way.
3792 CXXScopeSpec SS;
3793 UnqualifiedId id;
3794 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00003795 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003796 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3797 SelIdents, NumSelIdents);
3798 }
3799
3800 // Fall through
3801 }
3802
John McCallb3d87482010-08-24 05:47:05 +00003803 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00003804 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00003805 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00003806 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3807 NumSelIdents);
3808}
3809
John McCallb3d87482010-08-24 05:47:05 +00003810void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00003811 IdentifierInfo **SelIdents,
3812 unsigned NumSelIdents) {
John McCall0a2c5e22010-08-25 06:19:51 +00003813 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00003814 ObjCInterfaceDecl *CDecl = 0;
3815
Douglas Gregor24a069f2009-11-17 17:59:40 +00003816 // If the given name refers to an interface type, retrieve the
3817 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00003818 if (Receiver) {
3819 QualType T = GetTypeFromParser(Receiver, 0);
3820 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00003821 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3822 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00003823 }
3824
Douglas Gregor36ecb042009-11-17 23:22:23 +00003825 // Add all of the factory methods in this Objective-C class, its protocols,
3826 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00003827 ResultBuilder Results(*this);
3828 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00003829
3830 if (CDecl)
3831 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3832 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003833 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00003834 // We're messaging "id" as a type; provide all class/factory methods.
3835
Douglas Gregor719770d2010-04-06 17:30:22 +00003836 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003837 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00003838 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003839 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3840 I != N; ++I) {
3841 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00003842 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00003843 continue;
3844
Sebastian Redldb9d2142010-08-02 23:18:59 +00003845 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00003846 }
3847 }
3848
Sebastian Redldb9d2142010-08-02 23:18:59 +00003849 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3850 MEnd = MethodPool.end();
3851 M != MEnd; ++M) {
3852 for (ObjCMethodList *MethList = &M->second.second;
3853 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003854 MethList = MethList->Next) {
3855 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3856 NumSelIdents))
3857 continue;
3858
3859 Result R(MethList->Method, 0);
3860 R.StartParameter = NumSelIdents;
3861 R.AllParametersAreInformative = false;
3862 Results.MaybeAddResult(R, CurContext);
3863 }
3864 }
3865 }
3866
Steve Naroffc4df6d22009-11-07 02:08:14 +00003867 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003868 HandleCodeCompleteResults(this, CodeCompleter,
3869 CodeCompletionContext::CCC_Other,
3870 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003871}
3872
Douglas Gregord3c68542009-11-19 01:08:35 +00003873void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3874 IdentifierInfo **SelIdents,
3875 unsigned NumSelIdents) {
John McCall0a2c5e22010-08-25 06:19:51 +00003876 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00003877
3878 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00003879
Douglas Gregor36ecb042009-11-17 23:22:23 +00003880 // If necessary, apply function/array conversion to the receiver.
3881 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00003882 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003883 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00003884
Douglas Gregor36ecb042009-11-17 23:22:23 +00003885 // Build the set of methods we can see.
3886 ResultBuilder Results(*this);
3887 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00003888
3889 // If we're messaging an expression with type "id" or "Class", check
3890 // whether we know something special about the receiver that allows
3891 // us to assume a more-specific receiver type.
3892 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3893 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3894 ReceiverType = Context.getObjCObjectPointerType(
3895 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00003896
Douglas Gregorf74a4192009-11-18 00:06:18 +00003897 // Handle messages to Class. This really isn't a message to an instance
3898 // method, so we treat it the same way we would treat a message send to a
3899 // class method.
3900 if (ReceiverType->isObjCClassType() ||
3901 ReceiverType->isObjCQualifiedClassType()) {
3902 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3903 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003904 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3905 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003906 }
3907 }
3908 // Handle messages to a qualified ID ("id<foo>").
3909 else if (const ObjCObjectPointerType *QualID
3910 = ReceiverType->getAsObjCQualifiedIdType()) {
3911 // Search protocols for instance methods.
3912 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3913 E = QualID->qual_end();
3914 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003915 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3916 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003917 }
3918 // Handle messages to a pointer to interface type.
3919 else if (const ObjCObjectPointerType *IFacePtr
3920 = ReceiverType->getAsObjCInterfacePointerType()) {
3921 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003922 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3923 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003924
3925 // Search protocols for instance methods.
3926 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3927 E = IFacePtr->qual_end();
3928 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003929 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3930 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003931 }
Douglas Gregor13438f92010-04-06 16:40:00 +00003932 // Handle messages to "id".
3933 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003934 // We're messaging "id", so provide all instance methods we know
3935 // about as code-completion results.
3936
3937 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003938 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00003939 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003940 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3941 I != N; ++I) {
3942 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00003943 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00003944 continue;
3945
Sebastian Redldb9d2142010-08-02 23:18:59 +00003946 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00003947 }
3948 }
3949
Sebastian Redldb9d2142010-08-02 23:18:59 +00003950 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3951 MEnd = MethodPool.end();
3952 M != MEnd; ++M) {
3953 for (ObjCMethodList *MethList = &M->second.first;
3954 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003955 MethList = MethList->Next) {
3956 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3957 NumSelIdents))
3958 continue;
3959
3960 Result R(MethList->Method, 0);
3961 R.StartParameter = NumSelIdents;
3962 R.AllParametersAreInformative = false;
3963 Results.MaybeAddResult(R, CurContext);
3964 }
3965 }
3966 }
3967
Steve Naroffc4df6d22009-11-07 02:08:14 +00003968 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003969 HandleCodeCompleteResults(this, CodeCompleter,
3970 CodeCompletionContext::CCC_Other,
3971 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003972}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003973
Douglas Gregorfb629412010-08-23 21:17:50 +00003974void Sema::CodeCompleteObjCForCollection(Scope *S,
3975 DeclGroupPtrTy IterationVar) {
3976 CodeCompleteExpressionData Data;
3977 Data.ObjCCollection = true;
3978
3979 if (IterationVar.getAsOpaquePtr()) {
3980 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
3981 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
3982 if (*I)
3983 Data.IgnoreDecls.push_back(*I);
3984 }
3985 }
3986
3987 CodeCompleteExpression(S, Data);
3988}
3989
Douglas Gregor458433d2010-08-26 15:07:07 +00003990void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
3991 unsigned NumSelIdents) {
3992 // If we have an external source, load the entire class method
3993 // pool from the AST file.
3994 if (ExternalSource) {
3995 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3996 I != N; ++I) {
3997 Selector Sel = ExternalSource->GetExternalSelector(I);
3998 if (Sel.isNull() || MethodPool.count(Sel))
3999 continue;
4000
4001 ReadMethodPool(Sel);
4002 }
4003 }
4004
4005 ResultBuilder Results(*this);
4006 Results.EnterNewScope();
4007 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4008 MEnd = MethodPool.end();
4009 M != MEnd; ++M) {
4010
4011 Selector Sel = M->first;
4012 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4013 continue;
4014
4015 CodeCompletionString *Pattern = new CodeCompletionString;
4016 if (Sel.isUnarySelector()) {
4017 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4018 Results.AddResult(Pattern);
4019 continue;
4020 }
4021
4022 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
4023 std::string Piece = Sel.getIdentifierInfoForSlot(I)->getName().str();
4024 Piece += ':';
4025 if (I < NumSelIdents)
4026 Pattern->AddInformativeChunk(Piece);
4027 else if (I == NumSelIdents)
4028 Pattern->AddTypedTextChunk(Piece);
4029 else
4030 Pattern->AddTextChunk(Piece);
4031 }
4032 Results.AddResult(Pattern);
4033 }
4034 Results.ExitScope();
4035
4036 HandleCodeCompleteResults(this, CodeCompleter,
4037 CodeCompletionContext::CCC_SelectorName,
4038 Results.data(), Results.size());
4039}
4040
Douglas Gregor55385fe2009-11-18 04:19:12 +00004041/// \brief Add all of the protocol declarations that we find in the given
4042/// (translation unit) context.
4043static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004044 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004045 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004046 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004047
4048 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4049 DEnd = Ctx->decls_end();
4050 D != DEnd; ++D) {
4051 // Record any protocols we find.
4052 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004053 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004054 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004055
4056 // Record any forward-declared protocols we find.
4057 if (ObjCForwardProtocolDecl *Forward
4058 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4059 for (ObjCForwardProtocolDecl::protocol_iterator
4060 P = Forward->protocol_begin(),
4061 PEnd = Forward->protocol_end();
4062 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004063 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004064 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004065 }
4066 }
4067}
4068
4069void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4070 unsigned NumProtocols) {
4071 ResultBuilder Results(*this);
4072 Results.EnterNewScope();
4073
4074 // Tell the result set to ignore all of the protocols we have
4075 // already seen.
4076 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004077 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4078 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004079 Results.Ignore(Protocol);
4080
4081 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004082 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4083 Results);
4084
4085 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004086 HandleCodeCompleteResults(this, CodeCompleter,
4087 CodeCompletionContext::CCC_ObjCProtocolName,
4088 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004089}
4090
4091void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4092 ResultBuilder Results(*this);
4093 Results.EnterNewScope();
4094
4095 // Add all protocols.
4096 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4097 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004098
4099 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004100 HandleCodeCompleteResults(this, CodeCompleter,
4101 CodeCompletionContext::CCC_ObjCProtocolName,
4102 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004103}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004104
4105/// \brief Add all of the Objective-C interface declarations that we find in
4106/// the given (translation unit) context.
4107static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4108 bool OnlyForwardDeclarations,
4109 bool OnlyUnimplemented,
4110 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004111 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004112
4113 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4114 DEnd = Ctx->decls_end();
4115 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004116 // Record any interfaces we find.
4117 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4118 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4119 (!OnlyUnimplemented || !Class->getImplementation()))
4120 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004121
4122 // Record any forward-declared interfaces we find.
4123 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4124 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004125 C != CEnd; ++C)
4126 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4127 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4128 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004129 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004130 }
4131 }
4132}
4133
4134void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
4135 ResultBuilder Results(*this);
4136 Results.EnterNewScope();
4137
4138 // Add all classes.
4139 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4140 false, Results);
4141
4142 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004143 HandleCodeCompleteResults(this, CodeCompleter,
4144 CodeCompletionContext::CCC_Other,
4145 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004146}
4147
Douglas Gregorc83c6872010-04-15 22:33:43 +00004148void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4149 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004150 ResultBuilder Results(*this);
4151 Results.EnterNewScope();
4152
4153 // Make sure that we ignore the class we're currently defining.
4154 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004155 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004156 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004157 Results.Ignore(CurClass);
4158
4159 // Add all classes.
4160 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4161 false, Results);
4162
4163 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004164 HandleCodeCompleteResults(this, CodeCompleter,
4165 CodeCompletionContext::CCC_Other,
4166 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004167}
4168
4169void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
4170 ResultBuilder Results(*this);
4171 Results.EnterNewScope();
4172
4173 // Add all unimplemented classes.
4174 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4175 true, Results);
4176
4177 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004178 HandleCodeCompleteResults(this, CodeCompleter,
4179 CodeCompletionContext::CCC_Other,
4180 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004181}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004182
4183void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004184 IdentifierInfo *ClassName,
4185 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004186 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004187
4188 ResultBuilder Results(*this);
4189
4190 // Ignore any categories we find that have already been implemented by this
4191 // interface.
4192 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4193 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004194 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004195 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
4196 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4197 Category = Category->getNextClassCategory())
4198 CategoryNames.insert(Category->getIdentifier());
4199
4200 // Add all of the categories we know about.
4201 Results.EnterNewScope();
4202 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4203 for (DeclContext::decl_iterator D = TU->decls_begin(),
4204 DEnd = TU->decls_end();
4205 D != DEnd; ++D)
4206 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
4207 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004208 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004209 Results.ExitScope();
4210
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004211 HandleCodeCompleteResults(this, CodeCompleter,
4212 CodeCompletionContext::CCC_Other,
4213 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004214}
4215
4216void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004217 IdentifierInfo *ClassName,
4218 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004219 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004220
4221 // Find the corresponding interface. If we couldn't find the interface, the
4222 // program itself is ill-formed. However, we'll try to be helpful still by
4223 // providing the list of all of the categories we know about.
4224 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004225 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004226 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
4227 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004228 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004229
4230 ResultBuilder Results(*this);
4231
4232 // Add all of the categories that have have corresponding interface
4233 // declarations in this class and any of its superclasses, except for
4234 // already-implemented categories in the class itself.
4235 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4236 Results.EnterNewScope();
4237 bool IgnoreImplemented = true;
4238 while (Class) {
4239 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4240 Category = Category->getNextClassCategory())
4241 if ((!IgnoreImplemented || !Category->getImplementation()) &&
4242 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004243 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004244
4245 Class = Class->getSuperClass();
4246 IgnoreImplemented = false;
4247 }
4248 Results.ExitScope();
4249
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004250 HandleCodeCompleteResults(this, CodeCompleter,
4251 CodeCompletionContext::CCC_Other,
4252 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004253}
Douglas Gregor322328b2009-11-18 22:32:06 +00004254
John McCalld226f652010-08-21 09:40:31 +00004255void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004256 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004257 ResultBuilder Results(*this);
4258
4259 // Figure out where this @synthesize lives.
4260 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004261 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004262 if (!Container ||
4263 (!isa<ObjCImplementationDecl>(Container) &&
4264 !isa<ObjCCategoryImplDecl>(Container)))
4265 return;
4266
4267 // Ignore any properties that have already been implemented.
4268 for (DeclContext::decl_iterator D = Container->decls_begin(),
4269 DEnd = Container->decls_end();
4270 D != DEnd; ++D)
4271 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4272 Results.Ignore(PropertyImpl->getPropertyDecl());
4273
4274 // Add any properties that we find.
4275 Results.EnterNewScope();
4276 if (ObjCImplementationDecl *ClassImpl
4277 = dyn_cast<ObjCImplementationDecl>(Container))
4278 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4279 Results);
4280 else
4281 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4282 false, CurContext, Results);
4283 Results.ExitScope();
4284
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004285 HandleCodeCompleteResults(this, CodeCompleter,
4286 CodeCompletionContext::CCC_Other,
4287 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004288}
4289
4290void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4291 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00004292 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004293 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004294 ResultBuilder Results(*this);
4295
4296 // Figure out where this @synthesize lives.
4297 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004298 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004299 if (!Container ||
4300 (!isa<ObjCImplementationDecl>(Container) &&
4301 !isa<ObjCCategoryImplDecl>(Container)))
4302 return;
4303
4304 // Figure out which interface we're looking into.
4305 ObjCInterfaceDecl *Class = 0;
4306 if (ObjCImplementationDecl *ClassImpl
4307 = dyn_cast<ObjCImplementationDecl>(Container))
4308 Class = ClassImpl->getClassInterface();
4309 else
4310 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4311 ->getClassInterface();
4312
4313 // Add all of the instance variables in this class and its superclasses.
4314 Results.EnterNewScope();
4315 for(; Class; Class = Class->getSuperClass()) {
4316 // FIXME: We could screen the type of each ivar for compatibility with
4317 // the property, but is that being too paternal?
4318 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4319 IVarEnd = Class->ivar_end();
4320 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00004321 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00004322 }
4323 Results.ExitScope();
4324
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004325 HandleCodeCompleteResults(this, CodeCompleter,
4326 CodeCompletionContext::CCC_Other,
4327 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004328}
Douglas Gregore8f5a172010-04-07 00:21:17 +00004329
Douglas Gregor408be5a2010-08-25 01:08:01 +00004330// Mapping from selectors to the methods that implement that selector, along
4331// with the "in original class" flag.
4332typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
4333 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004334
4335/// \brief Find all of the methods that reside in the given container
4336/// (and its superclasses, protocols, etc.) that meet the given
4337/// criteria. Insert those methods into the map of known methods,
4338/// indexed by selector so they can be easily found.
4339static void FindImplementableMethods(ASTContext &Context,
4340 ObjCContainerDecl *Container,
4341 bool WantInstanceMethods,
4342 QualType ReturnType,
4343 bool IsInImplementation,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004344 KnownMethodsMap &KnownMethods,
4345 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004346 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4347 // Recurse into protocols.
4348 const ObjCList<ObjCProtocolDecl> &Protocols
4349 = IFace->getReferencedProtocols();
4350 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4351 E = Protocols.end();
4352 I != E; ++I)
4353 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004354 IsInImplementation, KnownMethods,
4355 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004356
4357 // If we're not in the implementation of a class, also visit the
4358 // superclass.
4359 if (!IsInImplementation && IFace->getSuperClass())
4360 FindImplementableMethods(Context, IFace->getSuperClass(),
4361 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004362 IsInImplementation, KnownMethods,
4363 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004364
4365 // Add methods from any class extensions (but not from categories;
4366 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00004367 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4368 Cat = Cat->getNextClassExtension())
4369 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4370 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004371 IsInImplementation, KnownMethods,
4372 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004373 }
4374
4375 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4376 // Recurse into protocols.
4377 const ObjCList<ObjCProtocolDecl> &Protocols
4378 = Category->getReferencedProtocols();
4379 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4380 E = Protocols.end();
4381 I != E; ++I)
4382 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004383 IsInImplementation, KnownMethods,
4384 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004385 }
4386
4387 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4388 // Recurse into protocols.
4389 const ObjCList<ObjCProtocolDecl> &Protocols
4390 = Protocol->getReferencedProtocols();
4391 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4392 E = Protocols.end();
4393 I != E; ++I)
4394 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004395 IsInImplementation, KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004396 }
4397
4398 // Add methods in this container. This operation occurs last because
4399 // we want the methods from this container to override any methods
4400 // we've previously seen with the same selector.
4401 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4402 MEnd = Container->meth_end();
4403 M != MEnd; ++M) {
4404 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4405 if (!ReturnType.isNull() &&
4406 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4407 continue;
4408
Douglas Gregor408be5a2010-08-25 01:08:01 +00004409 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004410 }
4411 }
4412}
4413
4414void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4415 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00004416 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00004417 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004418 // Determine the return type of the method we're declaring, if
4419 // provided.
4420 QualType ReturnType = GetTypeFromParser(ReturnTy);
4421
4422 // Determine where we should start searching for methods, and where we
4423 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4424 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00004425 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004426 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4427 SearchDecl = Impl->getClassInterface();
4428 CurrentDecl = Impl;
4429 IsInImplementation = true;
4430 } else if (ObjCCategoryImplDecl *CatImpl
4431 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4432 SearchDecl = CatImpl->getCategoryDecl();
4433 CurrentDecl = CatImpl;
4434 IsInImplementation = true;
4435 } else {
4436 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4437 CurrentDecl = SearchDecl;
4438 }
4439 }
4440
4441 if (!SearchDecl && S) {
4442 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4443 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4444 CurrentDecl = SearchDecl;
4445 }
4446 }
4447
4448 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004449 HandleCodeCompleteResults(this, CodeCompleter,
4450 CodeCompletionContext::CCC_Other,
4451 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004452 return;
4453 }
4454
4455 // Find all of the methods that we could declare/implement here.
4456 KnownMethodsMap KnownMethods;
4457 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4458 ReturnType, IsInImplementation, KnownMethods);
4459
4460 // Erase any methods that have already been declared or
4461 // implemented here.
4462 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4463 MEnd = CurrentDecl->meth_end();
4464 M != MEnd; ++M) {
4465 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4466 continue;
4467
4468 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4469 if (Pos != KnownMethods.end())
4470 KnownMethods.erase(Pos);
4471 }
4472
4473 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00004474 typedef CodeCompletionResult Result;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004475 ResultBuilder Results(*this);
4476 Results.EnterNewScope();
4477 PrintingPolicy Policy(Context.PrintingPolicy);
4478 Policy.AnonymousTagLocations = false;
4479 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4480 MEnd = KnownMethods.end();
4481 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00004482 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004483 CodeCompletionString *Pattern = new CodeCompletionString;
4484
4485 // If the result type was not already provided, add it to the
4486 // pattern as (type).
4487 if (ReturnType.isNull()) {
4488 std::string TypeStr;
4489 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4490 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4491 Pattern->AddTextChunk(TypeStr);
4492 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4493 }
4494
4495 Selector Sel = Method->getSelector();
4496
4497 // Add the first part of the selector to the pattern.
4498 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4499
4500 // Add parameters to the pattern.
4501 unsigned I = 0;
4502 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4503 PEnd = Method->param_end();
4504 P != PEnd; (void)++P, ++I) {
4505 // Add the part of the selector name.
4506 if (I == 0)
4507 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4508 else if (I < Sel.getNumArgs()) {
4509 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor47c03a72010-08-17 15:53:35 +00004510 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004511 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4512 } else
4513 break;
4514
4515 // Add the parameter type.
4516 std::string TypeStr;
4517 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4518 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4519 Pattern->AddTextChunk(TypeStr);
4520 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4521
4522 if (IdentifierInfo *Id = (*P)->getIdentifier())
4523 Pattern->AddTextChunk(Id->getName());
4524 }
4525
4526 if (Method->isVariadic()) {
4527 if (Method->param_size() > 0)
4528 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4529 Pattern->AddTextChunk("...");
4530 }
4531
Douglas Gregor447107d2010-05-28 00:57:46 +00004532 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004533 // We will be defining the method here, so add a compound statement.
4534 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4535 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4536 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4537 if (!Method->getResultType()->isVoidType()) {
4538 // If the result type is not void, add a return clause.
4539 Pattern->AddTextChunk("return");
4540 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4541 Pattern->AddPlaceholderChunk("expression");
4542 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4543 } else
4544 Pattern->AddPlaceholderChunk("statements");
4545
4546 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4547 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4548 }
4549
Douglas Gregor408be5a2010-08-25 01:08:01 +00004550 unsigned Priority = CCP_CodePattern;
4551 if (!M->second.second)
4552 Priority += CCD_InBaseClass;
4553
4554 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00004555 Method->isInstanceMethod()
4556 ? CXCursor_ObjCInstanceMethodDecl
4557 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00004558 }
4559
4560 Results.ExitScope();
4561
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004562 HandleCodeCompleteResults(this, CodeCompleter,
4563 CodeCompletionContext::CCC_Other,
4564 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004565}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004566
4567void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
4568 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004569 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00004570 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004571 IdentifierInfo **SelIdents,
4572 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004573 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004574 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004575 if (ExternalSource) {
4576 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4577 I != N; ++I) {
4578 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004579 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004580 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00004581
4582 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004583 }
4584 }
4585
4586 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00004587 typedef CodeCompletionResult Result;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004588 ResultBuilder Results(*this);
4589
4590 if (ReturnTy)
4591 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00004592
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004593 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004594 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4595 MEnd = MethodPool.end();
4596 M != MEnd; ++M) {
4597 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
4598 &M->second.second;
4599 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004600 MethList = MethList->Next) {
4601 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4602 NumSelIdents))
4603 continue;
4604
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004605 if (AtParameterName) {
4606 // Suggest parameter names we've seen before.
4607 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
4608 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
4609 if (Param->getIdentifier()) {
4610 CodeCompletionString *Pattern = new CodeCompletionString;
4611 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
4612 Results.AddResult(Pattern);
4613 }
4614 }
4615
4616 continue;
4617 }
4618
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004619 Result R(MethList->Method, 0);
4620 R.StartParameter = NumSelIdents;
4621 R.AllParametersAreInformative = false;
4622 R.DeclaringEntity = true;
4623 Results.MaybeAddResult(R, CurContext);
4624 }
4625 }
4626
4627 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004628 HandleCodeCompleteResults(this, CodeCompleter,
4629 CodeCompletionContext::CCC_Other,
4630 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004631}
Douglas Gregor87c08a52010-08-13 22:48:40 +00004632
Douglas Gregorf29c5232010-08-24 22:20:20 +00004633void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00004634 ResultBuilder Results(*this);
4635 Results.EnterNewScope();
4636
4637 // #if <condition>
4638 CodeCompletionString *Pattern = new CodeCompletionString;
4639 Pattern->AddTypedTextChunk("if");
4640 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4641 Pattern->AddPlaceholderChunk("condition");
4642 Results.AddResult(Pattern);
4643
4644 // #ifdef <macro>
4645 Pattern = new CodeCompletionString;
4646 Pattern->AddTypedTextChunk("ifdef");
4647 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4648 Pattern->AddPlaceholderChunk("macro");
4649 Results.AddResult(Pattern);
4650
4651 // #ifndef <macro>
4652 Pattern = new CodeCompletionString;
4653 Pattern->AddTypedTextChunk("ifndef");
4654 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4655 Pattern->AddPlaceholderChunk("macro");
4656 Results.AddResult(Pattern);
4657
4658 if (InConditional) {
4659 // #elif <condition>
4660 Pattern = new CodeCompletionString;
4661 Pattern->AddTypedTextChunk("elif");
4662 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4663 Pattern->AddPlaceholderChunk("condition");
4664 Results.AddResult(Pattern);
4665
4666 // #else
4667 Pattern = new CodeCompletionString;
4668 Pattern->AddTypedTextChunk("else");
4669 Results.AddResult(Pattern);
4670
4671 // #endif
4672 Pattern = new CodeCompletionString;
4673 Pattern->AddTypedTextChunk("endif");
4674 Results.AddResult(Pattern);
4675 }
4676
4677 // #include "header"
4678 Pattern = new CodeCompletionString;
4679 Pattern->AddTypedTextChunk("include");
4680 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4681 Pattern->AddTextChunk("\"");
4682 Pattern->AddPlaceholderChunk("header");
4683 Pattern->AddTextChunk("\"");
4684 Results.AddResult(Pattern);
4685
4686 // #include <header>
4687 Pattern = new CodeCompletionString;
4688 Pattern->AddTypedTextChunk("include");
4689 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4690 Pattern->AddTextChunk("<");
4691 Pattern->AddPlaceholderChunk("header");
4692 Pattern->AddTextChunk(">");
4693 Results.AddResult(Pattern);
4694
4695 // #define <macro>
4696 Pattern = new CodeCompletionString;
4697 Pattern->AddTypedTextChunk("define");
4698 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4699 Pattern->AddPlaceholderChunk("macro");
4700 Results.AddResult(Pattern);
4701
4702 // #define <macro>(<args>)
4703 Pattern = new CodeCompletionString;
4704 Pattern->AddTypedTextChunk("define");
4705 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4706 Pattern->AddPlaceholderChunk("macro");
4707 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4708 Pattern->AddPlaceholderChunk("args");
4709 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4710 Results.AddResult(Pattern);
4711
4712 // #undef <macro>
4713 Pattern = new CodeCompletionString;
4714 Pattern->AddTypedTextChunk("undef");
4715 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4716 Pattern->AddPlaceholderChunk("macro");
4717 Results.AddResult(Pattern);
4718
4719 // #line <number>
4720 Pattern = new CodeCompletionString;
4721 Pattern->AddTypedTextChunk("line");
4722 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4723 Pattern->AddPlaceholderChunk("number");
4724 Results.AddResult(Pattern);
4725
4726 // #line <number> "filename"
4727 Pattern = new CodeCompletionString;
4728 Pattern->AddTypedTextChunk("line");
4729 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4730 Pattern->AddPlaceholderChunk("number");
4731 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4732 Pattern->AddTextChunk("\"");
4733 Pattern->AddPlaceholderChunk("filename");
4734 Pattern->AddTextChunk("\"");
4735 Results.AddResult(Pattern);
4736
4737 // #error <message>
4738 Pattern = new CodeCompletionString;
4739 Pattern->AddTypedTextChunk("error");
4740 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4741 Pattern->AddPlaceholderChunk("message");
4742 Results.AddResult(Pattern);
4743
4744 // #pragma <arguments>
4745 Pattern = new CodeCompletionString;
4746 Pattern->AddTypedTextChunk("pragma");
4747 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4748 Pattern->AddPlaceholderChunk("arguments");
4749 Results.AddResult(Pattern);
4750
4751 if (getLangOptions().ObjC1) {
4752 // #import "header"
4753 Pattern = new CodeCompletionString;
4754 Pattern->AddTypedTextChunk("import");
4755 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4756 Pattern->AddTextChunk("\"");
4757 Pattern->AddPlaceholderChunk("header");
4758 Pattern->AddTextChunk("\"");
4759 Results.AddResult(Pattern);
4760
4761 // #import <header>
4762 Pattern = new CodeCompletionString;
4763 Pattern->AddTypedTextChunk("import");
4764 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4765 Pattern->AddTextChunk("<");
4766 Pattern->AddPlaceholderChunk("header");
4767 Pattern->AddTextChunk(">");
4768 Results.AddResult(Pattern);
4769 }
4770
4771 // #include_next "header"
4772 Pattern = new CodeCompletionString;
4773 Pattern->AddTypedTextChunk("include_next");
4774 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4775 Pattern->AddTextChunk("\"");
4776 Pattern->AddPlaceholderChunk("header");
4777 Pattern->AddTextChunk("\"");
4778 Results.AddResult(Pattern);
4779
4780 // #include_next <header>
4781 Pattern = new CodeCompletionString;
4782 Pattern->AddTypedTextChunk("include_next");
4783 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4784 Pattern->AddTextChunk("<");
4785 Pattern->AddPlaceholderChunk("header");
4786 Pattern->AddTextChunk(">");
4787 Results.AddResult(Pattern);
4788
4789 // #warning <message>
4790 Pattern = new CodeCompletionString;
4791 Pattern->AddTypedTextChunk("warning");
4792 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4793 Pattern->AddPlaceholderChunk("message");
4794 Results.AddResult(Pattern);
4795
4796 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
4797 // completions for them. And __include_macros is a Clang-internal extension
4798 // that we don't want to encourage anyone to use.
4799
4800 // FIXME: we don't support #assert or #unassert, so don't suggest them.
4801 Results.ExitScope();
4802
Douglas Gregorf44e8542010-08-24 19:08:16 +00004803 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00004804 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00004805 Results.data(), Results.size());
4806}
4807
4808void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00004809 CodeCompleteOrdinaryName(S,
4810 S->getFnParent()? Action::PCC_RecoveryInFunction
4811 : Action::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00004812}
4813
Douglas Gregorf29c5232010-08-24 22:20:20 +00004814void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor1fbb4472010-08-24 20:21:13 +00004815 ResultBuilder Results(*this);
4816 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
4817 // Add just the names of macros, not their arguments.
4818 Results.EnterNewScope();
4819 for (Preprocessor::macro_iterator M = PP.macro_begin(),
4820 MEnd = PP.macro_end();
4821 M != MEnd; ++M) {
4822 CodeCompletionString *Pattern = new CodeCompletionString;
4823 Pattern->AddTypedTextChunk(M->first->getName());
4824 Results.AddResult(Pattern);
4825 }
4826 Results.ExitScope();
4827 } else if (IsDefinition) {
4828 // FIXME: Can we detect when the user just wrote an include guard above?
4829 }
4830
4831 HandleCodeCompleteResults(this, CodeCompleter,
4832 IsDefinition? CodeCompletionContext::CCC_MacroName
4833 : CodeCompletionContext::CCC_MacroNameUse,
4834 Results.data(), Results.size());
4835}
4836
Douglas Gregorf29c5232010-08-24 22:20:20 +00004837void Sema::CodeCompletePreprocessorExpression() {
4838 ResultBuilder Results(*this);
4839
4840 if (!CodeCompleter || CodeCompleter->includeMacros())
4841 AddMacroResults(PP, Results);
4842
4843 // defined (<macro>)
4844 Results.EnterNewScope();
4845 CodeCompletionString *Pattern = new CodeCompletionString;
4846 Pattern->AddTypedTextChunk("defined");
4847 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4848 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4849 Pattern->AddPlaceholderChunk("macro");
4850 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4851 Results.AddResult(Pattern);
4852 Results.ExitScope();
4853
4854 HandleCodeCompleteResults(this, CodeCompleter,
4855 CodeCompletionContext::CCC_PreprocessorExpression,
4856 Results.data(), Results.size());
4857}
4858
4859void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
4860 IdentifierInfo *Macro,
4861 MacroInfo *MacroInfo,
4862 unsigned Argument) {
4863 // FIXME: In the future, we could provide "overload" results, much like we
4864 // do for function calls.
4865
4866 CodeCompleteOrdinaryName(S,
4867 S->getFnParent()? Action::PCC_RecoveryInFunction
4868 : Action::PCC_Namespace);
4869}
4870
Douglas Gregor55817af2010-08-25 17:04:25 +00004871void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00004872 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00004873 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00004874 0, 0);
4875}
4876
Douglas Gregor87c08a52010-08-13 22:48:40 +00004877void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00004878 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor87c08a52010-08-13 22:48:40 +00004879 ResultBuilder Builder(*this);
4880
Douglas Gregor8071e422010-08-15 06:18:01 +00004881 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
4882 CodeCompletionDeclConsumer Consumer(Builder,
4883 Context.getTranslationUnitDecl());
4884 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
4885 Consumer);
4886 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00004887
4888 if (!CodeCompleter || CodeCompleter->includeMacros())
4889 AddMacroResults(PP, Builder);
4890
4891 Results.clear();
4892 Results.insert(Results.end(),
4893 Builder.data(), Builder.data() + Builder.size());
4894}