blob: ab37b6ccbc100c1d8b696201491c1e0e48667b9a [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 Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
65
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
120
121 /// \brief If non-NULL, a filter function used to remove any code-completion
122 /// results that are not desirable.
123 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000124
125 /// \brief Whether we should allow declarations as
126 /// nested-name-specifiers that would otherwise be filtered out.
127 bool AllowNestedNameSpecifiers;
128
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000129 /// \brief If set, the type that we would prefer our resulting value
130 /// declarations to have.
131 ///
132 /// Closely matching the preferred type gives a boost to a result's
133 /// priority.
134 CanQualType PreferredType;
135
Douglas Gregor86d9a522009-09-21 16:56:56 +0000136 /// \brief A list of shadow maps, which is used to model name hiding at
137 /// different levels of, e.g., the inheritance hierarchy.
138 std::list<ShadowMap> ShadowMaps;
139
Douglas Gregor3cdee122010-08-26 16:36:48 +0000140 /// \brief If we're potentially referring to a C++ member function, the set
141 /// of qualifiers applied to the object type.
142 Qualifiers ObjectTypeQualifiers;
143
144 /// \brief Whether the \p ObjectTypeQualifiers field is active.
145 bool HasObjectTypeQualifiers;
146
Douglas Gregor265f7492010-08-27 15:29:55 +0000147 /// \brief The selector that we prefer.
148 Selector PreferredSelector;
149
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000150 /// \brief The completion context in which
151 CodeCompletionContext CompletionContext;
152
153 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000154
Douglas Gregor86d9a522009-09-21 16:56:56 +0000155 public:
156 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor3cdee122010-08-26 16:36:48 +0000157 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000158 HasObjectTypeQualifiers(false),
159 CompletionContext(CodeCompletionContext::CCC_Other) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000160
Douglas Gregord8e8a582010-05-25 21:41:55 +0000161 /// \brief Whether we should include code patterns in the completion
162 /// results.
163 bool includeCodePatterns() const {
164 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000165 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000166 }
167
Douglas Gregor86d9a522009-09-21 16:56:56 +0000168 /// \brief Set the filter used for code-completion results.
169 void setFilter(LookupFilter Filter) {
170 this->Filter = Filter;
171 }
172
Douglas Gregor86d9a522009-09-21 16:56:56 +0000173 Result *data() { return Results.empty()? 0 : &Results.front(); }
174 unsigned size() const { return Results.size(); }
175 bool empty() const { return Results.empty(); }
176
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000177 /// \brief Specify the preferred type.
178 void setPreferredType(QualType T) {
179 PreferredType = SemaRef.Context.getCanonicalType(T);
180 }
181
Douglas Gregor3cdee122010-08-26 16:36:48 +0000182 /// \brief Set the cv-qualifiers on the object type, for us in filtering
183 /// calls to member functions.
184 ///
185 /// When there are qualifiers in this set, they will be used to filter
186 /// out member functions that aren't available (because there will be a
187 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
188 /// match.
189 void setObjectTypeQualifiers(Qualifiers Quals) {
190 ObjectTypeQualifiers = Quals;
191 HasObjectTypeQualifiers = true;
192 }
193
Douglas Gregor265f7492010-08-27 15:29:55 +0000194 /// \brief Set the preferred selector.
195 ///
196 /// When an Objective-C method declaration result is added, and that
197 /// method's selector matches this preferred selector, we give that method
198 /// a slight priority boost.
199 void setPreferredSelector(Selector Sel) {
200 PreferredSelector = Sel;
201 }
202
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000203 /// \brief Retrieve the code-completion context for which results are
204 /// being collected.
205 const CodeCompletionContext &getCompletionContext() const {
206 return CompletionContext;
207 }
208
209 /// \brief Set the code-completion context.
210 void setCompletionContext(const CodeCompletionContext &CompletionContext) {
211 this->CompletionContext = CompletionContext;
212 }
213
Douglas Gregor45bcd432010-01-14 03:21:49 +0000214 /// \brief Specify whether nested-name-specifiers are allowed.
215 void allowNestedNameSpecifiers(bool Allow = true) {
216 AllowNestedNameSpecifiers = Allow;
217 }
218
Douglas Gregorb9d77572010-09-21 00:03:25 +0000219 /// \brief Return the semantic analysis object for which we are collecting
220 /// code completion results.
221 Sema &getSema() const { return SemaRef; }
222
Douglas Gregore495b7f2010-01-14 00:20:49 +0000223 /// \brief Determine whether the given declaration is at all interesting
224 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000225 ///
226 /// \param ND the declaration that we are inspecting.
227 ///
228 /// \param AsNestedNameSpecifier will be set true if this declaration is
229 /// only interesting when it is a nested-name-specifier.
230 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000231
232 /// \brief Check whether the result is hidden by the Hiding declaration.
233 ///
234 /// \returns true if the result is hidden and cannot be found, false if
235 /// the hidden result could still be found. When false, \p R may be
236 /// modified to describe how the result can be found (e.g., via extra
237 /// qualification).
238 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
239 NamedDecl *Hiding);
240
Douglas Gregor86d9a522009-09-21 16:56:56 +0000241 /// \brief Add a new result to this result set (if it isn't already in one
242 /// of the shadow maps), or replace an existing result (for, e.g., a
243 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000244 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000245 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000246 ///
247 /// \param R the context in which this result will be named.
248 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000249
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000250 /// \brief Add a new result to this result set, where we already know
251 /// the hiding declation (if any).
252 ///
253 /// \param R the result to add (if it is unique).
254 ///
255 /// \param CurContext the context in which this result will be named.
256 ///
257 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000258 ///
259 /// \param InBaseClass whether the result was found in a base
260 /// class of the searched context.
261 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
262 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000263
Douglas Gregora4477812010-01-14 16:01:26 +0000264 /// \brief Add a new non-declaration result to this result set.
265 void AddResult(Result R);
266
Douglas Gregor86d9a522009-09-21 16:56:56 +0000267 /// \brief Enter into a new scope.
268 void EnterNewScope();
269
270 /// \brief Exit from the current scope.
271 void ExitScope();
272
Douglas Gregor55385fe2009-11-18 04:19:12 +0000273 /// \brief Ignore this declaration, if it is seen again.
274 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
275
Douglas Gregor86d9a522009-09-21 16:56:56 +0000276 /// \name Name lookup predicates
277 ///
278 /// These predicates can be passed to the name lookup functions to filter the
279 /// results of name lookup. All of the predicates have the same type, so that
280 ///
281 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000282 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000283 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000284 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000285 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000286 bool IsNestedNameSpecifier(NamedDecl *ND) const;
287 bool IsEnum(NamedDecl *ND) const;
288 bool IsClassOrStruct(NamedDecl *ND) const;
289 bool IsUnion(NamedDecl *ND) const;
290 bool IsNamespace(NamedDecl *ND) const;
291 bool IsNamespaceOrAlias(NamedDecl *ND) const;
292 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000293 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000294 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000295 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000296 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000297 //@}
298 };
299}
300
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000301class ResultBuilder::ShadowMapEntry::iterator {
302 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
303 unsigned SingleDeclIndex;
304
305public:
306 typedef DeclIndexPair value_type;
307 typedef value_type reference;
308 typedef std::ptrdiff_t difference_type;
309 typedef std::input_iterator_tag iterator_category;
310
311 class pointer {
312 DeclIndexPair Value;
313
314 public:
315 pointer(const DeclIndexPair &Value) : Value(Value) { }
316
317 const DeclIndexPair *operator->() const {
318 return &Value;
319 }
320 };
321
322 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
323
324 iterator(NamedDecl *SingleDecl, unsigned Index)
325 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
326
327 iterator(const DeclIndexPair *Iterator)
328 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
329
330 iterator &operator++() {
331 if (DeclOrIterator.is<NamedDecl *>()) {
332 DeclOrIterator = (NamedDecl *)0;
333 SingleDeclIndex = 0;
334 return *this;
335 }
336
337 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
338 ++I;
339 DeclOrIterator = I;
340 return *this;
341 }
342
Chris Lattner66392d42010-09-04 18:12:20 +0000343 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000344 iterator tmp(*this);
345 ++(*this);
346 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000347 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000348
349 reference operator*() const {
350 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
351 return reference(ND, SingleDeclIndex);
352
Douglas Gregord490f952009-12-06 21:27:58 +0000353 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000354 }
355
356 pointer operator->() const {
357 return pointer(**this);
358 }
359
360 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000361 return X.DeclOrIterator.getOpaqueValue()
362 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000363 X.SingleDeclIndex == Y.SingleDeclIndex;
364 }
365
366 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000367 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000368 }
369};
370
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000371ResultBuilder::ShadowMapEntry::iterator
372ResultBuilder::ShadowMapEntry::begin() const {
373 if (DeclOrVector.isNull())
374 return iterator();
375
376 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
377 return iterator(ND, SingleDeclIndex);
378
379 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
380}
381
382ResultBuilder::ShadowMapEntry::iterator
383ResultBuilder::ShadowMapEntry::end() const {
384 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
385 return iterator();
386
387 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
388}
389
Douglas Gregor456c4a12009-09-21 20:12:40 +0000390/// \brief Compute the qualification required to get from the current context
391/// (\p CurContext) to the target context (\p TargetContext).
392///
393/// \param Context the AST context in which the qualification will be used.
394///
395/// \param CurContext the context where an entity is being named, which is
396/// typically based on the current scope.
397///
398/// \param TargetContext the context in which the named entity actually
399/// resides.
400///
401/// \returns a nested name specifier that refers into the target context, or
402/// NULL if no qualification is needed.
403static NestedNameSpecifier *
404getRequiredQualification(ASTContext &Context,
405 DeclContext *CurContext,
406 DeclContext *TargetContext) {
407 llvm::SmallVector<DeclContext *, 4> TargetParents;
408
409 for (DeclContext *CommonAncestor = TargetContext;
410 CommonAncestor && !CommonAncestor->Encloses(CurContext);
411 CommonAncestor = CommonAncestor->getLookupParent()) {
412 if (CommonAncestor->isTransparentContext() ||
413 CommonAncestor->isFunctionOrMethod())
414 continue;
415
416 TargetParents.push_back(CommonAncestor);
417 }
418
419 NestedNameSpecifier *Result = 0;
420 while (!TargetParents.empty()) {
421 DeclContext *Parent = TargetParents.back();
422 TargetParents.pop_back();
423
Douglas Gregorfb629412010-08-23 21:17:50 +0000424 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
425 if (!Namespace->getIdentifier())
426 continue;
427
Douglas Gregor456c4a12009-09-21 20:12:40 +0000428 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000429 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000430 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
431 Result = NestedNameSpecifier::Create(Context, Result,
432 false,
433 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000434 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000435 return Result;
436}
437
Douglas Gregor45bcd432010-01-14 03:21:49 +0000438bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
439 bool &AsNestedNameSpecifier) const {
440 AsNestedNameSpecifier = false;
441
Douglas Gregore495b7f2010-01-14 00:20:49 +0000442 ND = ND->getUnderlyingDecl();
443 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000444
445 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000446 if (!ND->getDeclName())
447 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000448
449 // Friend declarations and declarations introduced due to friends are never
450 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000451 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000452 return false;
453
Douglas Gregor76282942009-12-11 17:31:05 +0000454 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000455 if (isa<ClassTemplateSpecializationDecl>(ND) ||
456 isa<ClassTemplatePartialSpecializationDecl>(ND))
457 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000458
Douglas Gregor76282942009-12-11 17:31:05 +0000459 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000460 if (isa<UsingDecl>(ND))
461 return false;
462
463 // Some declarations have reserved names that we don't want to ever show.
464 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000465 // __va_list_tag is a freak of nature. Find it and skip it.
466 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000467 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000468
Douglas Gregorf52cede2009-10-09 22:16:47 +0000469 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000470 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000471 //
472 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000473 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000474 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000475 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000476 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
477 (ND->getLocation().isInvalid() ||
478 SemaRef.SourceMgr.isInSystemHeader(
479 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000480 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000481 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000482 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000483
Douglas Gregor86d9a522009-09-21 16:56:56 +0000484 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<CXXConstructorDecl>(ND))
486 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000487
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000488 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
489 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
490 Filter != &ResultBuilder::IsNamespace &&
491 Filter != &ResultBuilder::IsNamespaceOrAlias))
492 AsNestedNameSpecifier = true;
493
Douglas Gregor86d9a522009-09-21 16:56:56 +0000494 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000495 if (Filter && !(this->*Filter)(ND)) {
496 // Check whether it is interesting as a nested-name-specifier.
497 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
498 IsNestedNameSpecifier(ND) &&
499 (Filter != &ResultBuilder::IsMember ||
500 (isa<CXXRecordDecl>(ND) &&
501 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
502 AsNestedNameSpecifier = true;
503 return true;
504 }
505
Douglas Gregore495b7f2010-01-14 00:20:49 +0000506 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000507 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000508 // ... then it must be interesting!
509 return true;
510}
511
Douglas Gregor6660d842010-01-14 00:41:07 +0000512bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
513 NamedDecl *Hiding) {
514 // In C, there is no way to refer to a hidden name.
515 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
516 // name if we introduce the tag type.
517 if (!SemaRef.getLangOptions().CPlusPlus)
518 return true;
519
Sebastian Redl7a126a42010-08-31 00:36:30 +0000520 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000521
522 // There is no way to qualify a name declared in a function or method.
523 if (HiddenCtx->isFunctionOrMethod())
524 return true;
525
Sebastian Redl7a126a42010-08-31 00:36:30 +0000526 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000527 return true;
528
529 // We can refer to the result with the appropriate qualification. Do it.
530 R.Hidden = true;
531 R.QualifierIsInformative = false;
532
533 if (!R.Qualifier)
534 R.Qualifier = getRequiredQualification(SemaRef.Context,
535 CurContext,
536 R.Declaration->getDeclContext());
537 return false;
538}
539
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000540/// \brief A simplified classification of types used to determine whether two
541/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000542SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000543 switch (T->getTypeClass()) {
544 case Type::Builtin:
545 switch (cast<BuiltinType>(T)->getKind()) {
546 case BuiltinType::Void:
547 return STC_Void;
548
549 case BuiltinType::NullPtr:
550 return STC_Pointer;
551
552 case BuiltinType::Overload:
553 case BuiltinType::Dependent:
554 case BuiltinType::UndeducedAuto:
555 return STC_Other;
556
557 case BuiltinType::ObjCId:
558 case BuiltinType::ObjCClass:
559 case BuiltinType::ObjCSel:
560 return STC_ObjectiveC;
561
562 default:
563 return STC_Arithmetic;
564 }
565 return STC_Other;
566
567 case Type::Complex:
568 return STC_Arithmetic;
569
570 case Type::Pointer:
571 return STC_Pointer;
572
573 case Type::BlockPointer:
574 return STC_Block;
575
576 case Type::LValueReference:
577 case Type::RValueReference:
578 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
579
580 case Type::ConstantArray:
581 case Type::IncompleteArray:
582 case Type::VariableArray:
583 case Type::DependentSizedArray:
584 return STC_Array;
585
586 case Type::DependentSizedExtVector:
587 case Type::Vector:
588 case Type::ExtVector:
589 return STC_Arithmetic;
590
591 case Type::FunctionProto:
592 case Type::FunctionNoProto:
593 return STC_Function;
594
595 case Type::Record:
596 return STC_Record;
597
598 case Type::Enum:
599 return STC_Arithmetic;
600
601 case Type::ObjCObject:
602 case Type::ObjCInterface:
603 case Type::ObjCObjectPointer:
604 return STC_ObjectiveC;
605
606 default:
607 return STC_Other;
608 }
609}
610
611/// \brief Get the type that a given expression will have if this declaration
612/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000613QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000614 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
615
616 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
617 return C.getTypeDeclType(Type);
618 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
619 return C.getObjCInterfaceType(Iface);
620
621 QualType T;
622 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000623 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000624 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000625 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000626 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000627 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000628 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
629 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
630 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
631 T = Property->getType();
632 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
633 T = Value->getType();
634 else
635 return QualType();
636
637 return T.getNonReferenceType();
638}
639
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000640void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
641 // If this is an Objective-C method declaration whose selector matches our
642 // preferred selector, give it a priority boost.
643 if (!PreferredSelector.isNull())
644 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
645 if (PreferredSelector == Method->getSelector())
646 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000647
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000648 // If we have a preferred type, adjust the priority for results with exactly-
649 // matching or nearly-matching types.
650 if (!PreferredType.isNull()) {
651 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
652 if (!T.isNull()) {
653 CanQualType TC = SemaRef.Context.getCanonicalType(T);
654 // Check for exactly-matching types (modulo qualifiers).
655 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
656 R.Priority /= CCF_ExactTypeMatch;
657 // Check for nearly-matching types, based on classification of each.
658 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000659 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000660 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
661 R.Priority /= CCF_SimilarTypeMatch;
662 }
663 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000664}
665
Douglas Gregore495b7f2010-01-14 00:20:49 +0000666void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
667 assert(!ShadowMaps.empty() && "Must enter into a results scope");
668
669 if (R.Kind != Result::RK_Declaration) {
670 // For non-declaration results, just add the result.
671 Results.push_back(R);
672 return;
673 }
674
675 // Look through using declarations.
676 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
677 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
678 return;
679 }
680
681 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
682 unsigned IDNS = CanonDecl->getIdentifierNamespace();
683
Douglas Gregor45bcd432010-01-14 03:21:49 +0000684 bool AsNestedNameSpecifier = false;
685 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000686 return;
687
Douglas Gregor86d9a522009-09-21 16:56:56 +0000688 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000689 ShadowMapEntry::iterator I, IEnd;
690 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
691 if (NamePos != SMap.end()) {
692 I = NamePos->second.begin();
693 IEnd = NamePos->second.end();
694 }
695
696 for (; I != IEnd; ++I) {
697 NamedDecl *ND = I->first;
698 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000699 if (ND->getCanonicalDecl() == CanonDecl) {
700 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000701 Results[Index].Declaration = R.Declaration;
702
Douglas Gregor86d9a522009-09-21 16:56:56 +0000703 // We're done.
704 return;
705 }
706 }
707
708 // This is a new declaration in this scope. However, check whether this
709 // declaration name is hidden by a similarly-named declaration in an outer
710 // scope.
711 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
712 --SMEnd;
713 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000714 ShadowMapEntry::iterator I, IEnd;
715 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
716 if (NamePos != SM->end()) {
717 I = NamePos->second.begin();
718 IEnd = NamePos->second.end();
719 }
720 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000721 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000722 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000723 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
724 Decl::IDNS_ObjCProtocol)))
725 continue;
726
727 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000728 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000729 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000730 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000731 continue;
732
733 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000734 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000735 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000736
737 break;
738 }
739 }
740
741 // Make sure that any given declaration only shows up in the result set once.
742 if (!AllDeclsFound.insert(CanonDecl))
743 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000744
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000745 // If the filter is for nested-name-specifiers, then this result starts a
746 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000747 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000748 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000749 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000750 } else
751 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000752
Douglas Gregor0563c262009-09-22 23:15:58 +0000753 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000754 if (R.QualifierIsInformative && !R.Qualifier &&
755 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000756 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,
761 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
762 else
763 R.QualifierIsInformative = false;
764 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000765
Douglas Gregor86d9a522009-09-21 16:56:56 +0000766 // Insert this result into the set of results and into the current shadow
767 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000768 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000769 Results.push_back(R);
770}
771
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000772void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000773 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000774 if (R.Kind != Result::RK_Declaration) {
775 // For non-declaration results, just add the result.
776 Results.push_back(R);
777 return;
778 }
779
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000780 // Look through using declarations.
781 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
782 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
783 return;
784 }
785
Douglas Gregor45bcd432010-01-14 03:21:49 +0000786 bool AsNestedNameSpecifier = false;
787 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000788 return;
789
790 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
791 return;
792
793 // Make sure that any given declaration only shows up in the result set once.
794 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
795 return;
796
797 // If the filter is for nested-name-specifiers, then this result starts a
798 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000799 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000800 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000801 R.Priority = CCP_NestedNameSpecifier;
802 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000803 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
804 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000805 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000806 R.QualifierIsInformative = true;
807
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000808 // If this result is supposed to have an informative qualifier, add one.
809 if (R.QualifierIsInformative && !R.Qualifier &&
810 !R.StartsNestedNameSpecifier) {
811 DeclContext *Ctx = R.Declaration->getDeclContext();
812 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
813 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
814 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
815 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000816 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000817 else
818 R.QualifierIsInformative = false;
819 }
820
Douglas Gregor12e13132010-05-26 22:00:08 +0000821 // Adjust the priority if this result comes from a base class.
822 if (InBaseClass)
823 R.Priority += CCD_InBaseClass;
824
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000825 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000826
Douglas Gregor3cdee122010-08-26 16:36:48 +0000827 if (HasObjectTypeQualifiers)
828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
829 if (Method->isInstance()) {
830 Qualifiers MethodQuals
831 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
832 if (ObjectTypeQualifiers == MethodQuals)
833 R.Priority += CCD_ObjectQualifierMatch;
834 else if (ObjectTypeQualifiers - MethodQuals) {
835 // The method cannot be invoked, because doing so would drop
836 // qualifiers.
837 return;
838 }
839 }
840
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000841 // Insert this result into the set of results.
842 Results.push_back(R);
843}
844
Douglas Gregora4477812010-01-14 16:01:26 +0000845void ResultBuilder::AddResult(Result R) {
846 assert(R.Kind != Result::RK_Declaration &&
847 "Declaration results need more context");
848 Results.push_back(R);
849}
850
Douglas Gregor86d9a522009-09-21 16:56:56 +0000851/// \brief Enter into a new scope.
852void ResultBuilder::EnterNewScope() {
853 ShadowMaps.push_back(ShadowMap());
854}
855
856/// \brief Exit from the current scope.
857void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000858 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
859 EEnd = ShadowMaps.back().end();
860 E != EEnd;
861 ++E)
862 E->second.Destroy();
863
Douglas Gregor86d9a522009-09-21 16:56:56 +0000864 ShadowMaps.pop_back();
865}
866
Douglas Gregor791215b2009-09-21 20:51:25 +0000867/// \brief Determines whether this given declaration will be found by
868/// ordinary name lookup.
869bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000870 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
871
Douglas Gregor791215b2009-09-21 20:51:25 +0000872 unsigned IDNS = Decl::IDNS_Ordinary;
873 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000874 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000875 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
876 return true;
877
Douglas Gregor791215b2009-09-21 20:51:25 +0000878 return ND->getIdentifierNamespace() & IDNS;
879}
880
Douglas Gregor01dfea02010-01-10 23:08:15 +0000881/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000882/// ordinary name lookup but is not a type name.
883bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
884 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
885 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
886 return false;
887
888 unsigned IDNS = Decl::IDNS_Ordinary;
889 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000890 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000891 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
892 return true;
893
894 return ND->getIdentifierNamespace() & IDNS;
895}
896
Douglas Gregorf9578432010-07-28 21:50:18 +0000897bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
898 if (!IsOrdinaryNonTypeName(ND))
899 return 0;
900
901 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
902 if (VD->getType()->isIntegralOrEnumerationType())
903 return true;
904
905 return false;
906}
907
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000908/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000909/// ordinary name lookup.
910bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000911 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
912
Douglas Gregor01dfea02010-01-10 23:08:15 +0000913 unsigned IDNS = Decl::IDNS_Ordinary;
914 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000915 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000916
917 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000918 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
919 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000920}
921
Douglas Gregor86d9a522009-09-21 16:56:56 +0000922/// \brief Determines whether the given declaration is suitable as the
923/// start of a C++ nested-name-specifier, e.g., a class or namespace.
924bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
925 // Allow us to find class templates, too.
926 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
927 ND = ClassTemplate->getTemplatedDecl();
928
929 return SemaRef.isAcceptableNestedNameSpecifier(ND);
930}
931
932/// \brief Determines whether the given declaration is an enumeration.
933bool ResultBuilder::IsEnum(NamedDecl *ND) const {
934 return isa<EnumDecl>(ND);
935}
936
937/// \brief Determines whether the given declaration is a class or struct.
938bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
939 // Allow us to find class templates, too.
940 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
941 ND = ClassTemplate->getTemplatedDecl();
942
943 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000944 return RD->getTagKind() == TTK_Class ||
945 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000946
947 return false;
948}
949
950/// \brief Determines whether the given declaration is a union.
951bool ResultBuilder::IsUnion(NamedDecl *ND) const {
952 // Allow us to find class templates, too.
953 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
954 ND = ClassTemplate->getTemplatedDecl();
955
956 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000957 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000958
959 return false;
960}
961
962/// \brief Determines whether the given declaration is a namespace.
963bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
964 return isa<NamespaceDecl>(ND);
965}
966
967/// \brief Determines whether the given declaration is a namespace or
968/// namespace alias.
969bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
970 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
971}
972
Douglas Gregor76282942009-12-11 17:31:05 +0000973/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000974bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +0000975 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
976 ND = Using->getTargetDecl();
977
978 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979}
980
Douglas Gregor76282942009-12-11 17:31:05 +0000981/// \brief Determines which members of a class should be visible via
982/// "." or "->". Only value declarations, nested name specifiers, and
983/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000984bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000985 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
986 ND = Using->getTargetDecl();
987
Douglas Gregorce821962009-12-11 18:14:22 +0000988 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
989 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000990}
991
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000992static bool isObjCReceiverType(ASTContext &C, QualType T) {
993 T = C.getCanonicalType(T);
994 switch (T->getTypeClass()) {
995 case Type::ObjCObject:
996 case Type::ObjCInterface:
997 case Type::ObjCObjectPointer:
998 return true;
999
1000 case Type::Builtin:
1001 switch (cast<BuiltinType>(T)->getKind()) {
1002 case BuiltinType::ObjCId:
1003 case BuiltinType::ObjCClass:
1004 case BuiltinType::ObjCSel:
1005 return true;
1006
1007 default:
1008 break;
1009 }
1010 return false;
1011
1012 default:
1013 break;
1014 }
1015
1016 if (!C.getLangOptions().CPlusPlus)
1017 return false;
1018
1019 // FIXME: We could perform more analysis here to determine whether a
1020 // particular class type has any conversions to Objective-C types. For now,
1021 // just accept all class types.
1022 return T->isDependentType() || T->isRecordType();
1023}
1024
1025bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1026 QualType T = getDeclUsageType(SemaRef.Context, ND);
1027 if (T.isNull())
1028 return false;
1029
1030 T = SemaRef.Context.getBaseElementType(T);
1031 return isObjCReceiverType(SemaRef.Context, T);
1032}
1033
Douglas Gregorfb629412010-08-23 21:17:50 +00001034bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1035 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1036 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1037 return false;
1038
1039 QualType T = getDeclUsageType(SemaRef.Context, ND);
1040 if (T.isNull())
1041 return false;
1042
1043 T = SemaRef.Context.getBaseElementType(T);
1044 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1045 T->isObjCIdType() ||
1046 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1047}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001048
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001049/// \rief Determines whether the given declaration is an Objective-C
1050/// instance variable.
1051bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1052 return isa<ObjCIvarDecl>(ND);
1053}
1054
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001055namespace {
1056 /// \brief Visible declaration consumer that adds a code-completion result
1057 /// for each visible declaration.
1058 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1059 ResultBuilder &Results;
1060 DeclContext *CurContext;
1061
1062 public:
1063 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1064 : Results(Results), CurContext(CurContext) { }
1065
Douglas Gregor0cc84042010-01-14 15:47:35 +00001066 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1067 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001068 }
1069 };
1070}
1071
Douglas Gregor86d9a522009-09-21 16:56:56 +00001072/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001073static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001074 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001075 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001076 Results.AddResult(Result("short", CCP_Type));
1077 Results.AddResult(Result("long", CCP_Type));
1078 Results.AddResult(Result("signed", CCP_Type));
1079 Results.AddResult(Result("unsigned", CCP_Type));
1080 Results.AddResult(Result("void", CCP_Type));
1081 Results.AddResult(Result("char", CCP_Type));
1082 Results.AddResult(Result("int", CCP_Type));
1083 Results.AddResult(Result("float", CCP_Type));
1084 Results.AddResult(Result("double", CCP_Type));
1085 Results.AddResult(Result("enum", CCP_Type));
1086 Results.AddResult(Result("struct", CCP_Type));
1087 Results.AddResult(Result("union", CCP_Type));
1088 Results.AddResult(Result("const", CCP_Type));
1089 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001090
Douglas Gregor86d9a522009-09-21 16:56:56 +00001091 if (LangOpts.C99) {
1092 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001093 Results.AddResult(Result("_Complex", CCP_Type));
1094 Results.AddResult(Result("_Imaginary", CCP_Type));
1095 Results.AddResult(Result("_Bool", CCP_Type));
1096 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001097 }
1098
1099 if (LangOpts.CPlusPlus) {
1100 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001101 Results.AddResult(Result("bool", CCP_Type +
1102 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001103 Results.AddResult(Result("class", CCP_Type));
1104 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001105
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001106 // typename qualified-id
1107 CodeCompletionString *Pattern = new CodeCompletionString;
1108 Pattern->AddTypedTextChunk("typename");
1109 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1110 Pattern->AddPlaceholderChunk("qualifier");
1111 Pattern->AddTextChunk("::");
1112 Pattern->AddPlaceholderChunk("name");
1113 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001114
Douglas Gregor86d9a522009-09-21 16:56:56 +00001115 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001116 Results.AddResult(Result("auto", CCP_Type));
1117 Results.AddResult(Result("char16_t", CCP_Type));
1118 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001119
1120 CodeCompletionString *Pattern = new CodeCompletionString;
1121 Pattern->AddTypedTextChunk("decltype");
1122 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1123 Pattern->AddPlaceholderChunk("expression");
1124 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1125 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001126 }
1127 }
1128
1129 // GNU extensions
1130 if (LangOpts.GNUMode) {
1131 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001132 // Results.AddResult(Result("_Decimal32"));
1133 // Results.AddResult(Result("_Decimal64"));
1134 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001135
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001136 CodeCompletionString *Pattern = new CodeCompletionString;
1137 Pattern->AddTypedTextChunk("typeof");
1138 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1139 Pattern->AddPlaceholderChunk("expression");
1140 Results.AddResult(Result(Pattern));
1141
1142 Pattern = new CodeCompletionString;
1143 Pattern->AddTypedTextChunk("typeof");
1144 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1145 Pattern->AddPlaceholderChunk("type");
1146 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1147 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001148 }
1149}
1150
John McCallf312b1e2010-08-26 23:41:50 +00001151static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001152 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001153 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001154 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001155 // Note: we don't suggest either "auto" or "register", because both
1156 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1157 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001158 Results.AddResult(Result("extern"));
1159 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001160}
1161
John McCallf312b1e2010-08-26 23:41:50 +00001162static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001163 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001164 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001165 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001166 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001167 case Sema::PCC_Class:
1168 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001169 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001170 Results.AddResult(Result("explicit"));
1171 Results.AddResult(Result("friend"));
1172 Results.AddResult(Result("mutable"));
1173 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001174 }
1175 // Fall through
1176
John McCallf312b1e2010-08-26 23:41:50 +00001177 case Sema::PCC_ObjCInterface:
1178 case Sema::PCC_ObjCImplementation:
1179 case Sema::PCC_Namespace:
1180 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001181 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001182 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001183 break;
1184
John McCallf312b1e2010-08-26 23:41:50 +00001185 case Sema::PCC_ObjCInstanceVariableList:
1186 case Sema::PCC_Expression:
1187 case Sema::PCC_Statement:
1188 case Sema::PCC_ForInit:
1189 case Sema::PCC_Condition:
1190 case Sema::PCC_RecoveryInFunction:
1191 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001192 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001193 break;
1194 }
1195}
1196
Douglas Gregorbca403c2010-01-13 23:51:12 +00001197static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1198static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1199static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001200 ResultBuilder &Results,
1201 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001203 ResultBuilder &Results,
1204 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001205static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001206 ResultBuilder &Results,
1207 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001208static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001209
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001210static void AddTypedefResult(ResultBuilder &Results) {
1211 CodeCompletionString *Pattern = new CodeCompletionString;
1212 Pattern->AddTypedTextChunk("typedef");
1213 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1214 Pattern->AddPlaceholderChunk("type");
1215 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1216 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001217 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001218}
1219
John McCallf312b1e2010-08-26 23:41:50 +00001220static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001221 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001222 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001223 case Sema::PCC_Namespace:
1224 case Sema::PCC_Class:
1225 case Sema::PCC_ObjCInstanceVariableList:
1226 case Sema::PCC_Template:
1227 case Sema::PCC_MemberTemplate:
1228 case Sema::PCC_Statement:
1229 case Sema::PCC_RecoveryInFunction:
1230 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001231 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001232 return true;
1233
John McCallf312b1e2010-08-26 23:41:50 +00001234 case Sema::PCC_Expression:
1235 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001236 return LangOpts.CPlusPlus;
1237
1238 case Sema::PCC_ObjCInterface:
1239 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001240 return false;
1241
John McCallf312b1e2010-08-26 23:41:50 +00001242 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001243 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001244 }
1245
1246 return false;
1247}
1248
Douglas Gregor01dfea02010-01-10 23:08:15 +00001249/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001250static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001251 Scope *S,
1252 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001253 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001254 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001255 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001256 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001257 if (SemaRef.getLangOptions().CPlusPlus) {
1258 CodeCompletionString *Pattern = 0;
1259
1260 if (Results.includeCodePatterns()) {
1261 // namespace <identifier> { declarations }
1262 CodeCompletionString *Pattern = new CodeCompletionString;
1263 Pattern->AddTypedTextChunk("namespace");
1264 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1265 Pattern->AddPlaceholderChunk("identifier");
1266 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1267 Pattern->AddPlaceholderChunk("declarations");
1268 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1269 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1270 Results.AddResult(Result(Pattern));
1271 }
1272
Douglas Gregor01dfea02010-01-10 23:08:15 +00001273 // namespace identifier = identifier ;
1274 Pattern = new CodeCompletionString;
1275 Pattern->AddTypedTextChunk("namespace");
1276 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001277 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001279 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001280 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281
1282 // Using directives
1283 Pattern = new CodeCompletionString;
1284 Pattern->AddTypedTextChunk("using");
1285 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1286 Pattern->AddTextChunk("namespace");
1287 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1288 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001289 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290
1291 // asm(string-literal)
1292 Pattern = new CodeCompletionString;
1293 Pattern->AddTypedTextChunk("asm");
1294 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1295 Pattern->AddPlaceholderChunk("string-literal");
1296 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001297 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001298
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001299 if (Results.includeCodePatterns()) {
1300 // Explicit template instantiation
1301 Pattern = new CodeCompletionString;
1302 Pattern->AddTypedTextChunk("template");
1303 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1304 Pattern->AddPlaceholderChunk("declaration");
1305 Results.AddResult(Result(Pattern));
1306 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001308
1309 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001310 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001311
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001312 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001313 // Fall through
1314
John McCallf312b1e2010-08-26 23:41:50 +00001315 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001316 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001317 // Using declaration
1318 CodeCompletionString *Pattern = new CodeCompletionString;
1319 Pattern->AddTypedTextChunk("using");
1320 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001321 Pattern->AddPlaceholderChunk("qualifier");
1322 Pattern->AddTextChunk("::");
1323 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001324 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001325
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001326 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001327 if (SemaRef.CurContext->isDependentContext()) {
1328 Pattern = new CodeCompletionString;
1329 Pattern->AddTypedTextChunk("using");
1330 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1331 Pattern->AddTextChunk("typename");
1332 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001333 Pattern->AddPlaceholderChunk("qualifier");
1334 Pattern->AddTextChunk("::");
1335 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001336 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001337 }
1338
John McCallf312b1e2010-08-26 23:41:50 +00001339 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001340 AddTypedefResult(Results);
1341
Douglas Gregor01dfea02010-01-10 23:08:15 +00001342 // public:
1343 Pattern = new CodeCompletionString;
1344 Pattern->AddTypedTextChunk("public");
1345 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001346 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001347
1348 // protected:
1349 Pattern = new CodeCompletionString;
1350 Pattern->AddTypedTextChunk("protected");
1351 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001352 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001353
1354 // private:
1355 Pattern = new CodeCompletionString;
1356 Pattern->AddTypedTextChunk("private");
1357 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001358 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001359 }
1360 }
1361 // Fall through
1362
John McCallf312b1e2010-08-26 23:41:50 +00001363 case Sema::PCC_Template:
1364 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001365 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001366 // template < parameters >
1367 CodeCompletionString *Pattern = new CodeCompletionString;
1368 Pattern->AddTypedTextChunk("template");
1369 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1370 Pattern->AddPlaceholderChunk("parameters");
1371 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001372 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001373 }
1374
Douglas Gregorbca403c2010-01-13 23:51:12 +00001375 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1376 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377 break;
1378
John McCallf312b1e2010-08-26 23:41:50 +00001379 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001380 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1381 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1382 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001383 break;
1384
John McCallf312b1e2010-08-26 23:41:50 +00001385 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001386 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1387 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1388 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001389 break;
1390
John McCallf312b1e2010-08-26 23:41:50 +00001391 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001392 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001393 break;
1394
John McCallf312b1e2010-08-26 23:41:50 +00001395 case Sema::PCC_RecoveryInFunction:
1396 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001397 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001398
1399 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001400 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001401 Pattern = new CodeCompletionString;
1402 Pattern->AddTypedTextChunk("try");
1403 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1404 Pattern->AddPlaceholderChunk("statements");
1405 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1406 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1407 Pattern->AddTextChunk("catch");
1408 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1409 Pattern->AddPlaceholderChunk("declaration");
1410 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1411 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1412 Pattern->AddPlaceholderChunk("statements");
1413 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1414 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001415 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001416 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001417 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001418 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001419
Douglas Gregord8e8a582010-05-25 21:41:55 +00001420 if (Results.includeCodePatterns()) {
1421 // if (condition) { statements }
1422 Pattern = new CodeCompletionString;
1423 Pattern->AddTypedTextChunk("if");
1424 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1425 if (SemaRef.getLangOptions().CPlusPlus)
1426 Pattern->AddPlaceholderChunk("condition");
1427 else
1428 Pattern->AddPlaceholderChunk("expression");
1429 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1430 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1431 Pattern->AddPlaceholderChunk("statements");
1432 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1433 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1434 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001435
Douglas Gregord8e8a582010-05-25 21:41:55 +00001436 // switch (condition) { }
1437 Pattern = new CodeCompletionString;
1438 Pattern->AddTypedTextChunk("switch");
1439 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1440 if (SemaRef.getLangOptions().CPlusPlus)
1441 Pattern->AddPlaceholderChunk("condition");
1442 else
1443 Pattern->AddPlaceholderChunk("expression");
1444 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1445 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1446 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1447 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1448 Results.AddResult(Result(Pattern));
1449 }
1450
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001452 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001453 // case expression:
1454 Pattern = new CodeCompletionString;
1455 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001456 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001457 Pattern->AddPlaceholderChunk("expression");
1458 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001459 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460
1461 // default:
1462 Pattern = new CodeCompletionString;
1463 Pattern->AddTypedTextChunk("default");
1464 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001465 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001466 }
1467
Douglas Gregord8e8a582010-05-25 21:41:55 +00001468 if (Results.includeCodePatterns()) {
1469 /// while (condition) { statements }
1470 Pattern = new CodeCompletionString;
1471 Pattern->AddTypedTextChunk("while");
1472 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1473 if (SemaRef.getLangOptions().CPlusPlus)
1474 Pattern->AddPlaceholderChunk("condition");
1475 else
1476 Pattern->AddPlaceholderChunk("expression");
1477 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1478 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1479 Pattern->AddPlaceholderChunk("statements");
1480 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1481 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1482 Results.AddResult(Result(Pattern));
1483
1484 // do { statements } while ( expression );
1485 Pattern = new CodeCompletionString;
1486 Pattern->AddTypedTextChunk("do");
1487 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1488 Pattern->AddPlaceholderChunk("statements");
1489 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1490 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1491 Pattern->AddTextChunk("while");
1492 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001493 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001494 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1495 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001496
Douglas Gregord8e8a582010-05-25 21:41:55 +00001497 // for ( for-init-statement ; condition ; expression ) { statements }
1498 Pattern = new CodeCompletionString;
1499 Pattern->AddTypedTextChunk("for");
1500 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1501 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1502 Pattern->AddPlaceholderChunk("init-statement");
1503 else
1504 Pattern->AddPlaceholderChunk("init-expression");
1505 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1506 Pattern->AddPlaceholderChunk("condition");
1507 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1508 Pattern->AddPlaceholderChunk("inc-expression");
1509 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1510 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1511 Pattern->AddPlaceholderChunk("statements");
1512 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1513 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1514 Results.AddResult(Result(Pattern));
1515 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001516
1517 if (S->getContinueParent()) {
1518 // continue ;
1519 Pattern = new CodeCompletionString;
1520 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001521 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001522 }
1523
1524 if (S->getBreakParent()) {
1525 // break ;
1526 Pattern = new CodeCompletionString;
1527 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001528 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001529 }
1530
1531 // "return expression ;" or "return ;", depending on whether we
1532 // know the function is void or not.
1533 bool isVoid = false;
1534 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1535 isVoid = Function->getResultType()->isVoidType();
1536 else if (ObjCMethodDecl *Method
1537 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1538 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001539 else if (SemaRef.getCurBlock() &&
1540 !SemaRef.getCurBlock()->ReturnType.isNull())
1541 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001542 Pattern = new CodeCompletionString;
1543 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001544 if (!isVoid) {
1545 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001546 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001547 }
Douglas Gregora4477812010-01-14 16:01:26 +00001548 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001549
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001550 // goto identifier ;
1551 Pattern = new CodeCompletionString;
1552 Pattern->AddTypedTextChunk("goto");
1553 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1554 Pattern->AddPlaceholderChunk("label");
1555 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001556
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001557 // Using directives
1558 Pattern = new CodeCompletionString;
1559 Pattern->AddTypedTextChunk("using");
1560 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1561 Pattern->AddTextChunk("namespace");
1562 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1563 Pattern->AddPlaceholderChunk("identifier");
1564 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001565 }
1566
1567 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001568 case Sema::PCC_ForInit:
1569 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001570 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001571 // Fall through: conditions and statements can have expressions.
1572
Douglas Gregor02688102010-09-14 23:59:36 +00001573 case Sema::PCC_ParenthesizedExpression:
John McCallf312b1e2010-08-26 23:41:50 +00001574 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001575 CodeCompletionString *Pattern = 0;
1576 if (SemaRef.getLangOptions().CPlusPlus) {
1577 // 'this', if we're in a non-static member function.
1578 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1579 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001580 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001581
1582 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001583 Results.AddResult(Result("true"));
1584 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001585
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001586 // dynamic_cast < type-id > ( expression )
1587 Pattern = new CodeCompletionString;
1588 Pattern->AddTypedTextChunk("dynamic_cast");
1589 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1590 Pattern->AddPlaceholderChunk("type");
1591 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1592 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1593 Pattern->AddPlaceholderChunk("expression");
1594 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1595 Results.AddResult(Result(Pattern));
1596
1597 // static_cast < type-id > ( expression )
1598 Pattern = new CodeCompletionString;
1599 Pattern->AddTypedTextChunk("static_cast");
1600 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1601 Pattern->AddPlaceholderChunk("type");
1602 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1603 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1604 Pattern->AddPlaceholderChunk("expression");
1605 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1606 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001607
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001608 // reinterpret_cast < type-id > ( expression )
1609 Pattern = new CodeCompletionString;
1610 Pattern->AddTypedTextChunk("reinterpret_cast");
1611 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1612 Pattern->AddPlaceholderChunk("type");
1613 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1614 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1615 Pattern->AddPlaceholderChunk("expression");
1616 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1617 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001618
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001619 // const_cast < type-id > ( expression )
1620 Pattern = new CodeCompletionString;
1621 Pattern->AddTypedTextChunk("const_cast");
1622 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1623 Pattern->AddPlaceholderChunk("type");
1624 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1625 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1626 Pattern->AddPlaceholderChunk("expression");
1627 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1628 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001629
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001630 // typeid ( expression-or-type )
1631 Pattern = new CodeCompletionString;
1632 Pattern->AddTypedTextChunk("typeid");
1633 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1634 Pattern->AddPlaceholderChunk("expression-or-type");
1635 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1636 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001637
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001638 // new T ( ... )
1639 Pattern = new CodeCompletionString;
1640 Pattern->AddTypedTextChunk("new");
1641 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1642 Pattern->AddPlaceholderChunk("type");
1643 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1644 Pattern->AddPlaceholderChunk("expressions");
1645 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1646 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001647
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001648 // new T [ ] ( ... )
1649 Pattern = new CodeCompletionString;
1650 Pattern->AddTypedTextChunk("new");
1651 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1652 Pattern->AddPlaceholderChunk("type");
1653 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1654 Pattern->AddPlaceholderChunk("size");
1655 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1656 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1657 Pattern->AddPlaceholderChunk("expressions");
1658 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1659 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001660
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001661 // delete expression
1662 Pattern = new CodeCompletionString;
1663 Pattern->AddTypedTextChunk("delete");
1664 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1665 Pattern->AddPlaceholderChunk("expression");
1666 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001667
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001668 // delete [] expression
1669 Pattern = new CodeCompletionString;
1670 Pattern->AddTypedTextChunk("delete");
1671 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1672 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1673 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1674 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1675 Pattern->AddPlaceholderChunk("expression");
1676 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001677
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001678 // throw expression
1679 Pattern = new CodeCompletionString;
1680 Pattern->AddTypedTextChunk("throw");
1681 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1682 Pattern->AddPlaceholderChunk("expression");
1683 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001684
1685 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001686 }
1687
1688 if (SemaRef.getLangOptions().ObjC1) {
1689 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001690 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1691 // The interface can be NULL.
1692 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1693 if (ID->getSuperClass())
1694 Results.AddResult(Result("super"));
1695 }
1696
Douglas Gregorbca403c2010-01-13 23:51:12 +00001697 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001698 }
1699
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001700 // sizeof expression
1701 Pattern = new CodeCompletionString;
1702 Pattern->AddTypedTextChunk("sizeof");
1703 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1704 Pattern->AddPlaceholderChunk("expression-or-type");
1705 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1706 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001707 break;
1708 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001709
John McCallf312b1e2010-08-26 23:41:50 +00001710 case Sema::PCC_Type:
Douglas Gregord32b0222010-08-24 01:06:58 +00001711 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001712 }
1713
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001714 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1715 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001716
John McCallf312b1e2010-08-26 23:41:50 +00001717 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001718 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001719}
1720
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001721/// \brief If the given declaration has an associated type, add it as a result
1722/// type chunk.
1723static void AddResultTypeChunk(ASTContext &Context,
1724 NamedDecl *ND,
1725 CodeCompletionString *Result) {
1726 if (!ND)
1727 return;
1728
1729 // Determine the type of the declaration (if it has a type).
1730 QualType T;
1731 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1732 T = Function->getResultType();
1733 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1734 T = Method->getResultType();
1735 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1736 T = FunTmpl->getTemplatedDecl()->getResultType();
1737 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1738 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1739 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1740 /* Do nothing: ignore unresolved using declarations*/
1741 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1742 T = Value->getType();
1743 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1744 T = Property->getType();
1745
1746 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1747 return;
1748
Douglas Gregor84139d62010-04-05 21:25:31 +00001749 PrintingPolicy Policy(Context.PrintingPolicy);
1750 Policy.AnonymousTagLocations = false;
1751
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001752 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001753 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001754 Result->AddResultTypeChunk(TypeStr);
1755}
1756
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001757static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1758 CodeCompletionString *Result) {
1759 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1760 if (Sentinel->getSentinel() == 0) {
1761 if (Context.getLangOptions().ObjC1 &&
1762 Context.Idents.get("nil").hasMacroDefinition())
1763 Result->AddTextChunk(", nil");
1764 else if (Context.Idents.get("NULL").hasMacroDefinition())
1765 Result->AddTextChunk(", NULL");
1766 else
1767 Result->AddTextChunk(", (void*)0");
1768 }
1769}
1770
Douglas Gregor83482d12010-08-24 16:15:59 +00001771static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001772 ParmVarDecl *Param,
1773 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001774 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1775 if (Param->getType()->isDependentType() ||
1776 !Param->getType()->isBlockPointerType()) {
1777 // The argument for a dependent or non-block parameter is a placeholder
1778 // containing that parameter's type.
1779 std::string Result;
1780
Douglas Gregoraba48082010-08-29 19:47:46 +00001781 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001782 Result = Param->getIdentifier()->getName();
1783
1784 Param->getType().getAsStringInternal(Result,
1785 Context.PrintingPolicy);
1786
1787 if (ObjCMethodParam) {
1788 Result = "(" + Result;
1789 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001790 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001791 Result += Param->getIdentifier()->getName();
1792 }
1793 return Result;
1794 }
1795
1796 // The argument for a block pointer parameter is a block literal with
1797 // the appropriate type.
1798 FunctionProtoTypeLoc *Block = 0;
1799 TypeLoc TL;
1800 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1801 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1802 while (true) {
1803 // Look through typedefs.
1804 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1805 if (TypeSourceInfo *InnerTSInfo
1806 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1807 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1808 continue;
1809 }
1810 }
1811
1812 // Look through qualified types
1813 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1814 TL = QualifiedTL->getUnqualifiedLoc();
1815 continue;
1816 }
1817
1818 // Try to get the function prototype behind the block pointer type,
1819 // then we're done.
1820 if (BlockPointerTypeLoc *BlockPtr
1821 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1822 TL = BlockPtr->getPointeeLoc();
1823 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1824 }
1825 break;
1826 }
1827 }
1828
1829 if (!Block) {
1830 // We were unable to find a FunctionProtoTypeLoc with parameter names
1831 // for the block; just use the parameter type as a placeholder.
1832 std::string Result;
1833 Param->getType().getUnqualifiedType().
1834 getAsStringInternal(Result, Context.PrintingPolicy);
1835
1836 if (ObjCMethodParam) {
1837 Result = "(" + Result;
1838 Result += ")";
1839 if (Param->getIdentifier())
1840 Result += Param->getIdentifier()->getName();
1841 }
1842
1843 return Result;
1844 }
1845
1846 // We have the function prototype behind the block pointer type, as it was
1847 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001848 std::string Result;
1849 QualType ResultType = Block->getTypePtr()->getResultType();
1850 if (!ResultType->isVoidType())
1851 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1852
1853 Result = '^' + Result;
1854 if (Block->getNumArgs() == 0) {
1855 if (Block->getTypePtr()->isVariadic())
1856 Result += "(...)";
1857 } else {
1858 Result += "(";
1859 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1860 if (I)
1861 Result += ", ";
1862 Result += FormatFunctionParameter(Context, Block->getArg(I));
1863
1864 if (I == N - 1 && Block->getTypePtr()->isVariadic())
1865 Result += ", ...";
1866 }
1867 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00001868 }
Douglas Gregor38276252010-09-08 22:47:51 +00001869
Douglas Gregor83482d12010-08-24 16:15:59 +00001870 return Result;
1871}
1872
Douglas Gregor86d9a522009-09-21 16:56:56 +00001873/// \brief Add function parameter chunks to the given code completion string.
1874static void AddFunctionParameterChunks(ASTContext &Context,
1875 FunctionDecl *Function,
1876 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001877 typedef CodeCompletionString::Chunk Chunk;
1878
Douglas Gregor86d9a522009-09-21 16:56:56 +00001879 CodeCompletionString *CCStr = Result;
1880
1881 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1882 ParmVarDecl *Param = Function->getParamDecl(P);
1883
1884 if (Param->hasDefaultArg()) {
1885 // When we see an optional default argument, put that argument and
1886 // the remaining default arguments into a new, optional string.
1887 CodeCompletionString *Opt = new CodeCompletionString;
1888 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1889 CCStr = Opt;
1890 }
1891
1892 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001893 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001894
1895 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001896 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1897
Douglas Gregore17794f2010-08-31 05:13:43 +00001898 if (Function->isVariadic() && P == N - 1)
1899 PlaceholderStr += ", ...";
1900
Douglas Gregor86d9a522009-09-21 16:56:56 +00001901 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001902 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001903 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001904
1905 if (const FunctionProtoType *Proto
1906 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001907 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00001908 if (Proto->getNumArgs() == 0)
1909 CCStr->AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001910
1911 MaybeAddSentinel(Context, Function, CCStr);
1912 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001913}
1914
1915/// \brief Add template parameter chunks to the given code completion string.
1916static void AddTemplateParameterChunks(ASTContext &Context,
1917 TemplateDecl *Template,
1918 CodeCompletionString *Result,
1919 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001920 typedef CodeCompletionString::Chunk Chunk;
1921
Douglas Gregor86d9a522009-09-21 16:56:56 +00001922 CodeCompletionString *CCStr = Result;
1923 bool FirstParameter = true;
1924
1925 TemplateParameterList *Params = Template->getTemplateParameters();
1926 TemplateParameterList::iterator PEnd = Params->end();
1927 if (MaxParameters)
1928 PEnd = Params->begin() + MaxParameters;
1929 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1930 bool HasDefaultArg = false;
1931 std::string PlaceholderStr;
1932 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1933 if (TTP->wasDeclaredWithTypename())
1934 PlaceholderStr = "typename";
1935 else
1936 PlaceholderStr = "class";
1937
1938 if (TTP->getIdentifier()) {
1939 PlaceholderStr += ' ';
1940 PlaceholderStr += TTP->getIdentifier()->getName();
1941 }
1942
1943 HasDefaultArg = TTP->hasDefaultArgument();
1944 } else if (NonTypeTemplateParmDecl *NTTP
1945 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1946 if (NTTP->getIdentifier())
1947 PlaceholderStr = NTTP->getIdentifier()->getName();
1948 NTTP->getType().getAsStringInternal(PlaceholderStr,
1949 Context.PrintingPolicy);
1950 HasDefaultArg = NTTP->hasDefaultArgument();
1951 } else {
1952 assert(isa<TemplateTemplateParmDecl>(*P));
1953 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1954
1955 // Since putting the template argument list into the placeholder would
1956 // be very, very long, we just use an abbreviation.
1957 PlaceholderStr = "template<...> class";
1958 if (TTP->getIdentifier()) {
1959 PlaceholderStr += ' ';
1960 PlaceholderStr += TTP->getIdentifier()->getName();
1961 }
1962
1963 HasDefaultArg = TTP->hasDefaultArgument();
1964 }
1965
1966 if (HasDefaultArg) {
1967 // When we see an optional default argument, put that argument and
1968 // the remaining default arguments into a new, optional string.
1969 CodeCompletionString *Opt = new CodeCompletionString;
1970 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1971 CCStr = Opt;
1972 }
1973
1974 if (FirstParameter)
1975 FirstParameter = false;
1976 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001977 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001978
1979 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001980 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001981 }
1982}
1983
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001984/// \brief Add a qualifier to the given code-completion string, if the
1985/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001986static void
1987AddQualifierToCompletionString(CodeCompletionString *Result,
1988 NestedNameSpecifier *Qualifier,
1989 bool QualifierIsInformative,
1990 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001991 if (!Qualifier)
1992 return;
1993
1994 std::string PrintedNNS;
1995 {
1996 llvm::raw_string_ostream OS(PrintedNNS);
1997 Qualifier->print(OS, Context.PrintingPolicy);
1998 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001999 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002000 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00002001 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002002 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002003}
2004
Douglas Gregora61a8792009-12-11 18:44:16 +00002005static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
2006 FunctionDecl *Function) {
2007 const FunctionProtoType *Proto
2008 = Function->getType()->getAs<FunctionProtoType>();
2009 if (!Proto || !Proto->getTypeQuals())
2010 return;
2011
2012 std::string QualsStr;
2013 if (Proto->getTypeQuals() & Qualifiers::Const)
2014 QualsStr += " const";
2015 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2016 QualsStr += " volatile";
2017 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2018 QualsStr += " restrict";
2019 Result->AddInformativeChunk(QualsStr);
2020}
2021
Douglas Gregor86d9a522009-09-21 16:56:56 +00002022/// \brief If possible, create a new code completion string for the given
2023/// result.
2024///
2025/// \returns Either a new, heap-allocated code completion string describing
2026/// how to use this result, or NULL to indicate that the string or name of the
2027/// result is all that is needed.
2028CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002029CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002030 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002031 typedef CodeCompletionString::Chunk Chunk;
2032
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002033 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002034 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002035
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002036 if (!Result)
2037 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002038
2039 if (Kind == RK_Keyword) {
2040 Result->AddTypedTextChunk(Keyword);
2041 return Result;
2042 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002043
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002044 if (Kind == RK_Macro) {
2045 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002046 assert(MI && "Not a macro?");
2047
2048 Result->AddTypedTextChunk(Macro->getName());
2049
2050 if (!MI->isFunctionLike())
2051 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002052
2053 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002054 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002055 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2056 A != AEnd; ++A) {
2057 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002058 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002059
2060 if (!MI->isVariadic() || A != AEnd - 1) {
2061 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002062 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002063 continue;
2064 }
2065
2066 // Variadic argument; cope with the different between GNU and C99
2067 // variadic macros, providing a single placeholder for the rest of the
2068 // arguments.
2069 if ((*A)->isStr("__VA_ARGS__"))
2070 Result->AddPlaceholderChunk("...");
2071 else {
2072 std::string Arg = (*A)->getName();
2073 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00002074 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002075 }
2076 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002077 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002078 return Result;
2079 }
2080
Douglas Gregord8e8a582010-05-25 21:41:55 +00002081 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002082 NamedDecl *ND = Declaration;
2083
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002084 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002085 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002086 Result->AddTextChunk("::");
2087 return Result;
2088 }
2089
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002090 AddResultTypeChunk(S.Context, ND, Result);
2091
Douglas Gregor86d9a522009-09-21 16:56:56 +00002092 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002093 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2094 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002095 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002096 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002097 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002098 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002099 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002100 return Result;
2101 }
2102
2103 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002104 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2105 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002106 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00002107 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00002108
2109 // Figure out which template parameters are deduced (or have default
2110 // arguments).
2111 llvm::SmallVector<bool, 16> Deduced;
2112 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2113 unsigned LastDeducibleArgument;
2114 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2115 --LastDeducibleArgument) {
2116 if (!Deduced[LastDeducibleArgument - 1]) {
2117 // C++0x: Figure out if the template argument has a default. If so,
2118 // the user doesn't need to type this argument.
2119 // FIXME: We need to abstract template parameters better!
2120 bool HasDefaultArg = false;
2121 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2122 LastDeducibleArgument - 1);
2123 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2124 HasDefaultArg = TTP->hasDefaultArgument();
2125 else if (NonTypeTemplateParmDecl *NTTP
2126 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2127 HasDefaultArg = NTTP->hasDefaultArgument();
2128 else {
2129 assert(isa<TemplateTemplateParmDecl>(Param));
2130 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002131 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002132 }
2133
2134 if (!HasDefaultArg)
2135 break;
2136 }
2137 }
2138
2139 if (LastDeducibleArgument) {
2140 // Some of the function template arguments cannot be deduced from a
2141 // function call, so we introduce an explicit template argument list
2142 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002143 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002144 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2145 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002146 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002147 }
2148
2149 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002150 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002151 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002152 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002153 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002154 return Result;
2155 }
2156
2157 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002158 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2159 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002160 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002161 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002162 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002163 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002164 return Result;
2165 }
2166
Douglas Gregor9630eb62009-11-17 16:44:22 +00002167 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002168 Selector Sel = Method->getSelector();
2169 if (Sel.isUnarySelector()) {
2170 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2171 return Result;
2172 }
2173
Douglas Gregord3c68542009-11-19 01:08:35 +00002174 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2175 SelName += ':';
2176 if (StartParameter == 0)
2177 Result->AddTypedTextChunk(SelName);
2178 else {
2179 Result->AddInformativeChunk(SelName);
2180
2181 // If there is only one parameter, and we're past it, add an empty
2182 // typed-text chunk since there is nothing to type.
2183 if (Method->param_size() == 1)
2184 Result->AddTypedTextChunk("");
2185 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002186 unsigned Idx = 0;
2187 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2188 PEnd = Method->param_end();
2189 P != PEnd; (void)++P, ++Idx) {
2190 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002191 std::string Keyword;
2192 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002193 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002194 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2195 Keyword += II->getName().str();
2196 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002197 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002198 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002199 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00002200 Result->AddTypedTextChunk(Keyword);
2201 else
2202 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002203 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002204
2205 // If we're before the starting parameter, skip the placeholder.
2206 if (Idx < StartParameter)
2207 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002208
2209 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002210
2211 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002212 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002213 else {
2214 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2215 Arg = "(" + Arg + ")";
2216 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002217 if (DeclaringEntity || AllParametersAreInformative)
2218 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002219 }
2220
Douglas Gregore17794f2010-08-31 05:13:43 +00002221 if (Method->isVariadic() && (P + 1) == PEnd)
2222 Arg += ", ...";
2223
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002224 if (DeclaringEntity)
2225 Result->AddTextChunk(Arg);
2226 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002227 Result->AddInformativeChunk(Arg);
2228 else
2229 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002230 }
2231
Douglas Gregor2a17af02009-12-23 00:21:46 +00002232 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002233 if (Method->param_size() == 0) {
2234 if (DeclaringEntity)
2235 Result->AddTextChunk(", ...");
2236 else if (AllParametersAreInformative)
2237 Result->AddInformativeChunk(", ...");
2238 else
2239 Result->AddPlaceholderChunk(", ...");
2240 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002241
2242 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002243 }
2244
Douglas Gregor9630eb62009-11-17 16:44:22 +00002245 return Result;
2246 }
2247
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002248 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002249 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2250 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002251
2252 Result->AddTypedTextChunk(ND->getNameAsString());
2253 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002254}
2255
Douglas Gregor86d802e2009-09-23 00:34:09 +00002256CodeCompletionString *
2257CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2258 unsigned CurrentArg,
2259 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002260 typedef CodeCompletionString::Chunk Chunk;
2261
Douglas Gregor86d802e2009-09-23 00:34:09 +00002262 CodeCompletionString *Result = new CodeCompletionString;
2263 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002264 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002265 const FunctionProtoType *Proto
2266 = dyn_cast<FunctionProtoType>(getFunctionType());
2267 if (!FDecl && !Proto) {
2268 // Function without a prototype. Just give the return type and a
2269 // highlighted ellipsis.
2270 const FunctionType *FT = getFunctionType();
2271 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002272 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002273 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2274 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2275 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002276 return Result;
2277 }
2278
2279 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002280 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002281 else
2282 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002283 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002284
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002285 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002286 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2287 for (unsigned I = 0; I != NumParams; ++I) {
2288 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002289 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002290
2291 std::string ArgString;
2292 QualType ArgType;
2293
2294 if (FDecl) {
2295 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2296 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2297 } else {
2298 ArgType = Proto->getArgType(I);
2299 }
2300
2301 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2302
2303 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002304 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002305 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002306 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002307 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002308 }
2309
2310 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002311 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002312 if (CurrentArg < NumParams)
2313 Result->AddTextChunk("...");
2314 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002315 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002316 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002317 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002318
2319 return Result;
2320}
2321
Douglas Gregor1827e102010-08-16 16:18:59 +00002322unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002323 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002324 bool PreferredTypeIsPointer) {
2325 unsigned Priority = CCP_Macro;
2326
Douglas Gregorb05496d2010-09-20 21:11:48 +00002327 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2328 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2329 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002330 Priority = CCP_Constant;
2331 if (PreferredTypeIsPointer)
2332 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002333 }
2334 // Treat "YES", "NO", "true", and "false" as constants.
2335 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2336 MacroName.equals("true") || MacroName.equals("false"))
2337 Priority = CCP_Constant;
2338 // Treat "bool" as a type.
2339 else if (MacroName.equals("bool"))
2340 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2341
Douglas Gregor1827e102010-08-16 16:18:59 +00002342
2343 return Priority;
2344}
2345
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002346CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2347 if (!D)
2348 return CXCursor_UnexposedDecl;
2349
2350 switch (D->getKind()) {
2351 case Decl::Enum: return CXCursor_EnumDecl;
2352 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2353 case Decl::Field: return CXCursor_FieldDecl;
2354 case Decl::Function:
2355 return CXCursor_FunctionDecl;
2356 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2357 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2358 case Decl::ObjCClass:
2359 // FIXME
2360 return CXCursor_UnexposedDecl;
2361 case Decl::ObjCForwardProtocol:
2362 // FIXME
2363 return CXCursor_UnexposedDecl;
2364 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2365 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2366 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2367 case Decl::ObjCMethod:
2368 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2369 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2370 case Decl::CXXMethod: return CXCursor_CXXMethod;
2371 case Decl::CXXConstructor: return CXCursor_Constructor;
2372 case Decl::CXXDestructor: return CXCursor_Destructor;
2373 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2374 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2375 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2376 case Decl::ParmVar: return CXCursor_ParmDecl;
2377 case Decl::Typedef: return CXCursor_TypedefDecl;
2378 case Decl::Var: return CXCursor_VarDecl;
2379 case Decl::Namespace: return CXCursor_Namespace;
2380 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2381 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2382 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2383 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2384 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2385 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2386 case Decl::ClassTemplatePartialSpecialization:
2387 return CXCursor_ClassTemplatePartialSpecialization;
2388 case Decl::UsingDirective: return CXCursor_UsingDirective;
2389
2390 case Decl::Using:
2391 case Decl::UnresolvedUsingValue:
2392 case Decl::UnresolvedUsingTypename:
2393 return CXCursor_UsingDeclaration;
2394
2395 default:
2396 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2397 switch (TD->getTagKind()) {
2398 case TTK_Struct: return CXCursor_StructDecl;
2399 case TTK_Class: return CXCursor_ClassDecl;
2400 case TTK_Union: return CXCursor_UnionDecl;
2401 case TTK_Enum: return CXCursor_EnumDecl;
2402 }
2403 }
2404 }
2405
2406 return CXCursor_UnexposedDecl;
2407}
2408
Douglas Gregor590c7d52010-07-08 20:55:51 +00002409static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2410 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002411 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002412
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002413 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002414 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2415 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002416 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002417 Results.AddResult(Result(M->first,
2418 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002419 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002420 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002421 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002422 Results.ExitScope();
2423}
2424
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002425static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2426 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002427 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002428
2429 Results.EnterNewScope();
2430 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2431 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2432 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2433 Results.AddResult(Result("__func__", CCP_Constant));
2434 Results.ExitScope();
2435}
2436
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002437static void HandleCodeCompleteResults(Sema *S,
2438 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002439 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002440 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002441 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002442 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002443 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002444
2445 for (unsigned I = 0; I != NumResults; ++I)
2446 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447}
2448
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002449static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2450 Sema::ParserCompletionContext PCC) {
2451 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002452 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002453 return CodeCompletionContext::CCC_TopLevel;
2454
John McCallf312b1e2010-08-26 23:41:50 +00002455 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002456 return CodeCompletionContext::CCC_ClassStructUnion;
2457
John McCallf312b1e2010-08-26 23:41:50 +00002458 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002459 return CodeCompletionContext::CCC_ObjCInterface;
2460
John McCallf312b1e2010-08-26 23:41:50 +00002461 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002462 return CodeCompletionContext::CCC_ObjCImplementation;
2463
John McCallf312b1e2010-08-26 23:41:50 +00002464 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002465 return CodeCompletionContext::CCC_ObjCIvarList;
2466
John McCallf312b1e2010-08-26 23:41:50 +00002467 case Sema::PCC_Template:
2468 case Sema::PCC_MemberTemplate:
2469 case Sema::PCC_RecoveryInFunction:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002470 return CodeCompletionContext::CCC_Other;
2471
John McCallf312b1e2010-08-26 23:41:50 +00002472 case Sema::PCC_Expression:
2473 case Sema::PCC_ForInit:
2474 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002475 return CodeCompletionContext::CCC_Expression;
2476
John McCallf312b1e2010-08-26 23:41:50 +00002477 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002478 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002479
John McCallf312b1e2010-08-26 23:41:50 +00002480 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002481 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002482
2483 case Sema::PCC_ParenthesizedExpression:
2484 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002485 }
2486
2487 return CodeCompletionContext::CCC_Other;
2488}
2489
Douglas Gregorf6961522010-08-27 21:18:54 +00002490/// \brief If we're in a C++ virtual member function, add completion results
2491/// that invoke the functions we override, since it's common to invoke the
2492/// overridden function as well as adding new functionality.
2493///
2494/// \param S The semantic analysis object for which we are generating results.
2495///
2496/// \param InContext This context in which the nested-name-specifier preceding
2497/// the code-completion point
2498static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2499 ResultBuilder &Results) {
2500 // Look through blocks.
2501 DeclContext *CurContext = S.CurContext;
2502 while (isa<BlockDecl>(CurContext))
2503 CurContext = CurContext->getParent();
2504
2505
2506 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2507 if (!Method || !Method->isVirtual())
2508 return;
2509
2510 // We need to have names for all of the parameters, if we're going to
2511 // generate a forwarding call.
2512 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2513 PEnd = Method->param_end();
2514 P != PEnd;
2515 ++P) {
2516 if (!(*P)->getDeclName())
2517 return;
2518 }
2519
2520 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2521 MEnd = Method->end_overridden_methods();
2522 M != MEnd; ++M) {
2523 CodeCompletionString *Pattern = new CodeCompletionString;
2524 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2525 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2526 continue;
2527
2528 // If we need a nested-name-specifier, add one now.
2529 if (!InContext) {
2530 NestedNameSpecifier *NNS
2531 = getRequiredQualification(S.Context, CurContext,
2532 Overridden->getDeclContext());
2533 if (NNS) {
2534 std::string Str;
2535 llvm::raw_string_ostream OS(Str);
2536 NNS->print(OS, S.Context.PrintingPolicy);
2537 Pattern->AddTextChunk(OS.str());
2538 }
2539 } else if (!InContext->Equals(Overridden->getDeclContext()))
2540 continue;
2541
2542 Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2543 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2544 bool FirstParam = true;
2545 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2546 PEnd = Method->param_end();
2547 P != PEnd; ++P) {
2548 if (FirstParam)
2549 FirstParam = false;
2550 else
2551 Pattern->AddChunk(CodeCompletionString::CK_Comma);
2552
2553 Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2554 }
2555 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2556 Results.AddResult(CodeCompletionResult(Pattern,
2557 CCP_SuperCompletion,
2558 CXCursor_CXXMethod));
2559 Results.Ignore(Overridden);
2560 }
2561}
2562
Douglas Gregor01dfea02010-01-10 23:08:15 +00002563void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002564 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002565 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002566 ResultBuilder Results(*this);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002567 Results.setCompletionContext(mapCodeCompletionContext(*this,
2568 CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002569 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002570
Douglas Gregor01dfea02010-01-10 23:08:15 +00002571 // Determine how to filter results, e.g., so that the names of
2572 // values (functions, enumerators, function templates, etc.) are
2573 // only allowed where we can have an expression.
2574 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002575 case PCC_Namespace:
2576 case PCC_Class:
2577 case PCC_ObjCInterface:
2578 case PCC_ObjCImplementation:
2579 case PCC_ObjCInstanceVariableList:
2580 case PCC_Template:
2581 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002582 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002583 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2584 break;
2585
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002586 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002587 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002588 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002589 case PCC_ForInit:
2590 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002591 if (WantTypesInContext(CompletionContext, getLangOptions()))
2592 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2593 else
2594 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002595
2596 if (getLangOptions().CPlusPlus)
2597 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002598 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002599
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002600 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002601 // Unfiltered
2602 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002603 }
2604
Douglas Gregor3cdee122010-08-26 16:36:48 +00002605 // If we are in a C++ non-static member function, check the qualifiers on
2606 // the member function to filter/prioritize the results list.
2607 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2608 if (CurMethod->isInstance())
2609 Results.setObjectTypeQualifiers(
2610 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2611
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002612 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002613 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2614 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002615
Douglas Gregorbca403c2010-01-13 23:51:12 +00002616 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002617 Results.ExitScope();
2618
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002619 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002620 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002621 case PCC_Expression:
2622 case PCC_Statement:
2623 case PCC_RecoveryInFunction:
2624 if (S->getFnParent())
2625 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2626 break;
2627
2628 case PCC_Namespace:
2629 case PCC_Class:
2630 case PCC_ObjCInterface:
2631 case PCC_ObjCImplementation:
2632 case PCC_ObjCInstanceVariableList:
2633 case PCC_Template:
2634 case PCC_MemberTemplate:
2635 case PCC_ForInit:
2636 case PCC_Condition:
2637 case PCC_Type:
2638 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002639 }
2640
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002641 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002642 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002643
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002644 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002645 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002646}
2647
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002648static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2649 ParsedType Receiver,
2650 IdentifierInfo **SelIdents,
2651 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002652 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002653 bool IsSuper,
2654 ResultBuilder &Results);
2655
2656void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2657 bool AllowNonIdentifiers,
2658 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002659 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002660 ResultBuilder Results(*this);
2661 Results.EnterNewScope();
2662
2663 // Type qualifiers can come after names.
2664 Results.AddResult(Result("const"));
2665 Results.AddResult(Result("volatile"));
2666 if (getLangOptions().C99)
2667 Results.AddResult(Result("restrict"));
2668
2669 if (getLangOptions().CPlusPlus) {
2670 if (AllowNonIdentifiers) {
2671 Results.AddResult(Result("operator"));
2672 }
2673
2674 // Add nested-name-specifiers.
2675 if (AllowNestedNameSpecifiers) {
2676 Results.allowNestedNameSpecifiers();
2677 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2678 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2679 CodeCompleter->includeGlobals());
2680 }
2681 }
2682 Results.ExitScope();
2683
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002684 // If we're in a context where we might have an expression (rather than a
2685 // declaration), and what we've seen so far is an Objective-C type that could
2686 // be a receiver of a class message, this may be a class message send with
2687 // the initial opening bracket '[' missing. Add appropriate completions.
2688 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2689 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2690 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2691 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2692 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2693 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2694 DS.getTypeQualifiers() == 0 &&
2695 S &&
2696 (S->getFlags() & Scope::DeclScope) != 0 &&
2697 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2698 Scope::FunctionPrototypeScope |
2699 Scope::AtCatchScope)) == 0) {
2700 ParsedType T = DS.getRepAsType();
2701 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002702 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002703 }
2704
Douglas Gregor4497dd42010-08-24 04:59:56 +00002705 // Note that we intentionally suppress macro results here, since we do not
2706 // encourage using macros to produce the names of entities.
2707
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002708 HandleCodeCompleteResults(this, CodeCompleter,
2709 AllowNestedNameSpecifiers
2710 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2711 : CodeCompletionContext::CCC_Name,
2712 Results.data(), Results.size());
2713}
2714
Douglas Gregorfb629412010-08-23 21:17:50 +00002715struct Sema::CodeCompleteExpressionData {
2716 CodeCompleteExpressionData(QualType PreferredType = QualType())
2717 : PreferredType(PreferredType), IntegralConstantExpression(false),
2718 ObjCCollection(false) { }
2719
2720 QualType PreferredType;
2721 bool IntegralConstantExpression;
2722 bool ObjCCollection;
2723 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2724};
2725
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002726/// \brief Perform code-completion in an expression context when we know what
2727/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002728///
2729/// \param IntegralConstantExpression Only permit integral constant
2730/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002731void Sema::CodeCompleteExpression(Scope *S,
2732 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002733 typedef CodeCompletionResult Result;
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002734 ResultBuilder Results(*this);
2735
Douglas Gregorfb629412010-08-23 21:17:50 +00002736 if (Data.ObjCCollection)
2737 Results.setFilter(&ResultBuilder::IsObjCCollection);
2738 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002739 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002740 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002741 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2742 else
2743 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002744
2745 if (!Data.PreferredType.isNull())
2746 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2747
2748 // Ignore any declarations that we were told that we don't care about.
2749 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2750 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002751
2752 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002753 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2754 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002755
2756 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002757 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002758 Results.ExitScope();
2759
Douglas Gregor590c7d52010-07-08 20:55:51 +00002760 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002761 if (!Data.PreferredType.isNull())
2762 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2763 || Data.PreferredType->isMemberPointerType()
2764 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002765
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002766 if (S->getFnParent() &&
2767 !Data.ObjCCollection &&
2768 !Data.IntegralConstantExpression)
2769 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2770
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002771 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002772 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002773 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002774 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2775 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002776 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002777}
2778
Douglas Gregorac5fd842010-09-18 01:28:11 +00002779void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
2780 if (E.isInvalid())
2781 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
2782 else if (getLangOptions().ObjC1)
2783 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00002784}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002785
Douglas Gregor95ac6552009-11-18 01:29:26 +00002786static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002787 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002788 DeclContext *CurContext,
2789 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002790 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002791
2792 // Add properties in this container.
2793 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2794 PEnd = Container->prop_end();
2795 P != PEnd;
2796 ++P)
2797 Results.MaybeAddResult(Result(*P, 0), CurContext);
2798
2799 // Add properties in referenced protocols.
2800 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2801 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2802 PEnd = Protocol->protocol_end();
2803 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002804 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002805 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002806 if (AllowCategories) {
2807 // Look through categories.
2808 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2809 Category; Category = Category->getNextClassCategory())
2810 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2811 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002812
2813 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002814 for (ObjCInterfaceDecl::all_protocol_iterator
2815 I = IFace->all_referenced_protocol_begin(),
2816 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002817 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002818
2819 // Look in the superclass.
2820 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002821 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2822 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002823 } else if (const ObjCCategoryDecl *Category
2824 = dyn_cast<ObjCCategoryDecl>(Container)) {
2825 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002826 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
2827 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002828 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002829 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002830 }
2831}
2832
Douglas Gregor81b747b2009-09-17 21:32:03 +00002833void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2834 SourceLocation OpLoc,
2835 bool IsArrow) {
2836 if (!BaseE || !CodeCompleter)
2837 return;
2838
John McCall0a2c5e22010-08-25 06:19:51 +00002839 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002840
Douglas Gregor81b747b2009-09-17 21:32:03 +00002841 Expr *Base = static_cast<Expr *>(BaseE);
2842 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002843
2844 if (IsArrow) {
2845 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2846 BaseType = Ptr->getPointeeType();
2847 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00002848 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002849 else
2850 return;
2851 }
2852
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002853 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002854 Results.EnterNewScope();
2855 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00002856 // Indicate that we are performing a member access, and the cv-qualifiers
2857 // for the base object type.
2858 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
2859
Douglas Gregor95ac6552009-11-18 01:29:26 +00002860 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002861 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002862 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002863 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2864 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002865
Douglas Gregor95ac6552009-11-18 01:29:26 +00002866 if (getLangOptions().CPlusPlus) {
2867 if (!Results.empty()) {
2868 // The "template" keyword can follow "->" or "." in the grammar.
2869 // However, we only want to suggest the template keyword if something
2870 // is dependent.
2871 bool IsDependent = BaseType->isDependentType();
2872 if (!IsDependent) {
2873 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2874 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2875 IsDependent = Ctx->isDependentContext();
2876 break;
2877 }
2878 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002879
Douglas Gregor95ac6552009-11-18 01:29:26 +00002880 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002881 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002882 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002883 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002884 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2885 // Objective-C property reference.
2886
2887 // Add property results based on our interface.
2888 const ObjCObjectPointerType *ObjCPtr
2889 = BaseType->getAsObjCInterfacePointerType();
2890 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002891 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002892
2893 // Add properties from the protocols in a qualified interface.
2894 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2895 E = ObjCPtr->qual_end();
2896 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002897 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002898 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002899 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002900 // Objective-C instance variable access.
2901 ObjCInterfaceDecl *Class = 0;
2902 if (const ObjCObjectPointerType *ObjCPtr
2903 = BaseType->getAs<ObjCObjectPointerType>())
2904 Class = ObjCPtr->getInterfaceDecl();
2905 else
John McCallc12c5bb2010-05-15 11:32:37 +00002906 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002907
2908 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002909 if (Class) {
2910 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2911 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00002912 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2913 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00002914 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002915 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002916
2917 // FIXME: How do we cope with isa?
2918
2919 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002920
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002921 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002922 HandleCodeCompleteResults(this, CodeCompleter,
2923 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2924 BaseType),
2925 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002926}
2927
Douglas Gregor374929f2009-09-18 15:37:17 +00002928void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2929 if (!CodeCompleter)
2930 return;
2931
John McCall0a2c5e22010-08-25 06:19:51 +00002932 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002933 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002934 enum CodeCompletionContext::Kind ContextKind
2935 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00002936 switch ((DeclSpec::TST)TagSpec) {
2937 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002938 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002939 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002940 break;
2941
2942 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002943 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002944 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002945 break;
2946
2947 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002948 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002949 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002950 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002951 break;
2952
2953 default:
2954 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2955 return;
2956 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002957
John McCall0d6b1642010-04-23 18:46:30 +00002958 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002959 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002960
2961 // First pass: look for tags.
2962 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00002963 LookupVisibleDecls(S, LookupTagName, Consumer,
2964 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00002965
Douglas Gregor8071e422010-08-15 06:18:01 +00002966 if (CodeCompleter->includeGlobals()) {
2967 // Second pass: look for nested name specifiers.
2968 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2969 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2970 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002971
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002972 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2973 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002974}
2975
Douglas Gregor1a480c42010-08-27 17:35:51 +00002976void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
2977 ResultBuilder Results(*this);
2978 Results.EnterNewScope();
2979 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
2980 Results.AddResult("const");
2981 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
2982 Results.AddResult("volatile");
2983 if (getLangOptions().C99 &&
2984 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
2985 Results.AddResult("restrict");
2986 Results.ExitScope();
2987 HandleCodeCompleteResults(this, CodeCompleter,
2988 CodeCompletionContext::CCC_TypeQualifiers,
2989 Results.data(), Results.size());
2990}
2991
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002992void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00002993 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002994 return;
2995
John McCall781472f2010-08-25 08:40:02 +00002996 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00002997 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00002998 CodeCompleteExpressionData Data(Switch->getCond()->getType());
2999 Data.IntegralConstantExpression = true;
3000 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003001 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003002 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003003
3004 // Code-complete the cases of a switch statement over an enumeration type
3005 // by providing the list of
3006 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3007
3008 // Determine which enumerators we have already seen in the switch statement.
3009 // FIXME: Ideally, we would also be able to look *past* the code-completion
3010 // token, in case we are code-completing in the middle of the switch and not
3011 // at the end. However, we aren't able to do so at the moment.
3012 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003013 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003014 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3015 SC = SC->getNextSwitchCase()) {
3016 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3017 if (!Case)
3018 continue;
3019
3020 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3022 if (EnumConstantDecl *Enumerator
3023 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3024 // We look into the AST of the case statement to determine which
3025 // enumerator was named. Alternatively, we could compute the value of
3026 // the integral constant expression, then compare it against the
3027 // values of each enumerator. However, value-based approach would not
3028 // work as well with C++ templates where enumerators declared within a
3029 // template are type- and value-dependent.
3030 EnumeratorsSeen.insert(Enumerator);
3031
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003032 // If this is a qualified-id, keep track of the nested-name-specifier
3033 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003034 //
3035 // switch (TagD.getKind()) {
3036 // case TagDecl::TK_enum:
3037 // break;
3038 // case XXX
3039 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003040 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003041 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3042 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003043 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003044 }
3045 }
3046
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003047 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3048 // If there are no prior enumerators in C++, check whether we have to
3049 // qualify the names of the enumerators that we suggest, because they
3050 // may not be visible in this scope.
3051 Qualifier = getRequiredQualification(Context, CurContext,
3052 Enum->getDeclContext());
3053
3054 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3055 }
3056
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003057 // Add any enumerators that have not yet been mentioned.
3058 ResultBuilder Results(*this);
3059 Results.EnterNewScope();
3060 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3061 EEnd = Enum->enumerator_end();
3062 E != EEnd; ++E) {
3063 if (EnumeratorsSeen.count(*E))
3064 continue;
3065
John McCall0a2c5e22010-08-25 06:19:51 +00003066 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00003067 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003068 }
3069 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003070
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003071 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003072 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003073 HandleCodeCompleteResults(this, CodeCompleter,
3074 CodeCompletionContext::CCC_Expression,
3075 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003076}
3077
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003078namespace {
3079 struct IsBetterOverloadCandidate {
3080 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003081 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003082
3083 public:
John McCall5769d612010-02-08 23:07:23 +00003084 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3085 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003086
3087 bool
3088 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003089 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003090 }
3091 };
3092}
3093
Douglas Gregord28dcd72010-05-30 06:10:08 +00003094static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3095 if (NumArgs && !Args)
3096 return true;
3097
3098 for (unsigned I = 0; I != NumArgs; ++I)
3099 if (!Args[I])
3100 return true;
3101
3102 return false;
3103}
3104
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003105void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3106 ExprTy **ArgsIn, unsigned NumArgs) {
3107 if (!CodeCompleter)
3108 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003109
3110 // When we're code-completing for a call, we fall back to ordinary
3111 // name code-completion whenever we can't produce specific
3112 // results. We may want to revisit this strategy in the future,
3113 // e.g., by merging the two kinds of results.
3114
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003115 Expr *Fn = (Expr *)FnIn;
3116 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003117
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003118 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003119 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003120 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003121 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003122 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003123 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003124
John McCall3b4294e2009-12-16 12:17:52 +00003125 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003126 SourceLocation Loc = Fn->getExprLoc();
3127 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003128
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003129 // FIXME: What if we're calling something that isn't a function declaration?
3130 // FIXME: What if we're calling a pseudo-destructor?
3131 // FIXME: What if we're calling a member function?
3132
Douglas Gregorc0265402010-01-21 15:46:19 +00003133 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3134 llvm::SmallVector<ResultCandidate, 8> Results;
3135
John McCall3b4294e2009-12-16 12:17:52 +00003136 Expr *NakedFn = Fn->IgnoreParenCasts();
3137 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3138 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3139 /*PartialOverloading=*/ true);
3140 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3141 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003142 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003143 if (!getLangOptions().CPlusPlus ||
3144 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003145 Results.push_back(ResultCandidate(FDecl));
3146 else
John McCall86820f52010-01-26 01:37:31 +00003147 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003148 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3149 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003150 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003151 }
John McCall3b4294e2009-12-16 12:17:52 +00003152 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003153
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003154 QualType ParamType;
3155
Douglas Gregorc0265402010-01-21 15:46:19 +00003156 if (!CandidateSet.empty()) {
3157 // Sort the overload candidate set by placing the best overloads first.
3158 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003159 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003160
Douglas Gregorc0265402010-01-21 15:46:19 +00003161 // Add the remaining viable overload candidates as code-completion reslults.
3162 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3163 CandEnd = CandidateSet.end();
3164 Cand != CandEnd; ++Cand) {
3165 if (Cand->Viable)
3166 Results.push_back(ResultCandidate(Cand->Function));
3167 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003168
3169 // From the viable candidates, try to determine the type of this parameter.
3170 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3171 if (const FunctionType *FType = Results[I].getFunctionType())
3172 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3173 if (NumArgs < Proto->getNumArgs()) {
3174 if (ParamType.isNull())
3175 ParamType = Proto->getArgType(NumArgs);
3176 else if (!Context.hasSameUnqualifiedType(
3177 ParamType.getNonReferenceType(),
3178 Proto->getArgType(NumArgs).getNonReferenceType())) {
3179 ParamType = QualType();
3180 break;
3181 }
3182 }
3183 }
3184 } else {
3185 // Try to determine the parameter type from the type of the expression
3186 // being called.
3187 QualType FunctionType = Fn->getType();
3188 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3189 FunctionType = Ptr->getPointeeType();
3190 else if (const BlockPointerType *BlockPtr
3191 = FunctionType->getAs<BlockPointerType>())
3192 FunctionType = BlockPtr->getPointeeType();
3193 else if (const MemberPointerType *MemPtr
3194 = FunctionType->getAs<MemberPointerType>())
3195 FunctionType = MemPtr->getPointeeType();
3196
3197 if (const FunctionProtoType *Proto
3198 = FunctionType->getAs<FunctionProtoType>()) {
3199 if (NumArgs < Proto->getNumArgs())
3200 ParamType = Proto->getArgType(NumArgs);
3201 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003202 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003203
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003204 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003205 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003206 else
3207 CodeCompleteExpression(S, ParamType);
3208
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003209 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003210 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3211 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003212}
3213
John McCalld226f652010-08-21 09:40:31 +00003214void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3215 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003216 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003217 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003218 return;
3219 }
3220
3221 CodeCompleteExpression(S, VD->getType());
3222}
3223
3224void Sema::CodeCompleteReturn(Scope *S) {
3225 QualType ResultType;
3226 if (isa<BlockDecl>(CurContext)) {
3227 if (BlockScopeInfo *BSI = getCurBlock())
3228 ResultType = BSI->ReturnType;
3229 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3230 ResultType = Function->getResultType();
3231 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3232 ResultType = Method->getResultType();
3233
3234 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003235 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003236 else
3237 CodeCompleteExpression(S, ResultType);
3238}
3239
3240void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3241 if (LHS)
3242 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3243 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003244 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003245}
3246
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003247void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003248 bool EnteringContext) {
3249 if (!SS.getScopeRep() || !CodeCompleter)
3250 return;
3251
Douglas Gregor86d9a522009-09-21 16:56:56 +00003252 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3253 if (!Ctx)
3254 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003255
3256 // Try to instantiate any non-dependent declaration contexts before
3257 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003258 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003259 return;
3260
Douglas Gregor86d9a522009-09-21 16:56:56 +00003261 ResultBuilder Results(*this);
Douglas Gregor86d9a522009-09-21 16:56:56 +00003262
Douglas Gregorf6961522010-08-27 21:18:54 +00003263 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003264 // The "template" keyword can follow "::" in the grammar, but only
3265 // put it into the grammar if the nested-name-specifier is dependent.
3266 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3267 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003268 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003269
3270 // Add calls to overridden virtual functions, if there are any.
3271 //
3272 // FIXME: This isn't wonderful, because we don't know whether we're actually
3273 // in a context that permits expressions. This is a general issue with
3274 // qualified-id completions.
3275 if (!EnteringContext)
3276 MaybeAddOverrideCalls(*this, Ctx, Results);
3277 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003278
Douglas Gregorf6961522010-08-27 21:18:54 +00003279 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3280 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3281
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003282 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003283 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003284 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003285}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003286
3287void Sema::CodeCompleteUsing(Scope *S) {
3288 if (!CodeCompleter)
3289 return;
3290
Douglas Gregor86d9a522009-09-21 16:56:56 +00003291 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003292 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003293
3294 // If we aren't in class scope, we could see the "namespace" keyword.
3295 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003296 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003297
3298 // After "using", we can see anything that would start a
3299 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003300 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003301 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3302 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003303 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003304
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003305 HandleCodeCompleteResults(this, CodeCompleter,
3306 CodeCompletionContext::CCC_Other,
3307 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003308}
3309
3310void Sema::CodeCompleteUsingDirective(Scope *S) {
3311 if (!CodeCompleter)
3312 return;
3313
Douglas Gregor86d9a522009-09-21 16:56:56 +00003314 // After "using namespace", we expect to see a namespace name or namespace
3315 // alias.
3316 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003317 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003318 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003319 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3320 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003321 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003322 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003323 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003324 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003325}
3326
3327void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3328 if (!CodeCompleter)
3329 return;
3330
Douglas Gregor86d9a522009-09-21 16:56:56 +00003331 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
3332 DeclContext *Ctx = (DeclContext *)S->getEntity();
3333 if (!S->getParent())
3334 Ctx = Context.getTranslationUnitDecl();
3335
3336 if (Ctx && Ctx->isFileContext()) {
3337 // We only want to see those namespaces that have already been defined
3338 // within this scope, because its likely that the user is creating an
3339 // extended namespace declaration. Keep track of the most recent
3340 // definition of each namespace.
3341 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3342 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3343 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3344 NS != NSEnd; ++NS)
3345 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3346
3347 // Add the most recent definition (or extended definition) of each
3348 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003349 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003350 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3351 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3352 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003353 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003354 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003355 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003356 }
3357
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003358 HandleCodeCompleteResults(this, CodeCompleter,
3359 CodeCompletionContext::CCC_Other,
3360 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003361}
3362
3363void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3364 if (!CodeCompleter)
3365 return;
3366
Douglas Gregor86d9a522009-09-21 16:56:56 +00003367 // After "namespace", we expect to see a namespace or alias.
3368 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003369 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003370 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3371 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003372 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003373 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003374 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003375}
3376
Douglas Gregored8d3222009-09-18 20:05:18 +00003377void Sema::CodeCompleteOperatorName(Scope *S) {
3378 if (!CodeCompleter)
3379 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003380
John McCall0a2c5e22010-08-25 06:19:51 +00003381 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003382 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003383 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003384
Douglas Gregor86d9a522009-09-21 16:56:56 +00003385 // Add the names of overloadable operators.
3386#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3387 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003388 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003389#include "clang/Basic/OperatorKinds.def"
3390
3391 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003392 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003393 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003394 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3395 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003396
3397 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003398 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003399 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003400
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003401 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003402 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003403 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003404}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003405
Douglas Gregor0133f522010-08-28 00:00:50 +00003406void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3407 CXXBaseOrMemberInitializer** Initializers,
3408 unsigned NumInitializers) {
3409 CXXConstructorDecl *Constructor
3410 = static_cast<CXXConstructorDecl *>(ConstructorD);
3411 if (!Constructor)
3412 return;
3413
3414 ResultBuilder Results(*this);
3415 Results.EnterNewScope();
3416
3417 // Fill in any already-initialized fields or base classes.
3418 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3419 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3420 for (unsigned I = 0; I != NumInitializers; ++I) {
3421 if (Initializers[I]->isBaseInitializer())
3422 InitializedBases.insert(
3423 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3424 else
3425 InitializedFields.insert(cast<FieldDecl>(Initializers[I]->getMember()));
3426 }
3427
3428 // Add completions for base classes.
Douglas Gregor0c431c82010-08-29 19:27:27 +00003429 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003430 CXXRecordDecl *ClassDecl = Constructor->getParent();
3431 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3432 BaseEnd = ClassDecl->bases_end();
3433 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003434 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3435 SawLastInitializer
3436 = NumInitializers > 0 &&
3437 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3438 Context.hasSameUnqualifiedType(Base->getType(),
3439 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003440 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003441 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003442
3443 CodeCompletionString *Pattern = new CodeCompletionString;
3444 Pattern->AddTypedTextChunk(
3445 Base->getType().getAsString(Context.PrintingPolicy));
3446 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3447 Pattern->AddPlaceholderChunk("args");
3448 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003449 Results.AddResult(CodeCompletionResult(Pattern,
3450 SawLastInitializer? CCP_NextInitializer
3451 : CCP_MemberDeclaration));
3452 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003453 }
3454
3455 // Add completions for virtual base classes.
3456 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3457 BaseEnd = ClassDecl->vbases_end();
3458 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003459 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3460 SawLastInitializer
3461 = NumInitializers > 0 &&
3462 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3463 Context.hasSameUnqualifiedType(Base->getType(),
3464 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003465 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003466 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003467
3468 CodeCompletionString *Pattern = new CodeCompletionString;
3469 Pattern->AddTypedTextChunk(
3470 Base->getType().getAsString(Context.PrintingPolicy));
3471 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3472 Pattern->AddPlaceholderChunk("args");
3473 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003474 Results.AddResult(CodeCompletionResult(Pattern,
3475 SawLastInitializer? CCP_NextInitializer
3476 : CCP_MemberDeclaration));
3477 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003478 }
3479
3480 // Add completions for members.
3481 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3482 FieldEnd = ClassDecl->field_end();
3483 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003484 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3485 SawLastInitializer
3486 = NumInitializers > 0 &&
3487 Initializers[NumInitializers - 1]->isMemberInitializer() &&
3488 Initializers[NumInitializers - 1]->getMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003489 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003490 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003491
3492 if (!Field->getDeclName())
3493 continue;
3494
3495 CodeCompletionString *Pattern = new CodeCompletionString;
3496 Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3497 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3498 Pattern->AddPlaceholderChunk("args");
3499 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003500 Results.AddResult(CodeCompletionResult(Pattern,
3501 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003502 : CCP_MemberDeclaration,
3503 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003504 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003505 }
3506 Results.ExitScope();
3507
3508 HandleCodeCompleteResults(this, CodeCompleter,
3509 CodeCompletionContext::CCC_Name,
3510 Results.data(), Results.size());
3511}
3512
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003513// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3514// true or false.
3515#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003516static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003517 ResultBuilder &Results,
3518 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003519 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003520 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003521 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003522
3523 CodeCompletionString *Pattern = 0;
3524 if (LangOpts.ObjC2) {
3525 // @dynamic
3526 Pattern = new CodeCompletionString;
3527 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3528 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3529 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003530 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003531
3532 // @synthesize
3533 Pattern = new CodeCompletionString;
3534 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3535 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3536 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003537 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003538 }
3539}
3540
Douglas Gregorbca403c2010-01-13 23:51:12 +00003541static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003542 ResultBuilder &Results,
3543 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003544 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003545
3546 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003547 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003548
3549 if (LangOpts.ObjC2) {
3550 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003551 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003552
3553 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003554 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003555
3556 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003557 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003558 }
3559}
3560
Douglas Gregorbca403c2010-01-13 23:51:12 +00003561static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003562 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003563 CodeCompletionString *Pattern = 0;
3564
3565 // @class name ;
3566 Pattern = new CodeCompletionString;
3567 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3568 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003569 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003570 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003571
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003572 if (Results.includeCodePatterns()) {
3573 // @interface name
3574 // FIXME: Could introduce the whole pattern, including superclasses and
3575 // such.
3576 Pattern = new CodeCompletionString;
3577 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3578 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3579 Pattern->AddPlaceholderChunk("class");
3580 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003581
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003582 // @protocol name
3583 Pattern = new CodeCompletionString;
3584 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3585 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3586 Pattern->AddPlaceholderChunk("protocol");
3587 Results.AddResult(Result(Pattern));
3588
3589 // @implementation name
3590 Pattern = new CodeCompletionString;
3591 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3592 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3593 Pattern->AddPlaceholderChunk("class");
3594 Results.AddResult(Result(Pattern));
3595 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003596
3597 // @compatibility_alias name
3598 Pattern = new CodeCompletionString;
3599 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3600 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3601 Pattern->AddPlaceholderChunk("alias");
3602 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3603 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003604 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003605}
3606
John McCalld226f652010-08-21 09:40:31 +00003607void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003608 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003609 typedef CodeCompletionResult Result;
Douglas Gregorc464ae82009-12-07 09:27:33 +00003610 ResultBuilder Results(*this);
3611 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003612 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003613 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003614 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003615 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003616 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003617 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003618 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003619 HandleCodeCompleteResults(this, CodeCompleter,
3620 CodeCompletionContext::CCC_Other,
3621 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003622}
3623
Douglas Gregorbca403c2010-01-13 23:51:12 +00003624static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003625 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003626 CodeCompletionString *Pattern = 0;
3627
3628 // @encode ( type-name )
3629 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003630 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003631 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3632 Pattern->AddPlaceholderChunk("type-name");
3633 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003634 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003635
3636 // @protocol ( protocol-name )
3637 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003638 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003639 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3640 Pattern->AddPlaceholderChunk("protocol-name");
3641 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003642 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003643
3644 // @selector ( selector )
3645 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003646 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003647 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3648 Pattern->AddPlaceholderChunk("selector");
3649 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003650 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003651}
3652
Douglas Gregorbca403c2010-01-13 23:51:12 +00003653static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003654 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003655 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003657 if (Results.includeCodePatterns()) {
3658 // @try { statements } @catch ( declaration ) { statements } @finally
3659 // { statements }
3660 Pattern = new CodeCompletionString;
3661 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3662 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3663 Pattern->AddPlaceholderChunk("statements");
3664 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3665 Pattern->AddTextChunk("@catch");
3666 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3667 Pattern->AddPlaceholderChunk("parameter");
3668 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3669 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3670 Pattern->AddPlaceholderChunk("statements");
3671 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3672 Pattern->AddTextChunk("@finally");
3673 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3674 Pattern->AddPlaceholderChunk("statements");
3675 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3676 Results.AddResult(Result(Pattern));
3677 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003678
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003679 // @throw
3680 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003681 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003682 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003683 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003684 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003685
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003686 if (Results.includeCodePatterns()) {
3687 // @synchronized ( expression ) { statements }
3688 Pattern = new CodeCompletionString;
3689 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3690 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3691 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3692 Pattern->AddPlaceholderChunk("expression");
3693 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3694 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3695 Pattern->AddPlaceholderChunk("statements");
3696 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3697 Results.AddResult(Result(Pattern));
3698 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003699}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003700
Douglas Gregorbca403c2010-01-13 23:51:12 +00003701static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003702 ResultBuilder &Results,
3703 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003704 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003705 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3706 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3707 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003708 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003709 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003710}
3711
3712void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3713 ResultBuilder Results(*this);
3714 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003715 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003716 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003717 HandleCodeCompleteResults(this, CodeCompleter,
3718 CodeCompletionContext::CCC_Other,
3719 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003720}
3721
3722void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003723 ResultBuilder Results(*this);
3724 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003725 AddObjCStatementResults(Results, false);
3726 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003727 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003728 HandleCodeCompleteResults(this, CodeCompleter,
3729 CodeCompletionContext::CCC_Other,
3730 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003731}
3732
3733void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3734 ResultBuilder Results(*this);
3735 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003736 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003737 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003738 HandleCodeCompleteResults(this, CodeCompleter,
3739 CodeCompletionContext::CCC_Other,
3740 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003741}
3742
Douglas Gregor988358f2009-11-19 00:14:45 +00003743/// \brief Determine whether the addition of the given flag to an Objective-C
3744/// property's attributes will cause a conflict.
3745static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3746 // Check if we've already added this flag.
3747 if (Attributes & NewFlag)
3748 return true;
3749
3750 Attributes |= NewFlag;
3751
3752 // Check for collisions with "readonly".
3753 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3754 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3755 ObjCDeclSpec::DQ_PR_assign |
3756 ObjCDeclSpec::DQ_PR_copy |
3757 ObjCDeclSpec::DQ_PR_retain)))
3758 return true;
3759
3760 // Check for more than one of { assign, copy, retain }.
3761 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3762 ObjCDeclSpec::DQ_PR_copy |
3763 ObjCDeclSpec::DQ_PR_retain);
3764 if (AssignCopyRetMask &&
3765 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3766 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3767 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3768 return true;
3769
3770 return false;
3771}
3772
Douglas Gregora93b1082009-11-18 23:08:07 +00003773void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003774 if (!CodeCompleter)
3775 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003776
Steve Naroffece8e712009-10-08 21:55:05 +00003777 unsigned Attributes = ODS.getPropertyAttributes();
3778
John McCall0a2c5e22010-08-25 06:19:51 +00003779 typedef CodeCompletionResult Result;
Steve Naroffece8e712009-10-08 21:55:05 +00003780 ResultBuilder Results(*this);
3781 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003782 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003783 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003784 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003785 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003786 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003787 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003788 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003789 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003790 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003791 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003792 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003793 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003794 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003795 CodeCompletionString *Setter = new CodeCompletionString;
3796 Setter->AddTypedTextChunk("setter");
3797 Setter->AddTextChunk(" = ");
3798 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003799 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003800 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003801 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003802 CodeCompletionString *Getter = new CodeCompletionString;
3803 Getter->AddTypedTextChunk("getter");
3804 Getter->AddTextChunk(" = ");
3805 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003806 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003807 }
Steve Naroffece8e712009-10-08 21:55:05 +00003808 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003809 HandleCodeCompleteResults(this, CodeCompleter,
3810 CodeCompletionContext::CCC_Other,
3811 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003812}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003813
Douglas Gregor4ad96852009-11-19 07:41:15 +00003814/// \brief Descripts the kind of Objective-C method that we want to find
3815/// via code completion.
3816enum ObjCMethodKind {
3817 MK_Any, //< Any kind of method, provided it means other specified criteria.
3818 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3819 MK_OneArgSelector //< One-argument selector.
3820};
3821
Douglas Gregor458433d2010-08-26 15:07:07 +00003822static bool isAcceptableObjCSelector(Selector Sel,
3823 ObjCMethodKind WantKind,
3824 IdentifierInfo **SelIdents,
3825 unsigned NumSelIdents) {
3826 if (NumSelIdents > Sel.getNumArgs())
3827 return false;
3828
3829 switch (WantKind) {
3830 case MK_Any: break;
3831 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3832 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3833 }
3834
3835 for (unsigned I = 0; I != NumSelIdents; ++I)
3836 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3837 return false;
3838
3839 return true;
3840}
3841
Douglas Gregor4ad96852009-11-19 07:41:15 +00003842static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3843 ObjCMethodKind WantKind,
3844 IdentifierInfo **SelIdents,
3845 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00003846 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3847 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003848}
Douglas Gregord36adf52010-09-16 16:06:31 +00003849
3850namespace {
3851 /// \brief A set of selectors, which is used to avoid introducing multiple
3852 /// completions with the same selector into the result set.
3853 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
3854}
3855
Douglas Gregor36ecb042009-11-17 23:22:23 +00003856/// \brief Add all of the Objective-C methods in the given Objective-C
3857/// container to the set of results.
3858///
3859/// The container will be a class, protocol, category, or implementation of
3860/// any of the above. This mether will recurse to include methods from
3861/// the superclasses of classes along with their categories, protocols, and
3862/// implementations.
3863///
3864/// \param Container the container in which we'll look to find methods.
3865///
3866/// \param WantInstance whether to add instance methods (only); if false, this
3867/// routine will add factory methods (only).
3868///
3869/// \param CurContext the context in which we're performing the lookup that
3870/// finds methods.
3871///
3872/// \param Results the structure into which we'll add results.
3873static void AddObjCMethods(ObjCContainerDecl *Container,
3874 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003875 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003876 IdentifierInfo **SelIdents,
3877 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003878 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00003879 VisitedSelectorSet &Selectors,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003880 ResultBuilder &Results,
3881 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00003882 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00003883 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3884 MEnd = Container->meth_end();
3885 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003886 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3887 // Check whether the selector identifiers we've been given are a
3888 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003889 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003890 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003891
Douglas Gregord36adf52010-09-16 16:06:31 +00003892 if (!Selectors.insert((*M)->getSelector()))
3893 continue;
3894
Douglas Gregord3c68542009-11-19 01:08:35 +00003895 Result R = Result(*M, 0);
3896 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003897 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00003898 if (!InOriginalClass)
3899 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00003900 Results.MaybeAddResult(R, CurContext);
3901 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003902 }
3903
Douglas Gregore396c7b2010-09-16 15:34:59 +00003904 // Visit the protocols of protocols.
3905 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3906 const ObjCList<ObjCProtocolDecl> &Protocols
3907 = Protocol->getReferencedProtocols();
3908 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3909 E = Protocols.end();
3910 I != E; ++I)
3911 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003912 CurContext, Selectors, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00003913 }
3914
Douglas Gregor36ecb042009-11-17 23:22:23 +00003915 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3916 if (!IFace)
3917 return;
3918
3919 // Add methods in protocols.
3920 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3921 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3922 E = Protocols.end();
3923 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003924 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003925 CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003926
3927 // Add methods in categories.
3928 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3929 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003930 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003931 NumSelIdents, CurContext, Selectors, Results,
3932 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003933
3934 // Add a categories protocol methods.
3935 const ObjCList<ObjCProtocolDecl> &Protocols
3936 = CatDecl->getReferencedProtocols();
3937 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3938 E = Protocols.end();
3939 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003940 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003941 NumSelIdents, CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003942
3943 // Add methods in category implementations.
3944 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003945 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003946 NumSelIdents, CurContext, Selectors, Results,
3947 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003948 }
3949
3950 // Add methods in superclass.
3951 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003952 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregord36adf52010-09-16 16:06:31 +00003953 SelIdents, NumSelIdents, CurContext, Selectors, Results,
3954 false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003955
3956 // Add methods in our implementation, if any.
3957 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003958 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00003959 NumSelIdents, CurContext, Selectors, Results,
3960 InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003961}
3962
3963
John McCalld226f652010-08-21 09:40:31 +00003964void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
3965 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003966 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003967 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003968
3969 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00003970 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003971 if (!Class) {
3972 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003973 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003974 Class = Category->getClassInterface();
3975
3976 if (!Class)
3977 return;
3978 }
3979
3980 // Find all of the potential getters.
3981 ResultBuilder Results(*this);
3982 Results.EnterNewScope();
3983
3984 // FIXME: We need to do this because Objective-C methods don't get
3985 // pushed into DeclContexts early enough. Argh!
3986 for (unsigned I = 0; I != NumMethods; ++I) {
3987 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003988 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003989 if (Method->isInstanceMethod() &&
3990 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3991 Result R = Result(Method, 0);
3992 R.AllParametersAreInformative = true;
3993 Results.MaybeAddResult(R, CurContext);
3994 }
3995 }
3996
Douglas Gregord36adf52010-09-16 16:06:31 +00003997 VisitedSelectorSet Selectors;
3998 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
3999 Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004000 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004001 HandleCodeCompleteResults(this, CodeCompleter,
4002 CodeCompletionContext::CCC_Other,
4003 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004004}
4005
John McCalld226f652010-08-21 09:40:31 +00004006void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
4007 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004008 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00004009 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004010
4011 // Try to find the interface where setters might live.
4012 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004013 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004014 if (!Class) {
4015 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004016 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004017 Class = Category->getClassInterface();
4018
4019 if (!Class)
4020 return;
4021 }
4022
4023 // Find all of the potential getters.
4024 ResultBuilder Results(*this);
4025 Results.EnterNewScope();
4026
4027 // FIXME: We need to do this because Objective-C methods don't get
4028 // pushed into DeclContexts early enough. Argh!
4029 for (unsigned I = 0; I != NumMethods; ++I) {
4030 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00004031 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004032 if (Method->isInstanceMethod() &&
4033 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
4034 Result R = Result(Method, 0);
4035 R.AllParametersAreInformative = true;
4036 Results.MaybeAddResult(R, CurContext);
4037 }
4038 }
4039
Douglas Gregord36adf52010-09-16 16:06:31 +00004040 VisitedSelectorSet Selectors;
4041 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4042 Selectors, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004043
4044 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004045 HandleCodeCompleteResults(this, CodeCompleter,
4046 CodeCompletionContext::CCC_Other,
4047 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004048}
4049
Douglas Gregord32b0222010-08-24 01:06:58 +00004050void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00004051 typedef CodeCompletionResult Result;
Douglas Gregord32b0222010-08-24 01:06:58 +00004052 ResultBuilder Results(*this);
4053 Results.EnterNewScope();
4054
4055 // Add context-sensitive, Objective-C parameter-passing keywords.
4056 bool AddedInOut = false;
4057 if ((DS.getObjCDeclQualifier() &
4058 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4059 Results.AddResult("in");
4060 Results.AddResult("inout");
4061 AddedInOut = true;
4062 }
4063 if ((DS.getObjCDeclQualifier() &
4064 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4065 Results.AddResult("out");
4066 if (!AddedInOut)
4067 Results.AddResult("inout");
4068 }
4069 if ((DS.getObjCDeclQualifier() &
4070 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4071 ObjCDeclSpec::DQ_Oneway)) == 0) {
4072 Results.AddResult("bycopy");
4073 Results.AddResult("byref");
4074 Results.AddResult("oneway");
4075 }
4076
4077 // Add various builtin type names and specifiers.
4078 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4079 Results.ExitScope();
4080
4081 // Add the various type names
4082 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4083 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4084 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4085 CodeCompleter->includeGlobals());
4086
4087 if (CodeCompleter->includeMacros())
4088 AddMacroResults(PP, Results);
4089
4090 HandleCodeCompleteResults(this, CodeCompleter,
4091 CodeCompletionContext::CCC_Type,
4092 Results.data(), Results.size());
4093}
4094
Douglas Gregor22f56992010-04-06 19:22:33 +00004095/// \brief When we have an expression with type "id", we may assume
4096/// that it has some more-specific class type based on knowledge of
4097/// common uses of Objective-C. This routine returns that class type,
4098/// or NULL if no better result could be determined.
4099static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004100 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004101 if (!Msg)
4102 return 0;
4103
4104 Selector Sel = Msg->getSelector();
4105 if (Sel.isNull())
4106 return 0;
4107
4108 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4109 if (!Id)
4110 return 0;
4111
4112 ObjCMethodDecl *Method = Msg->getMethodDecl();
4113 if (!Method)
4114 return 0;
4115
4116 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004117 ObjCInterfaceDecl *IFace = 0;
4118 switch (Msg->getReceiverKind()) {
4119 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004120 if (const ObjCObjectType *ObjType
4121 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4122 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004123 break;
4124
4125 case ObjCMessageExpr::Instance: {
4126 QualType T = Msg->getInstanceReceiver()->getType();
4127 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4128 IFace = Ptr->getInterfaceDecl();
4129 break;
4130 }
4131
4132 case ObjCMessageExpr::SuperInstance:
4133 case ObjCMessageExpr::SuperClass:
4134 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004135 }
4136
4137 if (!IFace)
4138 return 0;
4139
4140 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4141 if (Method->isInstanceMethod())
4142 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4143 .Case("retain", IFace)
4144 .Case("autorelease", IFace)
4145 .Case("copy", IFace)
4146 .Case("copyWithZone", IFace)
4147 .Case("mutableCopy", IFace)
4148 .Case("mutableCopyWithZone", IFace)
4149 .Case("awakeFromCoder", IFace)
4150 .Case("replacementObjectFromCoder", IFace)
4151 .Case("class", IFace)
4152 .Case("classForCoder", IFace)
4153 .Case("superclass", Super)
4154 .Default(0);
4155
4156 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4157 .Case("new", IFace)
4158 .Case("alloc", IFace)
4159 .Case("allocWithZone", IFace)
4160 .Case("class", IFace)
4161 .Case("superclass", Super)
4162 .Default(0);
4163}
4164
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004165// Add a special completion for a message send to "super", which fills in the
4166// most likely case of forwarding all of our arguments to the superclass
4167// function.
4168///
4169/// \param S The semantic analysis object.
4170///
4171/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4172/// the "super" keyword. Otherwise, we just need to provide the arguments.
4173///
4174/// \param SelIdents The identifiers in the selector that have already been
4175/// provided as arguments for a send to "super".
4176///
4177/// \param NumSelIdents The number of identifiers in \p SelIdents.
4178///
4179/// \param Results The set of results to augment.
4180///
4181/// \returns the Objective-C method declaration that would be invoked by
4182/// this "super" completion. If NULL, no completion was added.
4183static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4184 IdentifierInfo **SelIdents,
4185 unsigned NumSelIdents,
4186 ResultBuilder &Results) {
4187 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4188 if (!CurMethod)
4189 return 0;
4190
4191 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4192 if (!Class)
4193 return 0;
4194
4195 // Try to find a superclass method with the same selector.
4196 ObjCMethodDecl *SuperMethod = 0;
4197 while ((Class = Class->getSuperClass()) && !SuperMethod)
4198 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4199 CurMethod->isInstanceMethod());
4200
4201 if (!SuperMethod)
4202 return 0;
4203
4204 // Check whether the superclass method has the same signature.
4205 if (CurMethod->param_size() != SuperMethod->param_size() ||
4206 CurMethod->isVariadic() != SuperMethod->isVariadic())
4207 return 0;
4208
4209 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4210 CurPEnd = CurMethod->param_end(),
4211 SuperP = SuperMethod->param_begin();
4212 CurP != CurPEnd; ++CurP, ++SuperP) {
4213 // Make sure the parameter types are compatible.
4214 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4215 (*SuperP)->getType()))
4216 return 0;
4217
4218 // Make sure we have a parameter name to forward!
4219 if (!(*CurP)->getIdentifier())
4220 return 0;
4221 }
4222
4223 // We have a superclass method. Now, form the send-to-super completion.
4224 CodeCompletionString *Pattern = new CodeCompletionString;
4225
4226 // Give this completion a return type.
4227 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4228
4229 // If we need the "super" keyword, add it (plus some spacing).
4230 if (NeedSuperKeyword) {
4231 Pattern->AddTypedTextChunk("super");
4232 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4233 }
4234
4235 Selector Sel = CurMethod->getSelector();
4236 if (Sel.isUnarySelector()) {
4237 if (NeedSuperKeyword)
4238 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4239 else
4240 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4241 } else {
4242 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4243 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4244 if (I > NumSelIdents)
4245 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4246
4247 if (I < NumSelIdents)
4248 Pattern->AddInformativeChunk(
4249 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4250 else if (NeedSuperKeyword || I > NumSelIdents) {
4251 Pattern->AddTextChunk(
4252 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4253 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4254 } else {
4255 Pattern->AddTypedTextChunk(
4256 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4257 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4258 }
4259 }
4260 }
4261
4262 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4263 SuperMethod->isInstanceMethod()
4264 ? CXCursor_ObjCInstanceMethodDecl
4265 : CXCursor_ObjCClassMethodDecl));
4266 return SuperMethod;
4267}
4268
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004269void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004270 typedef CodeCompletionResult Result;
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004271 ResultBuilder Results(*this);
4272
4273 // Find anything that looks like it could be a message receiver.
4274 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004275 Results.setCompletionContext(CodeCompletionContext::CCC_ObjCMessageReceiver);
4276
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004277 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4278 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004279 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4280 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004281
4282 // If we are in an Objective-C method inside a class that has a superclass,
4283 // add "super" as an option.
4284 if (ObjCMethodDecl *Method = getCurMethodDecl())
4285 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004286 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004287 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004288
4289 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4290 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004291
4292 Results.ExitScope();
4293
4294 if (CodeCompleter->includeMacros())
4295 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004296 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004297 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004298
4299}
4300
Douglas Gregor2725ca82010-04-21 19:57:20 +00004301void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4302 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004303 unsigned NumSelIdents,
4304 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004305 ObjCInterfaceDecl *CDecl = 0;
4306 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4307 // Figure out which interface we're in.
4308 CDecl = CurMethod->getClassInterface();
4309 if (!CDecl)
4310 return;
4311
4312 // Find the superclass of this class.
4313 CDecl = CDecl->getSuperClass();
4314 if (!CDecl)
4315 return;
4316
4317 if (CurMethod->isInstanceMethod()) {
4318 // We are inside an instance method, which means that the message
4319 // send [super ...] is actually calling an instance method on the
4320 // current object. Build the super expression and handle this like
4321 // an instance method.
4322 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
4323 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall60d7b3a2010-08-24 06:29:42 +00004324 ExprResult Super
Douglas Gregor2725ca82010-04-21 19:57:20 +00004325 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
4326 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004327 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004328 AtArgumentExpression,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004329 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004330 }
4331
4332 // Fall through to send to the superclass in CDecl.
4333 } else {
4334 // "super" may be the name of a type or variable. Figure out which
4335 // it is.
4336 IdentifierInfo *Super = &Context.Idents.get("super");
4337 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4338 LookupOrdinaryName);
4339 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4340 // "super" names an interface. Use it.
4341 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004342 if (const ObjCObjectType *Iface
4343 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4344 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004345 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4346 // "super" names an unresolved type; we can't be more specific.
4347 } else {
4348 // Assume that "super" names some kind of value and parse that way.
4349 CXXScopeSpec SS;
4350 UnqualifiedId id;
4351 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004352 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004353 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004354 SelIdents, NumSelIdents,
4355 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004356 }
4357
4358 // Fall through
4359 }
4360
John McCallb3d87482010-08-24 05:47:05 +00004361 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004362 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004363 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004364 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004365 NumSelIdents, AtArgumentExpression,
4366 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004367}
4368
Douglas Gregorb9d77572010-09-21 00:03:25 +00004369/// \brief Given a set of code-completion results for the argument of a message
4370/// send, determine the preferred type (if any) for that argument expression.
4371static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4372 unsigned NumSelIdents) {
4373 typedef CodeCompletionResult Result;
4374 ASTContext &Context = Results.getSema().Context;
4375
4376 QualType PreferredType;
4377 unsigned BestPriority = CCP_Unlikely * 2;
4378 Result *ResultsData = Results.data();
4379 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4380 Result &R = ResultsData[I];
4381 if (R.Kind == Result::RK_Declaration &&
4382 isa<ObjCMethodDecl>(R.Declaration)) {
4383 if (R.Priority <= BestPriority) {
4384 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4385 if (NumSelIdents <= Method->param_size()) {
4386 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4387 ->getType();
4388 if (R.Priority < BestPriority || PreferredType.isNull()) {
4389 BestPriority = R.Priority;
4390 PreferredType = MyPreferredType;
4391 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4392 MyPreferredType)) {
4393 PreferredType = QualType();
4394 }
4395 }
4396 }
4397 }
4398 }
4399
4400 return PreferredType;
4401}
4402
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004403static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4404 ParsedType Receiver,
4405 IdentifierInfo **SelIdents,
4406 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004407 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004408 bool IsSuper,
4409 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004410 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004411 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004412
Douglas Gregor24a069f2009-11-17 17:59:40 +00004413 // If the given name refers to an interface type, retrieve the
4414 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004415 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004416 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004417 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004418 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4419 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004420 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004421
Douglas Gregor36ecb042009-11-17 23:22:23 +00004422 // Add all of the factory methods in this Objective-C class, its protocols,
4423 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004424 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004425
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004426 // If this is a send-to-super, try to add the special "super" send
4427 // completion.
4428 if (IsSuper) {
4429 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004430 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4431 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004432 Results.Ignore(SuperMethod);
4433 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004434
Douglas Gregor265f7492010-08-27 15:29:55 +00004435 // If we're inside an Objective-C method definition, prefer its selector to
4436 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004437 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004438 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004439
Douglas Gregord36adf52010-09-16 16:06:31 +00004440 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004441 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004442 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004443 SemaRef.CurContext, Selectors, Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004444 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004445 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004446
Douglas Gregor719770d2010-04-06 17:30:22 +00004447 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004448 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004449 if (SemaRef.ExternalSource) {
4450 for (uint32_t I = 0,
4451 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004452 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004453 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4454 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004455 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004456
4457 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004458 }
4459 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004460
4461 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4462 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004463 M != MEnd; ++M) {
4464 for (ObjCMethodList *MethList = &M->second.second;
4465 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004466 MethList = MethList->Next) {
4467 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4468 NumSelIdents))
4469 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004470
Douglas Gregor13438f92010-04-06 16:40:00 +00004471 Result R(MethList->Method, 0);
4472 R.StartParameter = NumSelIdents;
4473 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004474 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004475 }
4476 }
4477 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004478
4479 Results.ExitScope();
4480}
Douglas Gregor13438f92010-04-06 16:40:00 +00004481
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004482void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4483 IdentifierInfo **SelIdents,
4484 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004485 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004486 bool IsSuper) {
4487 ResultBuilder Results(*this);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004488 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4489 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004490
4491 // If we're actually at the argument expression (rather than prior to the
4492 // selector), we're actually performing code completion for an expression.
4493 // Determine whether we have a single, best method. If so, we can
4494 // code-complete the expression using the corresponding parameter type as
4495 // our preferred type, improving completion results.
4496 if (AtArgumentExpression) {
4497 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4498 NumSelIdents);
4499 if (PreferredType.isNull())
4500 CodeCompleteOrdinaryName(S, PCC_Expression);
4501 else
4502 CodeCompleteExpression(S, PreferredType);
4503 return;
4504 }
4505
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004506 HandleCodeCompleteResults(this, CodeCompleter,
4507 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004508 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004509}
4510
Douglas Gregord3c68542009-11-19 01:08:35 +00004511void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4512 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004513 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004514 bool AtArgumentExpression,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004515 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004516 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004517
4518 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004519
Douglas Gregor36ecb042009-11-17 23:22:23 +00004520 // If necessary, apply function/array conversion to the receiver.
4521 // C99 6.7.5.3p[7,8].
Douglas Gregor78edf512010-09-15 16:23:04 +00004522 if (RecExpr)
4523 DefaultFunctionArrayLvalueConversion(RecExpr);
4524 QualType ReceiverType = RecExpr? RecExpr->getType() : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004525
Douglas Gregor36ecb042009-11-17 23:22:23 +00004526 // Build the set of methods we can see.
4527 ResultBuilder Results(*this);
4528 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004529
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004530 // If this is a send-to-super, try to add the special "super" send
4531 // completion.
4532 if (IsSuper) {
4533 if (ObjCMethodDecl *SuperMethod
4534 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4535 Results))
4536 Results.Ignore(SuperMethod);
4537 }
4538
Douglas Gregor265f7492010-08-27 15:29:55 +00004539 // If we're inside an Objective-C method definition, prefer its selector to
4540 // others.
4541 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4542 Results.setPreferredSelector(CurMethod->getSelector());
4543
Douglas Gregor22f56992010-04-06 19:22:33 +00004544 // If we're messaging an expression with type "id" or "Class", check
4545 // whether we know something special about the receiver that allows
4546 // us to assume a more-specific receiver type.
4547 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4548 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4549 ReceiverType = Context.getObjCObjectPointerType(
4550 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00004551
Douglas Gregord36adf52010-09-16 16:06:31 +00004552 // Keep track of the selectors we've already added.
4553 VisitedSelectorSet Selectors;
4554
Douglas Gregorf74a4192009-11-18 00:06:18 +00004555 // Handle messages to Class. This really isn't a message to an instance
4556 // method, so we treat it the same way we would treat a message send to a
4557 // class method.
4558 if (ReceiverType->isObjCClassType() ||
4559 ReceiverType->isObjCQualifiedClassType()) {
4560 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4561 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004562 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004563 CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004564 }
4565 }
4566 // Handle messages to a qualified ID ("id<foo>").
4567 else if (const ObjCObjectPointerType *QualID
4568 = ReceiverType->getAsObjCQualifiedIdType()) {
4569 // Search protocols for instance methods.
4570 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4571 E = QualID->qual_end();
4572 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004573 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004574 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004575 }
4576 // Handle messages to a pointer to interface type.
4577 else if (const ObjCObjectPointerType *IFacePtr
4578 = ReceiverType->getAsObjCInterfacePointerType()) {
4579 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004580 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004581 NumSelIdents, CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004582
4583 // Search protocols for instance methods.
4584 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4585 E = IFacePtr->qual_end();
4586 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004587 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004588 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004589 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004590 // Handle messages to "id".
4591 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004592 // We're messaging "id", so provide all instance methods we know
4593 // about as code-completion results.
4594
4595 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004596 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004597 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004598 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4599 I != N; ++I) {
4600 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004601 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004602 continue;
4603
Sebastian Redldb9d2142010-08-02 23:18:59 +00004604 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004605 }
4606 }
4607
Sebastian Redldb9d2142010-08-02 23:18:59 +00004608 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4609 MEnd = MethodPool.end();
4610 M != MEnd; ++M) {
4611 for (ObjCMethodList *MethList = &M->second.first;
4612 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004613 MethList = MethList->Next) {
4614 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4615 NumSelIdents))
4616 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00004617
4618 if (!Selectors.insert(MethList->Method->getSelector()))
4619 continue;
4620
Douglas Gregor13438f92010-04-06 16:40:00 +00004621 Result R(MethList->Method, 0);
4622 R.StartParameter = NumSelIdents;
4623 R.AllParametersAreInformative = false;
4624 Results.MaybeAddResult(R, CurContext);
4625 }
4626 }
4627 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00004628 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00004629
4630
4631 // If we're actually at the argument expression (rather than prior to the
4632 // selector), we're actually performing code completion for an expression.
4633 // Determine whether we have a single, best method. If so, we can
4634 // code-complete the expression using the corresponding parameter type as
4635 // our preferred type, improving completion results.
4636 if (AtArgumentExpression) {
4637 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4638 NumSelIdents);
4639 if (PreferredType.isNull())
4640 CodeCompleteOrdinaryName(S, PCC_Expression);
4641 else
4642 CodeCompleteExpression(S, PreferredType);
4643 return;
4644 }
4645
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004646 HandleCodeCompleteResults(this, CodeCompleter,
4647 CodeCompletionContext::CCC_Other,
4648 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004649}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004650
Douglas Gregorfb629412010-08-23 21:17:50 +00004651void Sema::CodeCompleteObjCForCollection(Scope *S,
4652 DeclGroupPtrTy IterationVar) {
4653 CodeCompleteExpressionData Data;
4654 Data.ObjCCollection = true;
4655
4656 if (IterationVar.getAsOpaquePtr()) {
4657 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4658 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4659 if (*I)
4660 Data.IgnoreDecls.push_back(*I);
4661 }
4662 }
4663
4664 CodeCompleteExpression(S, Data);
4665}
4666
Douglas Gregor458433d2010-08-26 15:07:07 +00004667void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4668 unsigned NumSelIdents) {
4669 // If we have an external source, load the entire class method
4670 // pool from the AST file.
4671 if (ExternalSource) {
4672 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4673 I != N; ++I) {
4674 Selector Sel = ExternalSource->GetExternalSelector(I);
4675 if (Sel.isNull() || MethodPool.count(Sel))
4676 continue;
4677
4678 ReadMethodPool(Sel);
4679 }
4680 }
4681
4682 ResultBuilder Results(*this);
4683 Results.EnterNewScope();
4684 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4685 MEnd = MethodPool.end();
4686 M != MEnd; ++M) {
4687
4688 Selector Sel = M->first;
4689 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4690 continue;
4691
4692 CodeCompletionString *Pattern = new CodeCompletionString;
4693 if (Sel.isUnarySelector()) {
4694 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4695 Results.AddResult(Pattern);
4696 continue;
4697 }
4698
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004699 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004700 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004701 if (I == NumSelIdents) {
4702 if (!Accumulator.empty()) {
4703 Pattern->AddInformativeChunk(Accumulator);
4704 Accumulator.clear();
4705 }
4706 }
4707
4708 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4709 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004710 }
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004711 Pattern->AddTypedTextChunk(Accumulator);
Douglas Gregor458433d2010-08-26 15:07:07 +00004712 Results.AddResult(Pattern);
4713 }
4714 Results.ExitScope();
4715
4716 HandleCodeCompleteResults(this, CodeCompleter,
4717 CodeCompletionContext::CCC_SelectorName,
4718 Results.data(), Results.size());
4719}
4720
Douglas Gregor55385fe2009-11-18 04:19:12 +00004721/// \brief Add all of the protocol declarations that we find in the given
4722/// (translation unit) context.
4723static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004724 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004725 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004726 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004727
4728 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4729 DEnd = Ctx->decls_end();
4730 D != DEnd; ++D) {
4731 // Record any protocols we find.
4732 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004733 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004734 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004735
4736 // Record any forward-declared protocols we find.
4737 if (ObjCForwardProtocolDecl *Forward
4738 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4739 for (ObjCForwardProtocolDecl::protocol_iterator
4740 P = Forward->protocol_begin(),
4741 PEnd = Forward->protocol_end();
4742 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004743 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004744 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004745 }
4746 }
4747}
4748
4749void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4750 unsigned NumProtocols) {
4751 ResultBuilder Results(*this);
4752 Results.EnterNewScope();
4753
4754 // Tell the result set to ignore all of the protocols we have
4755 // already seen.
4756 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004757 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4758 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004759 Results.Ignore(Protocol);
4760
4761 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004762 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4763 Results);
4764
4765 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004766 HandleCodeCompleteResults(this, CodeCompleter,
4767 CodeCompletionContext::CCC_ObjCProtocolName,
4768 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004769}
4770
4771void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4772 ResultBuilder Results(*this);
4773 Results.EnterNewScope();
4774
4775 // Add all protocols.
4776 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4777 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004778
4779 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004780 HandleCodeCompleteResults(this, CodeCompleter,
4781 CodeCompletionContext::CCC_ObjCProtocolName,
4782 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004783}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004784
4785/// \brief Add all of the Objective-C interface declarations that we find in
4786/// the given (translation unit) context.
4787static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4788 bool OnlyForwardDeclarations,
4789 bool OnlyUnimplemented,
4790 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004791 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004792
4793 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4794 DEnd = Ctx->decls_end();
4795 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004796 // Record any interfaces we find.
4797 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4798 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4799 (!OnlyUnimplemented || !Class->getImplementation()))
4800 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004801
4802 // Record any forward-declared interfaces we find.
4803 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4804 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004805 C != CEnd; ++C)
4806 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4807 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4808 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004809 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004810 }
4811 }
4812}
4813
4814void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
4815 ResultBuilder Results(*this);
4816 Results.EnterNewScope();
4817
4818 // Add all classes.
4819 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4820 false, Results);
4821
4822 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004823 HandleCodeCompleteResults(this, CodeCompleter,
4824 CodeCompletionContext::CCC_Other,
4825 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004826}
4827
Douglas Gregorc83c6872010-04-15 22:33:43 +00004828void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4829 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004830 ResultBuilder Results(*this);
4831 Results.EnterNewScope();
4832
4833 // Make sure that we ignore the class we're currently defining.
4834 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004835 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004836 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004837 Results.Ignore(CurClass);
4838
4839 // Add all classes.
4840 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4841 false, Results);
4842
4843 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004844 HandleCodeCompleteResults(this, CodeCompleter,
4845 CodeCompletionContext::CCC_Other,
4846 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004847}
4848
4849void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
4850 ResultBuilder Results(*this);
4851 Results.EnterNewScope();
4852
4853 // Add all unimplemented classes.
4854 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4855 true, Results);
4856
4857 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004858 HandleCodeCompleteResults(this, CodeCompleter,
4859 CodeCompletionContext::CCC_Other,
4860 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004861}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004862
4863void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004864 IdentifierInfo *ClassName,
4865 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004866 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004867
4868 ResultBuilder Results(*this);
4869
4870 // Ignore any categories we find that have already been implemented by this
4871 // interface.
4872 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4873 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004874 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004875 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
4876 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4877 Category = Category->getNextClassCategory())
4878 CategoryNames.insert(Category->getIdentifier());
4879
4880 // Add all of the categories we know about.
4881 Results.EnterNewScope();
4882 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4883 for (DeclContext::decl_iterator D = TU->decls_begin(),
4884 DEnd = TU->decls_end();
4885 D != DEnd; ++D)
4886 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
4887 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004888 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004889 Results.ExitScope();
4890
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004891 HandleCodeCompleteResults(this, CodeCompleter,
4892 CodeCompletionContext::CCC_Other,
4893 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004894}
4895
4896void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004897 IdentifierInfo *ClassName,
4898 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004899 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004900
4901 // Find the corresponding interface. If we couldn't find the interface, the
4902 // program itself is ill-formed. However, we'll try to be helpful still by
4903 // providing the list of all of the categories we know about.
4904 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004905 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004906 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
4907 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004908 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004909
4910 ResultBuilder Results(*this);
4911
4912 // Add all of the categories that have have corresponding interface
4913 // declarations in this class and any of its superclasses, except for
4914 // already-implemented categories in the class itself.
4915 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4916 Results.EnterNewScope();
4917 bool IgnoreImplemented = true;
4918 while (Class) {
4919 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4920 Category = Category->getNextClassCategory())
4921 if ((!IgnoreImplemented || !Category->getImplementation()) &&
4922 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004923 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004924
4925 Class = Class->getSuperClass();
4926 IgnoreImplemented = false;
4927 }
4928 Results.ExitScope();
4929
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004930 HandleCodeCompleteResults(this, CodeCompleter,
4931 CodeCompletionContext::CCC_Other,
4932 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004933}
Douglas Gregor322328b2009-11-18 22:32:06 +00004934
John McCalld226f652010-08-21 09:40:31 +00004935void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004936 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004937 ResultBuilder Results(*this);
4938
4939 // Figure out where this @synthesize lives.
4940 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004941 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004942 if (!Container ||
4943 (!isa<ObjCImplementationDecl>(Container) &&
4944 !isa<ObjCCategoryImplDecl>(Container)))
4945 return;
4946
4947 // Ignore any properties that have already been implemented.
4948 for (DeclContext::decl_iterator D = Container->decls_begin(),
4949 DEnd = Container->decls_end();
4950 D != DEnd; ++D)
4951 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4952 Results.Ignore(PropertyImpl->getPropertyDecl());
4953
4954 // Add any properties that we find.
4955 Results.EnterNewScope();
4956 if (ObjCImplementationDecl *ClassImpl
4957 = dyn_cast<ObjCImplementationDecl>(Container))
4958 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4959 Results);
4960 else
4961 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4962 false, CurContext, Results);
4963 Results.ExitScope();
4964
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004965 HandleCodeCompleteResults(this, CodeCompleter,
4966 CodeCompletionContext::CCC_Other,
4967 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004968}
4969
4970void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4971 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00004972 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004973 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004974 ResultBuilder Results(*this);
4975
4976 // Figure out where this @synthesize lives.
4977 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004978 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004979 if (!Container ||
4980 (!isa<ObjCImplementationDecl>(Container) &&
4981 !isa<ObjCCategoryImplDecl>(Container)))
4982 return;
4983
4984 // Figure out which interface we're looking into.
4985 ObjCInterfaceDecl *Class = 0;
4986 if (ObjCImplementationDecl *ClassImpl
4987 = dyn_cast<ObjCImplementationDecl>(Container))
4988 Class = ClassImpl->getClassInterface();
4989 else
4990 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4991 ->getClassInterface();
4992
4993 // Add all of the instance variables in this class and its superclasses.
4994 Results.EnterNewScope();
4995 for(; Class; Class = Class->getSuperClass()) {
4996 // FIXME: We could screen the type of each ivar for compatibility with
4997 // the property, but is that being too paternal?
4998 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4999 IVarEnd = Class->ivar_end();
5000 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00005001 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00005002 }
5003 Results.ExitScope();
5004
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005005 HandleCodeCompleteResults(this, CodeCompleter,
5006 CodeCompletionContext::CCC_Other,
5007 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005008}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005009
Douglas Gregor408be5a2010-08-25 01:08:01 +00005010// Mapping from selectors to the methods that implement that selector, along
5011// with the "in original class" flag.
5012typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5013 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005014
5015/// \brief Find all of the methods that reside in the given container
5016/// (and its superclasses, protocols, etc.) that meet the given
5017/// criteria. Insert those methods into the map of known methods,
5018/// indexed by selector so they can be easily found.
5019static void FindImplementableMethods(ASTContext &Context,
5020 ObjCContainerDecl *Container,
5021 bool WantInstanceMethods,
5022 QualType ReturnType,
5023 bool IsInImplementation,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005024 KnownMethodsMap &KnownMethods,
5025 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005026 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5027 // Recurse into protocols.
5028 const ObjCList<ObjCProtocolDecl> &Protocols
5029 = IFace->getReferencedProtocols();
5030 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5031 E = Protocols.end();
5032 I != E; ++I)
5033 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005034 IsInImplementation, KnownMethods,
5035 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005036
5037 // If we're not in the implementation of a class, also visit the
5038 // superclass.
5039 if (!IsInImplementation && IFace->getSuperClass())
5040 FindImplementableMethods(Context, IFace->getSuperClass(),
5041 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005042 IsInImplementation, KnownMethods,
5043 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005044
5045 // Add methods from any class extensions (but not from categories;
5046 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005047 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
5048 Cat = Cat->getNextClassExtension())
5049 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5050 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005051 IsInImplementation, KnownMethods,
5052 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005053 }
5054
5055 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5056 // Recurse into protocols.
5057 const ObjCList<ObjCProtocolDecl> &Protocols
5058 = Category->getReferencedProtocols();
5059 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5060 E = Protocols.end();
5061 I != E; ++I)
5062 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005063 IsInImplementation, KnownMethods,
5064 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005065 }
5066
5067 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5068 // Recurse into protocols.
5069 const ObjCList<ObjCProtocolDecl> &Protocols
5070 = Protocol->getReferencedProtocols();
5071 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5072 E = Protocols.end();
5073 I != E; ++I)
5074 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005075 IsInImplementation, KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005076 }
5077
5078 // Add methods in this container. This operation occurs last because
5079 // we want the methods from this container to override any methods
5080 // we've previously seen with the same selector.
5081 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5082 MEnd = Container->meth_end();
5083 M != MEnd; ++M) {
5084 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5085 if (!ReturnType.isNull() &&
5086 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5087 continue;
5088
Douglas Gregor408be5a2010-08-25 01:08:01 +00005089 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005090 }
5091 }
5092}
5093
5094void Sema::CodeCompleteObjCMethodDecl(Scope *S,
5095 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00005096 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00005097 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005098 // Determine the return type of the method we're declaring, if
5099 // provided.
5100 QualType ReturnType = GetTypeFromParser(ReturnTy);
5101
5102 // Determine where we should start searching for methods, and where we
5103 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
5104 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00005105 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005106 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
5107 SearchDecl = Impl->getClassInterface();
5108 CurrentDecl = Impl;
5109 IsInImplementation = true;
5110 } else if (ObjCCategoryImplDecl *CatImpl
5111 = dyn_cast<ObjCCategoryImplDecl>(D)) {
5112 SearchDecl = CatImpl->getCategoryDecl();
5113 CurrentDecl = CatImpl;
5114 IsInImplementation = true;
5115 } else {
5116 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
5117 CurrentDecl = SearchDecl;
5118 }
5119 }
5120
5121 if (!SearchDecl && S) {
5122 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
5123 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
5124 CurrentDecl = SearchDecl;
5125 }
5126 }
5127
5128 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005129 HandleCodeCompleteResults(this, CodeCompleter,
5130 CodeCompletionContext::CCC_Other,
5131 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005132 return;
5133 }
5134
5135 // Find all of the methods that we could declare/implement here.
5136 KnownMethodsMap KnownMethods;
5137 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
5138 ReturnType, IsInImplementation, KnownMethods);
5139
5140 // Erase any methods that have already been declared or
5141 // implemented here.
5142 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
5143 MEnd = CurrentDecl->meth_end();
5144 M != MEnd; ++M) {
5145 if ((*M)->isInstanceMethod() != IsInstanceMethod)
5146 continue;
5147
5148 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
5149 if (Pos != KnownMethods.end())
5150 KnownMethods.erase(Pos);
5151 }
5152
5153 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00005154 typedef CodeCompletionResult Result;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005155 ResultBuilder Results(*this);
5156 Results.EnterNewScope();
5157 PrintingPolicy Policy(Context.PrintingPolicy);
5158 Policy.AnonymousTagLocations = false;
5159 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
5160 MEnd = KnownMethods.end();
5161 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00005162 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005163 CodeCompletionString *Pattern = new CodeCompletionString;
5164
5165 // If the result type was not already provided, add it to the
5166 // pattern as (type).
5167 if (ReturnType.isNull()) {
5168 std::string TypeStr;
5169 Method->getResultType().getAsStringInternal(TypeStr, Policy);
5170 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5171 Pattern->AddTextChunk(TypeStr);
5172 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5173 }
5174
5175 Selector Sel = Method->getSelector();
5176
5177 // Add the first part of the selector to the pattern.
5178 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
5179
5180 // Add parameters to the pattern.
5181 unsigned I = 0;
5182 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5183 PEnd = Method->param_end();
5184 P != PEnd; (void)++P, ++I) {
5185 // Add the part of the selector name.
5186 if (I == 0)
5187 Pattern->AddChunk(CodeCompletionString::CK_Colon);
5188 else if (I < Sel.getNumArgs()) {
5189 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor47c03a72010-08-17 15:53:35 +00005190 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005191 Pattern->AddChunk(CodeCompletionString::CK_Colon);
5192 } else
5193 break;
5194
5195 // Add the parameter type.
5196 std::string TypeStr;
5197 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
5198 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5199 Pattern->AddTextChunk(TypeStr);
5200 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5201
5202 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregore17794f2010-08-31 05:13:43 +00005203 Pattern->AddTextChunk(Id->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005204 }
5205
5206 if (Method->isVariadic()) {
5207 if (Method->param_size() > 0)
5208 Pattern->AddChunk(CodeCompletionString::CK_Comma);
5209 Pattern->AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00005210 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005211
Douglas Gregor447107d2010-05-28 00:57:46 +00005212 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005213 // We will be defining the method here, so add a compound statement.
5214 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5215 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
5216 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5217 if (!Method->getResultType()->isVoidType()) {
5218 // If the result type is not void, add a return clause.
5219 Pattern->AddTextChunk("return");
5220 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5221 Pattern->AddPlaceholderChunk("expression");
5222 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
5223 } else
5224 Pattern->AddPlaceholderChunk("statements");
5225
5226 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5227 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
5228 }
5229
Douglas Gregor408be5a2010-08-25 01:08:01 +00005230 unsigned Priority = CCP_CodePattern;
5231 if (!M->second.second)
5232 Priority += CCD_InBaseClass;
5233
5234 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00005235 Method->isInstanceMethod()
5236 ? CXCursor_ObjCInstanceMethodDecl
5237 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005238 }
5239
5240 Results.ExitScope();
5241
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005242 HandleCodeCompleteResults(this, CodeCompleter,
5243 CodeCompletionContext::CCC_Other,
5244 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005245}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005246
5247void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5248 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005249 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00005250 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005251 IdentifierInfo **SelIdents,
5252 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005253 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005254 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005255 if (ExternalSource) {
5256 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5257 I != N; ++I) {
5258 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005259 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005260 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00005261
5262 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005263 }
5264 }
5265
5266 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00005267 typedef CodeCompletionResult Result;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005268 ResultBuilder Results(*this);
5269
5270 if (ReturnTy)
5271 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00005272
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005273 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005274 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5275 MEnd = MethodPool.end();
5276 M != MEnd; ++M) {
5277 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5278 &M->second.second;
5279 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005280 MethList = MethList->Next) {
5281 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5282 NumSelIdents))
5283 continue;
5284
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005285 if (AtParameterName) {
5286 // Suggest parameter names we've seen before.
5287 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5288 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5289 if (Param->getIdentifier()) {
5290 CodeCompletionString *Pattern = new CodeCompletionString;
5291 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5292 Results.AddResult(Pattern);
5293 }
5294 }
5295
5296 continue;
5297 }
5298
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005299 Result R(MethList->Method, 0);
5300 R.StartParameter = NumSelIdents;
5301 R.AllParametersAreInformative = false;
5302 R.DeclaringEntity = true;
5303 Results.MaybeAddResult(R, CurContext);
5304 }
5305 }
5306
5307 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005308 HandleCodeCompleteResults(this, CodeCompleter,
5309 CodeCompletionContext::CCC_Other,
5310 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005311}
Douglas Gregor87c08a52010-08-13 22:48:40 +00005312
Douglas Gregorf29c5232010-08-24 22:20:20 +00005313void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00005314 ResultBuilder Results(*this);
5315 Results.EnterNewScope();
5316
5317 // #if <condition>
5318 CodeCompletionString *Pattern = new CodeCompletionString;
5319 Pattern->AddTypedTextChunk("if");
5320 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5321 Pattern->AddPlaceholderChunk("condition");
5322 Results.AddResult(Pattern);
5323
5324 // #ifdef <macro>
5325 Pattern = new CodeCompletionString;
5326 Pattern->AddTypedTextChunk("ifdef");
5327 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5328 Pattern->AddPlaceholderChunk("macro");
5329 Results.AddResult(Pattern);
5330
5331 // #ifndef <macro>
5332 Pattern = new CodeCompletionString;
5333 Pattern->AddTypedTextChunk("ifndef");
5334 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5335 Pattern->AddPlaceholderChunk("macro");
5336 Results.AddResult(Pattern);
5337
5338 if (InConditional) {
5339 // #elif <condition>
5340 Pattern = new CodeCompletionString;
5341 Pattern->AddTypedTextChunk("elif");
5342 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5343 Pattern->AddPlaceholderChunk("condition");
5344 Results.AddResult(Pattern);
5345
5346 // #else
5347 Pattern = new CodeCompletionString;
5348 Pattern->AddTypedTextChunk("else");
5349 Results.AddResult(Pattern);
5350
5351 // #endif
5352 Pattern = new CodeCompletionString;
5353 Pattern->AddTypedTextChunk("endif");
5354 Results.AddResult(Pattern);
5355 }
5356
5357 // #include "header"
5358 Pattern = new CodeCompletionString;
5359 Pattern->AddTypedTextChunk("include");
5360 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5361 Pattern->AddTextChunk("\"");
5362 Pattern->AddPlaceholderChunk("header");
5363 Pattern->AddTextChunk("\"");
5364 Results.AddResult(Pattern);
5365
5366 // #include <header>
5367 Pattern = new CodeCompletionString;
5368 Pattern->AddTypedTextChunk("include");
5369 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5370 Pattern->AddTextChunk("<");
5371 Pattern->AddPlaceholderChunk("header");
5372 Pattern->AddTextChunk(">");
5373 Results.AddResult(Pattern);
5374
5375 // #define <macro>
5376 Pattern = new CodeCompletionString;
5377 Pattern->AddTypedTextChunk("define");
5378 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5379 Pattern->AddPlaceholderChunk("macro");
5380 Results.AddResult(Pattern);
5381
5382 // #define <macro>(<args>)
5383 Pattern = new CodeCompletionString;
5384 Pattern->AddTypedTextChunk("define");
5385 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5386 Pattern->AddPlaceholderChunk("macro");
5387 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5388 Pattern->AddPlaceholderChunk("args");
5389 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5390 Results.AddResult(Pattern);
5391
5392 // #undef <macro>
5393 Pattern = new CodeCompletionString;
5394 Pattern->AddTypedTextChunk("undef");
5395 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5396 Pattern->AddPlaceholderChunk("macro");
5397 Results.AddResult(Pattern);
5398
5399 // #line <number>
5400 Pattern = new CodeCompletionString;
5401 Pattern->AddTypedTextChunk("line");
5402 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5403 Pattern->AddPlaceholderChunk("number");
5404 Results.AddResult(Pattern);
5405
5406 // #line <number> "filename"
5407 Pattern = new CodeCompletionString;
5408 Pattern->AddTypedTextChunk("line");
5409 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5410 Pattern->AddPlaceholderChunk("number");
5411 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5412 Pattern->AddTextChunk("\"");
5413 Pattern->AddPlaceholderChunk("filename");
5414 Pattern->AddTextChunk("\"");
5415 Results.AddResult(Pattern);
5416
5417 // #error <message>
5418 Pattern = new CodeCompletionString;
5419 Pattern->AddTypedTextChunk("error");
5420 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5421 Pattern->AddPlaceholderChunk("message");
5422 Results.AddResult(Pattern);
5423
5424 // #pragma <arguments>
5425 Pattern = new CodeCompletionString;
5426 Pattern->AddTypedTextChunk("pragma");
5427 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5428 Pattern->AddPlaceholderChunk("arguments");
5429 Results.AddResult(Pattern);
5430
5431 if (getLangOptions().ObjC1) {
5432 // #import "header"
5433 Pattern = new CodeCompletionString;
5434 Pattern->AddTypedTextChunk("import");
5435 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5436 Pattern->AddTextChunk("\"");
5437 Pattern->AddPlaceholderChunk("header");
5438 Pattern->AddTextChunk("\"");
5439 Results.AddResult(Pattern);
5440
5441 // #import <header>
5442 Pattern = new CodeCompletionString;
5443 Pattern->AddTypedTextChunk("import");
5444 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5445 Pattern->AddTextChunk("<");
5446 Pattern->AddPlaceholderChunk("header");
5447 Pattern->AddTextChunk(">");
5448 Results.AddResult(Pattern);
5449 }
5450
5451 // #include_next "header"
5452 Pattern = new CodeCompletionString;
5453 Pattern->AddTypedTextChunk("include_next");
5454 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5455 Pattern->AddTextChunk("\"");
5456 Pattern->AddPlaceholderChunk("header");
5457 Pattern->AddTextChunk("\"");
5458 Results.AddResult(Pattern);
5459
5460 // #include_next <header>
5461 Pattern = new CodeCompletionString;
5462 Pattern->AddTypedTextChunk("include_next");
5463 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5464 Pattern->AddTextChunk("<");
5465 Pattern->AddPlaceholderChunk("header");
5466 Pattern->AddTextChunk(">");
5467 Results.AddResult(Pattern);
5468
5469 // #warning <message>
5470 Pattern = new CodeCompletionString;
5471 Pattern->AddTypedTextChunk("warning");
5472 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5473 Pattern->AddPlaceholderChunk("message");
5474 Results.AddResult(Pattern);
5475
5476 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5477 // completions for them. And __include_macros is a Clang-internal extension
5478 // that we don't want to encourage anyone to use.
5479
5480 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5481 Results.ExitScope();
5482
Douglas Gregorf44e8542010-08-24 19:08:16 +00005483 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005484 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005485 Results.data(), Results.size());
5486}
5487
5488void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005489 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005490 S->getFnParent()? Sema::PCC_RecoveryInFunction
5491 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005492}
5493
Douglas Gregorf29c5232010-08-24 22:20:20 +00005494void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005495 ResultBuilder Results(*this);
5496 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5497 // Add just the names of macros, not their arguments.
5498 Results.EnterNewScope();
5499 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5500 MEnd = PP.macro_end();
5501 M != MEnd; ++M) {
5502 CodeCompletionString *Pattern = new CodeCompletionString;
5503 Pattern->AddTypedTextChunk(M->first->getName());
5504 Results.AddResult(Pattern);
5505 }
5506 Results.ExitScope();
5507 } else if (IsDefinition) {
5508 // FIXME: Can we detect when the user just wrote an include guard above?
5509 }
5510
5511 HandleCodeCompleteResults(this, CodeCompleter,
5512 IsDefinition? CodeCompletionContext::CCC_MacroName
5513 : CodeCompletionContext::CCC_MacroNameUse,
5514 Results.data(), Results.size());
5515}
5516
Douglas Gregorf29c5232010-08-24 22:20:20 +00005517void Sema::CodeCompletePreprocessorExpression() {
5518 ResultBuilder Results(*this);
5519
5520 if (!CodeCompleter || CodeCompleter->includeMacros())
5521 AddMacroResults(PP, Results);
5522
5523 // defined (<macro>)
5524 Results.EnterNewScope();
5525 CodeCompletionString *Pattern = new CodeCompletionString;
5526 Pattern->AddTypedTextChunk("defined");
5527 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5528 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5529 Pattern->AddPlaceholderChunk("macro");
5530 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5531 Results.AddResult(Pattern);
5532 Results.ExitScope();
5533
5534 HandleCodeCompleteResults(this, CodeCompleter,
5535 CodeCompletionContext::CCC_PreprocessorExpression,
5536 Results.data(), Results.size());
5537}
5538
5539void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5540 IdentifierInfo *Macro,
5541 MacroInfo *MacroInfo,
5542 unsigned Argument) {
5543 // FIXME: In the future, we could provide "overload" results, much like we
5544 // do for function calls.
5545
5546 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005547 S->getFnParent()? Sema::PCC_RecoveryInFunction
5548 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005549}
5550
Douglas Gregor55817af2010-08-25 17:04:25 +00005551void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005552 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005553 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005554 0, 0);
5555}
5556
Douglas Gregor87c08a52010-08-13 22:48:40 +00005557void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00005558 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor87c08a52010-08-13 22:48:40 +00005559 ResultBuilder Builder(*this);
5560
Douglas Gregor8071e422010-08-15 06:18:01 +00005561 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5562 CodeCompletionDeclConsumer Consumer(Builder,
5563 Context.getTranslationUnitDecl());
5564 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5565 Consumer);
5566 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005567
5568 if (!CodeCompleter || CodeCompleter->includeMacros())
5569 AddMacroResults(PP, Builder);
5570
5571 Results.clear();
5572 Results.insert(Results.end(),
5573 Builder.data(), Builder.data() + Builder.size());
5574}