blob: 64a96dbff7a42d09192d6baf86f9c36080bf71e1 [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 Gregor6f942b22010-09-21 16:06:22 +0000155 void MaybeAddConstructorResults(Result R);
156
Douglas Gregor86d9a522009-09-21 16:56:56 +0000157 public:
Douglas Gregor52779fb2010-09-23 23:01:17 +0000158 explicit ResultBuilder(Sema &SemaRef,
159 const CodeCompletionContext &CompletionContext,
160 LookupFilter Filter = 0)
Douglas Gregor3cdee122010-08-26 16:36:48 +0000161 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000162 HasObjectTypeQualifiers(false),
Douglas Gregor52779fb2010-09-23 23:01:17 +0000163 CompletionContext(CompletionContext) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164
Douglas Gregord8e8a582010-05-25 21:41:55 +0000165 /// \brief Whether we should include code patterns in the completion
166 /// results.
167 bool includeCodePatterns() const {
168 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000169 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000170 }
171
Douglas Gregor86d9a522009-09-21 16:56:56 +0000172 /// \brief Set the filter used for code-completion results.
173 void setFilter(LookupFilter Filter) {
174 this->Filter = Filter;
175 }
176
Douglas Gregor86d9a522009-09-21 16:56:56 +0000177 Result *data() { return Results.empty()? 0 : &Results.front(); }
178 unsigned size() const { return Results.size(); }
179 bool empty() const { return Results.empty(); }
180
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000181 /// \brief Specify the preferred type.
182 void setPreferredType(QualType T) {
183 PreferredType = SemaRef.Context.getCanonicalType(T);
184 }
185
Douglas Gregor3cdee122010-08-26 16:36:48 +0000186 /// \brief Set the cv-qualifiers on the object type, for us in filtering
187 /// calls to member functions.
188 ///
189 /// When there are qualifiers in this set, they will be used to filter
190 /// out member functions that aren't available (because there will be a
191 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
192 /// match.
193 void setObjectTypeQualifiers(Qualifiers Quals) {
194 ObjectTypeQualifiers = Quals;
195 HasObjectTypeQualifiers = true;
196 }
197
Douglas Gregor265f7492010-08-27 15:29:55 +0000198 /// \brief Set the preferred selector.
199 ///
200 /// When an Objective-C method declaration result is added, and that
201 /// method's selector matches this preferred selector, we give that method
202 /// a slight priority boost.
203 void setPreferredSelector(Selector Sel) {
204 PreferredSelector = Sel;
205 }
206
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000207 /// \brief Retrieve the code-completion context for which results are
208 /// being collected.
209 const CodeCompletionContext &getCompletionContext() const {
210 return CompletionContext;
211 }
212
Douglas Gregor45bcd432010-01-14 03:21:49 +0000213 /// \brief Specify whether nested-name-specifiers are allowed.
214 void allowNestedNameSpecifiers(bool Allow = true) {
215 AllowNestedNameSpecifiers = Allow;
216 }
217
Douglas Gregorb9d77572010-09-21 00:03:25 +0000218 /// \brief Return the semantic analysis object for which we are collecting
219 /// code completion results.
220 Sema &getSema() const { return SemaRef; }
221
Douglas Gregore495b7f2010-01-14 00:20:49 +0000222 /// \brief Determine whether the given declaration is at all interesting
223 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000224 ///
225 /// \param ND the declaration that we are inspecting.
226 ///
227 /// \param AsNestedNameSpecifier will be set true if this declaration is
228 /// only interesting when it is a nested-name-specifier.
229 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000230
231 /// \brief Check whether the result is hidden by the Hiding declaration.
232 ///
233 /// \returns true if the result is hidden and cannot be found, false if
234 /// the hidden result could still be found. When false, \p R may be
235 /// modified to describe how the result can be found (e.g., via extra
236 /// qualification).
237 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
238 NamedDecl *Hiding);
239
Douglas Gregor86d9a522009-09-21 16:56:56 +0000240 /// \brief Add a new result to this result set (if it isn't already in one
241 /// of the shadow maps), or replace an existing result (for, e.g., a
242 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000243 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000244 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000245 ///
246 /// \param R the context in which this result will be named.
247 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000248
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000249 /// \brief Add a new result to this result set, where we already know
250 /// the hiding declation (if any).
251 ///
252 /// \param R the result to add (if it is unique).
253 ///
254 /// \param CurContext the context in which this result will be named.
255 ///
256 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000257 ///
258 /// \param InBaseClass whether the result was found in a base
259 /// class of the searched context.
260 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
261 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000262
Douglas Gregora4477812010-01-14 16:01:26 +0000263 /// \brief Add a new non-declaration result to this result set.
264 void AddResult(Result R);
265
Douglas Gregor86d9a522009-09-21 16:56:56 +0000266 /// \brief Enter into a new scope.
267 void EnterNewScope();
268
269 /// \brief Exit from the current scope.
270 void ExitScope();
271
Douglas Gregor55385fe2009-11-18 04:19:12 +0000272 /// \brief Ignore this declaration, if it is seen again.
273 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
274
Douglas Gregor86d9a522009-09-21 16:56:56 +0000275 /// \name Name lookup predicates
276 ///
277 /// These predicates can be passed to the name lookup functions to filter the
278 /// results of name lookup. All of the predicates have the same type, so that
279 ///
280 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000281 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000282 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000283 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000284 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000285 bool IsNestedNameSpecifier(NamedDecl *ND) const;
286 bool IsEnum(NamedDecl *ND) const;
287 bool IsClassOrStruct(NamedDecl *ND) const;
288 bool IsUnion(NamedDecl *ND) const;
289 bool IsNamespace(NamedDecl *ND) const;
290 bool IsNamespaceOrAlias(NamedDecl *ND) const;
291 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000292 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000293 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000294 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000295 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000296 bool IsImpossibleToSatisfy(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 Gregor6f942b22010-09-21 16:06:22 +0000483
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000484 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
485 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
486 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000487 Filter != &ResultBuilder::IsNamespaceOrAlias &&
488 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000489 AsNestedNameSpecifier = true;
490
Douglas Gregor86d9a522009-09-21 16:56:56 +0000491 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000492 if (Filter && !(this->*Filter)(ND)) {
493 // Check whether it is interesting as a nested-name-specifier.
494 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
495 IsNestedNameSpecifier(ND) &&
496 (Filter != &ResultBuilder::IsMember ||
497 (isa<CXXRecordDecl>(ND) &&
498 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
499 AsNestedNameSpecifier = true;
500 return true;
501 }
502
Douglas Gregore495b7f2010-01-14 00:20:49 +0000503 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000504 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000505 // ... then it must be interesting!
506 return true;
507}
508
Douglas Gregor6660d842010-01-14 00:41:07 +0000509bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
510 NamedDecl *Hiding) {
511 // In C, there is no way to refer to a hidden name.
512 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
513 // name if we introduce the tag type.
514 if (!SemaRef.getLangOptions().CPlusPlus)
515 return true;
516
Sebastian Redl7a126a42010-08-31 00:36:30 +0000517 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000518
519 // There is no way to qualify a name declared in a function or method.
520 if (HiddenCtx->isFunctionOrMethod())
521 return true;
522
Sebastian Redl7a126a42010-08-31 00:36:30 +0000523 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000524 return true;
525
526 // We can refer to the result with the appropriate qualification. Do it.
527 R.Hidden = true;
528 R.QualifierIsInformative = false;
529
530 if (!R.Qualifier)
531 R.Qualifier = getRequiredQualification(SemaRef.Context,
532 CurContext,
533 R.Declaration->getDeclContext());
534 return false;
535}
536
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000537/// \brief A simplified classification of types used to determine whether two
538/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000539SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000540 switch (T->getTypeClass()) {
541 case Type::Builtin:
542 switch (cast<BuiltinType>(T)->getKind()) {
543 case BuiltinType::Void:
544 return STC_Void;
545
546 case BuiltinType::NullPtr:
547 return STC_Pointer;
548
549 case BuiltinType::Overload:
550 case BuiltinType::Dependent:
551 case BuiltinType::UndeducedAuto:
552 return STC_Other;
553
554 case BuiltinType::ObjCId:
555 case BuiltinType::ObjCClass:
556 case BuiltinType::ObjCSel:
557 return STC_ObjectiveC;
558
559 default:
560 return STC_Arithmetic;
561 }
562 return STC_Other;
563
564 case Type::Complex:
565 return STC_Arithmetic;
566
567 case Type::Pointer:
568 return STC_Pointer;
569
570 case Type::BlockPointer:
571 return STC_Block;
572
573 case Type::LValueReference:
574 case Type::RValueReference:
575 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
576
577 case Type::ConstantArray:
578 case Type::IncompleteArray:
579 case Type::VariableArray:
580 case Type::DependentSizedArray:
581 return STC_Array;
582
583 case Type::DependentSizedExtVector:
584 case Type::Vector:
585 case Type::ExtVector:
586 return STC_Arithmetic;
587
588 case Type::FunctionProto:
589 case Type::FunctionNoProto:
590 return STC_Function;
591
592 case Type::Record:
593 return STC_Record;
594
595 case Type::Enum:
596 return STC_Arithmetic;
597
598 case Type::ObjCObject:
599 case Type::ObjCInterface:
600 case Type::ObjCObjectPointer:
601 return STC_ObjectiveC;
602
603 default:
604 return STC_Other;
605 }
606}
607
608/// \brief Get the type that a given expression will have if this declaration
609/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000610QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000611 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
612
613 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
614 return C.getTypeDeclType(Type);
615 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
616 return C.getObjCInterfaceType(Iface);
617
618 QualType T;
619 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000620 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000621 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000622 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000623 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000624 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000625 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
626 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
627 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
628 T = Property->getType();
629 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
630 T = Value->getType();
631 else
632 return QualType();
633
634 return T.getNonReferenceType();
635}
636
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000637void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
638 // If this is an Objective-C method declaration whose selector matches our
639 // preferred selector, give it a priority boost.
640 if (!PreferredSelector.isNull())
641 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
642 if (PreferredSelector == Method->getSelector())
643 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000644
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000645 // If we have a preferred type, adjust the priority for results with exactly-
646 // matching or nearly-matching types.
647 if (!PreferredType.isNull()) {
648 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
649 if (!T.isNull()) {
650 CanQualType TC = SemaRef.Context.getCanonicalType(T);
651 // Check for exactly-matching types (modulo qualifiers).
652 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
653 R.Priority /= CCF_ExactTypeMatch;
654 // Check for nearly-matching types, based on classification of each.
655 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000656 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000657 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
658 R.Priority /= CCF_SimilarTypeMatch;
659 }
660 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000661}
662
Douglas Gregor6f942b22010-09-21 16:06:22 +0000663void ResultBuilder::MaybeAddConstructorResults(Result R) {
664 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
665 !CompletionContext.wantConstructorResults())
666 return;
667
668 ASTContext &Context = SemaRef.Context;
669 NamedDecl *D = R.Declaration;
670 CXXRecordDecl *Record = 0;
671 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
672 Record = ClassTemplate->getTemplatedDecl();
673 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
674 // Skip specializations and partial specializations.
675 if (isa<ClassTemplateSpecializationDecl>(Record))
676 return;
677 } else {
678 // There are no constructors here.
679 return;
680 }
681
682 Record = Record->getDefinition();
683 if (!Record)
684 return;
685
686
687 QualType RecordTy = Context.getTypeDeclType(Record);
688 DeclarationName ConstructorName
689 = Context.DeclarationNames.getCXXConstructorName(
690 Context.getCanonicalType(RecordTy));
691 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
692 Ctors.first != Ctors.second; ++Ctors.first) {
693 R.Declaration = *Ctors.first;
694 R.CursorKind = getCursorKindForDecl(R.Declaration);
695 Results.push_back(R);
696 }
697}
698
Douglas Gregore495b7f2010-01-14 00:20:49 +0000699void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
700 assert(!ShadowMaps.empty() && "Must enter into a results scope");
701
702 if (R.Kind != Result::RK_Declaration) {
703 // For non-declaration results, just add the result.
704 Results.push_back(R);
705 return;
706 }
707
708 // Look through using declarations.
709 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
710 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
711 return;
712 }
713
714 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
715 unsigned IDNS = CanonDecl->getIdentifierNamespace();
716
Douglas Gregor45bcd432010-01-14 03:21:49 +0000717 bool AsNestedNameSpecifier = false;
718 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000719 return;
720
Douglas Gregor6f942b22010-09-21 16:06:22 +0000721 // C++ constructors are never found by name lookup.
722 if (isa<CXXConstructorDecl>(R.Declaration))
723 return;
724
Douglas Gregor86d9a522009-09-21 16:56:56 +0000725 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000726 ShadowMapEntry::iterator I, IEnd;
727 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
728 if (NamePos != SMap.end()) {
729 I = NamePos->second.begin();
730 IEnd = NamePos->second.end();
731 }
732
733 for (; I != IEnd; ++I) {
734 NamedDecl *ND = I->first;
735 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000736 if (ND->getCanonicalDecl() == CanonDecl) {
737 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000738 Results[Index].Declaration = R.Declaration;
739
Douglas Gregor86d9a522009-09-21 16:56:56 +0000740 // We're done.
741 return;
742 }
743 }
744
745 // This is a new declaration in this scope. However, check whether this
746 // declaration name is hidden by a similarly-named declaration in an outer
747 // scope.
748 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
749 --SMEnd;
750 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000751 ShadowMapEntry::iterator I, IEnd;
752 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
753 if (NamePos != SM->end()) {
754 I = NamePos->second.begin();
755 IEnd = NamePos->second.end();
756 }
757 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000758 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000759 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000760 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
761 Decl::IDNS_ObjCProtocol)))
762 continue;
763
764 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000765 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000766 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000767 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000768 continue;
769
770 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000771 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000772 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000773
774 break;
775 }
776 }
777
778 // Make sure that any given declaration only shows up in the result set once.
779 if (!AllDeclsFound.insert(CanonDecl))
780 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000781
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000782 // If the filter is for nested-name-specifiers, then this result starts a
783 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000784 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000785 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000786 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000787 } else
788 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000789
Douglas Gregor0563c262009-09-22 23:15:58 +0000790 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000791 if (R.QualifierIsInformative && !R.Qualifier &&
792 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000793 DeclContext *Ctx = R.Declaration->getDeclContext();
794 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
795 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
796 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
797 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
798 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
799 else
800 R.QualifierIsInformative = false;
801 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000802
Douglas Gregor86d9a522009-09-21 16:56:56 +0000803 // Insert this result into the set of results and into the current shadow
804 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000805 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000807
808 if (!AsNestedNameSpecifier)
809 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000810}
811
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000812void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000813 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000814 if (R.Kind != Result::RK_Declaration) {
815 // For non-declaration results, just add the result.
816 Results.push_back(R);
817 return;
818 }
819
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000820 // Look through using declarations.
821 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
822 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
823 return;
824 }
825
Douglas Gregor45bcd432010-01-14 03:21:49 +0000826 bool AsNestedNameSpecifier = false;
827 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000828 return;
829
Douglas Gregor6f942b22010-09-21 16:06:22 +0000830 // C++ constructors are never found by name lookup.
831 if (isa<CXXConstructorDecl>(R.Declaration))
832 return;
833
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000834 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
835 return;
836
837 // Make sure that any given declaration only shows up in the result set once.
838 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
839 return;
840
841 // If the filter is for nested-name-specifiers, then this result starts a
842 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000843 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000844 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000845 R.Priority = CCP_NestedNameSpecifier;
846 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000847 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
848 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000849 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000850 R.QualifierIsInformative = true;
851
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000852 // If this result is supposed to have an informative qualifier, add one.
853 if (R.QualifierIsInformative && !R.Qualifier &&
854 !R.StartsNestedNameSpecifier) {
855 DeclContext *Ctx = R.Declaration->getDeclContext();
856 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
857 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
858 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
859 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000860 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000861 else
862 R.QualifierIsInformative = false;
863 }
864
Douglas Gregor12e13132010-05-26 22:00:08 +0000865 // Adjust the priority if this result comes from a base class.
866 if (InBaseClass)
867 R.Priority += CCD_InBaseClass;
868
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000869 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000870
Douglas Gregor3cdee122010-08-26 16:36:48 +0000871 if (HasObjectTypeQualifiers)
872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
873 if (Method->isInstance()) {
874 Qualifiers MethodQuals
875 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
876 if (ObjectTypeQualifiers == MethodQuals)
877 R.Priority += CCD_ObjectQualifierMatch;
878 else if (ObjectTypeQualifiers - MethodQuals) {
879 // The method cannot be invoked, because doing so would drop
880 // qualifiers.
881 return;
882 }
883 }
884
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000885 // Insert this result into the set of results.
886 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000887
888 if (!AsNestedNameSpecifier)
889 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000890}
891
Douglas Gregora4477812010-01-14 16:01:26 +0000892void ResultBuilder::AddResult(Result R) {
893 assert(R.Kind != Result::RK_Declaration &&
894 "Declaration results need more context");
895 Results.push_back(R);
896}
897
Douglas Gregor86d9a522009-09-21 16:56:56 +0000898/// \brief Enter into a new scope.
899void ResultBuilder::EnterNewScope() {
900 ShadowMaps.push_back(ShadowMap());
901}
902
903/// \brief Exit from the current scope.
904void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000905 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
906 EEnd = ShadowMaps.back().end();
907 E != EEnd;
908 ++E)
909 E->second.Destroy();
910
Douglas Gregor86d9a522009-09-21 16:56:56 +0000911 ShadowMaps.pop_back();
912}
913
Douglas Gregor791215b2009-09-21 20:51:25 +0000914/// \brief Determines whether this given declaration will be found by
915/// ordinary name lookup.
916bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000917 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
918
Douglas Gregor791215b2009-09-21 20:51:25 +0000919 unsigned IDNS = Decl::IDNS_Ordinary;
920 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000921 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000922 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
923 return true;
924
Douglas Gregor791215b2009-09-21 20:51:25 +0000925 return ND->getIdentifierNamespace() & IDNS;
926}
927
Douglas Gregor01dfea02010-01-10 23:08:15 +0000928/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000929/// ordinary name lookup but is not a type name.
930bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
931 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
932 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
933 return false;
934
935 unsigned IDNS = Decl::IDNS_Ordinary;
936 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000937 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000938 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
939 return true;
940
941 return ND->getIdentifierNamespace() & IDNS;
942}
943
Douglas Gregorf9578432010-07-28 21:50:18 +0000944bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
945 if (!IsOrdinaryNonTypeName(ND))
946 return 0;
947
948 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
949 if (VD->getType()->isIntegralOrEnumerationType())
950 return true;
951
952 return false;
953}
954
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000955/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000956/// ordinary name lookup.
957bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000958 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
959
Douglas Gregor01dfea02010-01-10 23:08:15 +0000960 unsigned IDNS = Decl::IDNS_Ordinary;
961 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000962 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000963
964 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000965 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
966 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000967}
968
Douglas Gregor86d9a522009-09-21 16:56:56 +0000969/// \brief Determines whether the given declaration is suitable as the
970/// start of a C++ nested-name-specifier, e.g., a class or namespace.
971bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
972 // Allow us to find class templates, too.
973 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
974 ND = ClassTemplate->getTemplatedDecl();
975
976 return SemaRef.isAcceptableNestedNameSpecifier(ND);
977}
978
979/// \brief Determines whether the given declaration is an enumeration.
980bool ResultBuilder::IsEnum(NamedDecl *ND) const {
981 return isa<EnumDecl>(ND);
982}
983
984/// \brief Determines whether the given declaration is a class or struct.
985bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
986 // Allow us to find class templates, too.
987 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
988 ND = ClassTemplate->getTemplatedDecl();
989
990 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000991 return RD->getTagKind() == TTK_Class ||
992 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000993
994 return false;
995}
996
997/// \brief Determines whether the given declaration is a union.
998bool ResultBuilder::IsUnion(NamedDecl *ND) const {
999 // Allow us to find class templates, too.
1000 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1001 ND = ClassTemplate->getTemplatedDecl();
1002
1003 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001004 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001005
1006 return false;
1007}
1008
1009/// \brief Determines whether the given declaration is a namespace.
1010bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1011 return isa<NamespaceDecl>(ND);
1012}
1013
1014/// \brief Determines whether the given declaration is a namespace or
1015/// namespace alias.
1016bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1017 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1018}
1019
Douglas Gregor76282942009-12-11 17:31:05 +00001020/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001021bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001022 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1023 ND = Using->getTargetDecl();
1024
1025 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001026}
1027
Douglas Gregor76282942009-12-11 17:31:05 +00001028/// \brief Determines which members of a class should be visible via
1029/// "." or "->". Only value declarations, nested name specifiers, and
1030/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001031bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001032 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1033 ND = Using->getTargetDecl();
1034
Douglas Gregorce821962009-12-11 18:14:22 +00001035 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1036 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001037}
1038
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001039static bool isObjCReceiverType(ASTContext &C, QualType T) {
1040 T = C.getCanonicalType(T);
1041 switch (T->getTypeClass()) {
1042 case Type::ObjCObject:
1043 case Type::ObjCInterface:
1044 case Type::ObjCObjectPointer:
1045 return true;
1046
1047 case Type::Builtin:
1048 switch (cast<BuiltinType>(T)->getKind()) {
1049 case BuiltinType::ObjCId:
1050 case BuiltinType::ObjCClass:
1051 case BuiltinType::ObjCSel:
1052 return true;
1053
1054 default:
1055 break;
1056 }
1057 return false;
1058
1059 default:
1060 break;
1061 }
1062
1063 if (!C.getLangOptions().CPlusPlus)
1064 return false;
1065
1066 // FIXME: We could perform more analysis here to determine whether a
1067 // particular class type has any conversions to Objective-C types. For now,
1068 // just accept all class types.
1069 return T->isDependentType() || T->isRecordType();
1070}
1071
1072bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1073 QualType T = getDeclUsageType(SemaRef.Context, ND);
1074 if (T.isNull())
1075 return false;
1076
1077 T = SemaRef.Context.getBaseElementType(T);
1078 return isObjCReceiverType(SemaRef.Context, T);
1079}
1080
Douglas Gregorfb629412010-08-23 21:17:50 +00001081bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1082 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1083 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1084 return false;
1085
1086 QualType T = getDeclUsageType(SemaRef.Context, ND);
1087 if (T.isNull())
1088 return false;
1089
1090 T = SemaRef.Context.getBaseElementType(T);
1091 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1092 T->isObjCIdType() ||
1093 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1094}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001095
Douglas Gregor52779fb2010-09-23 23:01:17 +00001096bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1097 return false;
1098}
1099
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001100/// \rief Determines whether the given declaration is an Objective-C
1101/// instance variable.
1102bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1103 return isa<ObjCIvarDecl>(ND);
1104}
1105
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001106namespace {
1107 /// \brief Visible declaration consumer that adds a code-completion result
1108 /// for each visible declaration.
1109 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1110 ResultBuilder &Results;
1111 DeclContext *CurContext;
1112
1113 public:
1114 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1115 : Results(Results), CurContext(CurContext) { }
1116
Douglas Gregor0cc84042010-01-14 15:47:35 +00001117 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1118 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001119 }
1120 };
1121}
1122
Douglas Gregor86d9a522009-09-21 16:56:56 +00001123/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001124static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001125 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001126 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001127 Results.AddResult(Result("short", CCP_Type));
1128 Results.AddResult(Result("long", CCP_Type));
1129 Results.AddResult(Result("signed", CCP_Type));
1130 Results.AddResult(Result("unsigned", CCP_Type));
1131 Results.AddResult(Result("void", CCP_Type));
1132 Results.AddResult(Result("char", CCP_Type));
1133 Results.AddResult(Result("int", CCP_Type));
1134 Results.AddResult(Result("float", CCP_Type));
1135 Results.AddResult(Result("double", CCP_Type));
1136 Results.AddResult(Result("enum", CCP_Type));
1137 Results.AddResult(Result("struct", CCP_Type));
1138 Results.AddResult(Result("union", CCP_Type));
1139 Results.AddResult(Result("const", CCP_Type));
1140 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001141
Douglas Gregor86d9a522009-09-21 16:56:56 +00001142 if (LangOpts.C99) {
1143 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001144 Results.AddResult(Result("_Complex", CCP_Type));
1145 Results.AddResult(Result("_Imaginary", CCP_Type));
1146 Results.AddResult(Result("_Bool", CCP_Type));
1147 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001148 }
1149
1150 if (LangOpts.CPlusPlus) {
1151 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001152 Results.AddResult(Result("bool", CCP_Type +
1153 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001154 Results.AddResult(Result("class", CCP_Type));
1155 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001156
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001157 // typename qualified-id
1158 CodeCompletionString *Pattern = new CodeCompletionString;
1159 Pattern->AddTypedTextChunk("typename");
1160 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1161 Pattern->AddPlaceholderChunk("qualifier");
1162 Pattern->AddTextChunk("::");
1163 Pattern->AddPlaceholderChunk("name");
1164 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001165
Douglas Gregor86d9a522009-09-21 16:56:56 +00001166 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001167 Results.AddResult(Result("auto", CCP_Type));
1168 Results.AddResult(Result("char16_t", CCP_Type));
1169 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001170
1171 CodeCompletionString *Pattern = new CodeCompletionString;
1172 Pattern->AddTypedTextChunk("decltype");
1173 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1174 Pattern->AddPlaceholderChunk("expression");
1175 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1176 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001177 }
1178 }
1179
1180 // GNU extensions
1181 if (LangOpts.GNUMode) {
1182 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001183 // Results.AddResult(Result("_Decimal32"));
1184 // Results.AddResult(Result("_Decimal64"));
1185 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001186
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001187 CodeCompletionString *Pattern = new CodeCompletionString;
1188 Pattern->AddTypedTextChunk("typeof");
1189 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1190 Pattern->AddPlaceholderChunk("expression");
1191 Results.AddResult(Result(Pattern));
1192
1193 Pattern = new CodeCompletionString;
1194 Pattern->AddTypedTextChunk("typeof");
1195 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1196 Pattern->AddPlaceholderChunk("type");
1197 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1198 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001199 }
1200}
1201
John McCallf312b1e2010-08-26 23:41:50 +00001202static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001203 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001204 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001205 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001206 // Note: we don't suggest either "auto" or "register", because both
1207 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1208 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001209 Results.AddResult(Result("extern"));
1210 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001211}
1212
John McCallf312b1e2010-08-26 23:41:50 +00001213static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001214 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001215 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001216 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001217 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001218 case Sema::PCC_Class:
1219 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001220 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001221 Results.AddResult(Result("explicit"));
1222 Results.AddResult(Result("friend"));
1223 Results.AddResult(Result("mutable"));
1224 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001225 }
1226 // Fall through
1227
John McCallf312b1e2010-08-26 23:41:50 +00001228 case Sema::PCC_ObjCInterface:
1229 case Sema::PCC_ObjCImplementation:
1230 case Sema::PCC_Namespace:
1231 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001232 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001233 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001234 break;
1235
John McCallf312b1e2010-08-26 23:41:50 +00001236 case Sema::PCC_ObjCInstanceVariableList:
1237 case Sema::PCC_Expression:
1238 case Sema::PCC_Statement:
1239 case Sema::PCC_ForInit:
1240 case Sema::PCC_Condition:
1241 case Sema::PCC_RecoveryInFunction:
1242 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001243 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001244 break;
1245 }
1246}
1247
Douglas Gregorbca403c2010-01-13 23:51:12 +00001248static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1249static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1250static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001251 ResultBuilder &Results,
1252 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001253static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001254 ResultBuilder &Results,
1255 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001256static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001257 ResultBuilder &Results,
1258 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001259static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001260
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001261static void AddTypedefResult(ResultBuilder &Results) {
1262 CodeCompletionString *Pattern = new CodeCompletionString;
1263 Pattern->AddTypedTextChunk("typedef");
1264 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1265 Pattern->AddPlaceholderChunk("type");
1266 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1267 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001268 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001269}
1270
John McCallf312b1e2010-08-26 23:41:50 +00001271static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001272 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001273 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001274 case Sema::PCC_Namespace:
1275 case Sema::PCC_Class:
1276 case Sema::PCC_ObjCInstanceVariableList:
1277 case Sema::PCC_Template:
1278 case Sema::PCC_MemberTemplate:
1279 case Sema::PCC_Statement:
1280 case Sema::PCC_RecoveryInFunction:
1281 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001282 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001283 return true;
1284
John McCallf312b1e2010-08-26 23:41:50 +00001285 case Sema::PCC_Expression:
1286 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001287 return LangOpts.CPlusPlus;
1288
1289 case Sema::PCC_ObjCInterface:
1290 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001291 return false;
1292
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001294 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001295 }
1296
1297 return false;
1298}
1299
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001301static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001302 Scope *S,
1303 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001304 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001305 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001306 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001307 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001308 if (SemaRef.getLangOptions().CPlusPlus) {
1309 CodeCompletionString *Pattern = 0;
1310
1311 if (Results.includeCodePatterns()) {
1312 // namespace <identifier> { declarations }
1313 CodeCompletionString *Pattern = new CodeCompletionString;
1314 Pattern->AddTypedTextChunk("namespace");
1315 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1316 Pattern->AddPlaceholderChunk("identifier");
1317 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1318 Pattern->AddPlaceholderChunk("declarations");
1319 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1320 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1321 Results.AddResult(Result(Pattern));
1322 }
1323
Douglas Gregor01dfea02010-01-10 23:08:15 +00001324 // namespace identifier = identifier ;
1325 Pattern = new CodeCompletionString;
1326 Pattern->AddTypedTextChunk("namespace");
1327 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001328 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001329 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001330 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001331 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001332
1333 // Using directives
1334 Pattern = new CodeCompletionString;
1335 Pattern->AddTypedTextChunk("using");
1336 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1337 Pattern->AddTextChunk("namespace");
1338 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1339 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001340 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001341
1342 // asm(string-literal)
1343 Pattern = new CodeCompletionString;
1344 Pattern->AddTypedTextChunk("asm");
1345 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1346 Pattern->AddPlaceholderChunk("string-literal");
1347 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001348 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001349
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001350 if (Results.includeCodePatterns()) {
1351 // Explicit template instantiation
1352 Pattern = new CodeCompletionString;
1353 Pattern->AddTypedTextChunk("template");
1354 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1355 Pattern->AddPlaceholderChunk("declaration");
1356 Results.AddResult(Result(Pattern));
1357 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001358 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001359
1360 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001361 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001362
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001363 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001364 // Fall through
1365
John McCallf312b1e2010-08-26 23:41:50 +00001366 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001367 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001368 // Using declaration
1369 CodeCompletionString *Pattern = new CodeCompletionString;
1370 Pattern->AddTypedTextChunk("using");
1371 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001372 Pattern->AddPlaceholderChunk("qualifier");
1373 Pattern->AddTextChunk("::");
1374 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001375 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001376
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001377 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001378 if (SemaRef.CurContext->isDependentContext()) {
1379 Pattern = new CodeCompletionString;
1380 Pattern->AddTypedTextChunk("using");
1381 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1382 Pattern->AddTextChunk("typename");
1383 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001384 Pattern->AddPlaceholderChunk("qualifier");
1385 Pattern->AddTextChunk("::");
1386 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001387 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001388 }
1389
John McCallf312b1e2010-08-26 23:41:50 +00001390 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001391 AddTypedefResult(Results);
1392
Douglas Gregor01dfea02010-01-10 23:08:15 +00001393 // public:
1394 Pattern = new CodeCompletionString;
1395 Pattern->AddTypedTextChunk("public");
1396 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001397 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001398
1399 // protected:
1400 Pattern = new CodeCompletionString;
1401 Pattern->AddTypedTextChunk("protected");
1402 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001403 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001404
1405 // private:
1406 Pattern = new CodeCompletionString;
1407 Pattern->AddTypedTextChunk("private");
1408 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001409 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001410 }
1411 }
1412 // Fall through
1413
John McCallf312b1e2010-08-26 23:41:50 +00001414 case Sema::PCC_Template:
1415 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001416 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001417 // template < parameters >
1418 CodeCompletionString *Pattern = new CodeCompletionString;
1419 Pattern->AddTypedTextChunk("template");
1420 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1421 Pattern->AddPlaceholderChunk("parameters");
1422 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001423 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424 }
1425
Douglas Gregorbca403c2010-01-13 23:51:12 +00001426 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1427 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001428 break;
1429
John McCallf312b1e2010-08-26 23:41:50 +00001430 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001431 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1432 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1433 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001434 break;
1435
John McCallf312b1e2010-08-26 23:41:50 +00001436 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001437 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1438 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1439 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001440 break;
1441
John McCallf312b1e2010-08-26 23:41:50 +00001442 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001443 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001444 break;
1445
John McCallf312b1e2010-08-26 23:41:50 +00001446 case Sema::PCC_RecoveryInFunction:
1447 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001448 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449
1450 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001451 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001452 Pattern = new CodeCompletionString;
1453 Pattern->AddTypedTextChunk("try");
1454 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1455 Pattern->AddPlaceholderChunk("statements");
1456 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1457 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1458 Pattern->AddTextChunk("catch");
1459 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1460 Pattern->AddPlaceholderChunk("declaration");
1461 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1462 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1463 Pattern->AddPlaceholderChunk("statements");
1464 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1465 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001466 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001468 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001469 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001470
Douglas Gregord8e8a582010-05-25 21:41:55 +00001471 if (Results.includeCodePatterns()) {
1472 // if (condition) { statements }
1473 Pattern = new CodeCompletionString;
1474 Pattern->AddTypedTextChunk("if");
1475 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1476 if (SemaRef.getLangOptions().CPlusPlus)
1477 Pattern->AddPlaceholderChunk("condition");
1478 else
1479 Pattern->AddPlaceholderChunk("expression");
1480 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1481 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1482 Pattern->AddPlaceholderChunk("statements");
1483 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1484 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1485 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486
Douglas Gregord8e8a582010-05-25 21:41:55 +00001487 // switch (condition) { }
1488 Pattern = new CodeCompletionString;
1489 Pattern->AddTypedTextChunk("switch");
1490 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1491 if (SemaRef.getLangOptions().CPlusPlus)
1492 Pattern->AddPlaceholderChunk("condition");
1493 else
1494 Pattern->AddPlaceholderChunk("expression");
1495 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1496 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1497 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1498 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1499 Results.AddResult(Result(Pattern));
1500 }
1501
Douglas Gregor01dfea02010-01-10 23:08:15 +00001502 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001503 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001504 // case expression:
1505 Pattern = new CodeCompletionString;
1506 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001507 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001508 Pattern->AddPlaceholderChunk("expression");
1509 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001510 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001511
1512 // default:
1513 Pattern = new CodeCompletionString;
1514 Pattern->AddTypedTextChunk("default");
1515 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001516 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001517 }
1518
Douglas Gregord8e8a582010-05-25 21:41:55 +00001519 if (Results.includeCodePatterns()) {
1520 /// while (condition) { statements }
1521 Pattern = new CodeCompletionString;
1522 Pattern->AddTypedTextChunk("while");
1523 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1524 if (SemaRef.getLangOptions().CPlusPlus)
1525 Pattern->AddPlaceholderChunk("condition");
1526 else
1527 Pattern->AddPlaceholderChunk("expression");
1528 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1529 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1530 Pattern->AddPlaceholderChunk("statements");
1531 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1532 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1533 Results.AddResult(Result(Pattern));
1534
1535 // do { statements } while ( expression );
1536 Pattern = new CodeCompletionString;
1537 Pattern->AddTypedTextChunk("do");
1538 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1539 Pattern->AddPlaceholderChunk("statements");
1540 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1541 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1542 Pattern->AddTextChunk("while");
1543 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001544 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001545 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1546 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001547
Douglas Gregord8e8a582010-05-25 21:41:55 +00001548 // for ( for-init-statement ; condition ; expression ) { statements }
1549 Pattern = new CodeCompletionString;
1550 Pattern->AddTypedTextChunk("for");
1551 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1552 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1553 Pattern->AddPlaceholderChunk("init-statement");
1554 else
1555 Pattern->AddPlaceholderChunk("init-expression");
1556 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1557 Pattern->AddPlaceholderChunk("condition");
1558 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1559 Pattern->AddPlaceholderChunk("inc-expression");
1560 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1561 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1562 Pattern->AddPlaceholderChunk("statements");
1563 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1564 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1565 Results.AddResult(Result(Pattern));
1566 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567
1568 if (S->getContinueParent()) {
1569 // continue ;
1570 Pattern = new CodeCompletionString;
1571 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001572 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573 }
1574
1575 if (S->getBreakParent()) {
1576 // break ;
1577 Pattern = new CodeCompletionString;
1578 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001579 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001580 }
1581
1582 // "return expression ;" or "return ;", depending on whether we
1583 // know the function is void or not.
1584 bool isVoid = false;
1585 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1586 isVoid = Function->getResultType()->isVoidType();
1587 else if (ObjCMethodDecl *Method
1588 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1589 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001590 else if (SemaRef.getCurBlock() &&
1591 !SemaRef.getCurBlock()->ReturnType.isNull())
1592 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001593 Pattern = new CodeCompletionString;
1594 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001595 if (!isVoid) {
1596 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001597 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001598 }
Douglas Gregora4477812010-01-14 16:01:26 +00001599 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001600
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001601 // goto identifier ;
1602 Pattern = new CodeCompletionString;
1603 Pattern->AddTypedTextChunk("goto");
1604 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1605 Pattern->AddPlaceholderChunk("label");
1606 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001607
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001608 // Using directives
1609 Pattern = new CodeCompletionString;
1610 Pattern->AddTypedTextChunk("using");
1611 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1612 Pattern->AddTextChunk("namespace");
1613 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1614 Pattern->AddPlaceholderChunk("identifier");
1615 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001616 }
1617
1618 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001619 case Sema::PCC_ForInit:
1620 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001621 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001622 // Fall through: conditions and statements can have expressions.
1623
Douglas Gregor02688102010-09-14 23:59:36 +00001624 case Sema::PCC_ParenthesizedExpression:
John McCallf312b1e2010-08-26 23:41:50 +00001625 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626 CodeCompletionString *Pattern = 0;
1627 if (SemaRef.getLangOptions().CPlusPlus) {
1628 // 'this', if we're in a non-static member function.
1629 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1630 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001631 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001632
1633 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001634 Results.AddResult(Result("true"));
1635 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001636
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001637 // dynamic_cast < type-id > ( expression )
1638 Pattern = new CodeCompletionString;
1639 Pattern->AddTypedTextChunk("dynamic_cast");
1640 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1641 Pattern->AddPlaceholderChunk("type");
1642 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1643 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1644 Pattern->AddPlaceholderChunk("expression");
1645 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1646 Results.AddResult(Result(Pattern));
1647
1648 // static_cast < type-id > ( expression )
1649 Pattern = new CodeCompletionString;
1650 Pattern->AddTypedTextChunk("static_cast");
1651 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1652 Pattern->AddPlaceholderChunk("type");
1653 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1654 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1655 Pattern->AddPlaceholderChunk("expression");
1656 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1657 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001658
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001659 // reinterpret_cast < type-id > ( expression )
1660 Pattern = new CodeCompletionString;
1661 Pattern->AddTypedTextChunk("reinterpret_cast");
1662 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1663 Pattern->AddPlaceholderChunk("type");
1664 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1665 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1666 Pattern->AddPlaceholderChunk("expression");
1667 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1668 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001669
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001670 // const_cast < type-id > ( expression )
1671 Pattern = new CodeCompletionString;
1672 Pattern->AddTypedTextChunk("const_cast");
1673 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1674 Pattern->AddPlaceholderChunk("type");
1675 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1676 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1677 Pattern->AddPlaceholderChunk("expression");
1678 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1679 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001680
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001681 // typeid ( expression-or-type )
1682 Pattern = new CodeCompletionString;
1683 Pattern->AddTypedTextChunk("typeid");
1684 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1685 Pattern->AddPlaceholderChunk("expression-or-type");
1686 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1687 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001688
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001689 // new T ( ... )
1690 Pattern = new CodeCompletionString;
1691 Pattern->AddTypedTextChunk("new");
1692 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1693 Pattern->AddPlaceholderChunk("type");
1694 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1695 Pattern->AddPlaceholderChunk("expressions");
1696 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1697 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001698
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001699 // new T [ ] ( ... )
1700 Pattern = new CodeCompletionString;
1701 Pattern->AddTypedTextChunk("new");
1702 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1703 Pattern->AddPlaceholderChunk("type");
1704 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1705 Pattern->AddPlaceholderChunk("size");
1706 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1707 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1708 Pattern->AddPlaceholderChunk("expressions");
1709 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1710 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001711
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001712 // delete expression
1713 Pattern = new CodeCompletionString;
1714 Pattern->AddTypedTextChunk("delete");
1715 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1716 Pattern->AddPlaceholderChunk("expression");
1717 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001718
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001719 // delete [] expression
1720 Pattern = new CodeCompletionString;
1721 Pattern->AddTypedTextChunk("delete");
1722 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1723 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1724 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1725 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1726 Pattern->AddPlaceholderChunk("expression");
1727 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001728
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001729 // throw expression
1730 Pattern = new CodeCompletionString;
1731 Pattern->AddTypedTextChunk("throw");
1732 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1733 Pattern->AddPlaceholderChunk("expression");
1734 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001735
1736 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001737 }
1738
1739 if (SemaRef.getLangOptions().ObjC1) {
1740 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001741 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1742 // The interface can be NULL.
1743 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1744 if (ID->getSuperClass())
1745 Results.AddResult(Result("super"));
1746 }
1747
Douglas Gregorbca403c2010-01-13 23:51:12 +00001748 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749 }
1750
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001751 // sizeof expression
1752 Pattern = new CodeCompletionString;
1753 Pattern->AddTypedTextChunk("sizeof");
1754 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1755 Pattern->AddPlaceholderChunk("expression-or-type");
1756 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1757 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001758 break;
1759 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001760
John McCallf312b1e2010-08-26 23:41:50 +00001761 case Sema::PCC_Type:
Douglas Gregord32b0222010-08-24 01:06:58 +00001762 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001763 }
1764
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001765 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1766 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001767
John McCallf312b1e2010-08-26 23:41:50 +00001768 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001769 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001770}
1771
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001772/// \brief If the given declaration has an associated type, add it as a result
1773/// type chunk.
1774static void AddResultTypeChunk(ASTContext &Context,
1775 NamedDecl *ND,
1776 CodeCompletionString *Result) {
1777 if (!ND)
1778 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001779
1780 // Skip constructors and conversion functions, which have their return types
1781 // built into their names.
1782 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1783 return;
1784
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001785 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001786 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001787 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1788 T = Function->getResultType();
1789 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1790 T = Method->getResultType();
1791 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1792 T = FunTmpl->getTemplatedDecl()->getResultType();
1793 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1794 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1795 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1796 /* Do nothing: ignore unresolved using declarations*/
1797 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1798 T = Value->getType();
1799 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1800 T = Property->getType();
1801
1802 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1803 return;
1804
Douglas Gregor84139d62010-04-05 21:25:31 +00001805 PrintingPolicy Policy(Context.PrintingPolicy);
1806 Policy.AnonymousTagLocations = false;
1807
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001808 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001809 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001810 Result->AddResultTypeChunk(TypeStr);
1811}
1812
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001813static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1814 CodeCompletionString *Result) {
1815 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1816 if (Sentinel->getSentinel() == 0) {
1817 if (Context.getLangOptions().ObjC1 &&
1818 Context.Idents.get("nil").hasMacroDefinition())
1819 Result->AddTextChunk(", nil");
1820 else if (Context.Idents.get("NULL").hasMacroDefinition())
1821 Result->AddTextChunk(", NULL");
1822 else
1823 Result->AddTextChunk(", (void*)0");
1824 }
1825}
1826
Douglas Gregor83482d12010-08-24 16:15:59 +00001827static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001828 ParmVarDecl *Param,
1829 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001830 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1831 if (Param->getType()->isDependentType() ||
1832 !Param->getType()->isBlockPointerType()) {
1833 // The argument for a dependent or non-block parameter is a placeholder
1834 // containing that parameter's type.
1835 std::string Result;
1836
Douglas Gregoraba48082010-08-29 19:47:46 +00001837 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001838 Result = Param->getIdentifier()->getName();
1839
1840 Param->getType().getAsStringInternal(Result,
1841 Context.PrintingPolicy);
1842
1843 if (ObjCMethodParam) {
1844 Result = "(" + Result;
1845 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001846 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001847 Result += Param->getIdentifier()->getName();
1848 }
1849 return Result;
1850 }
1851
1852 // The argument for a block pointer parameter is a block literal with
1853 // the appropriate type.
1854 FunctionProtoTypeLoc *Block = 0;
1855 TypeLoc TL;
1856 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1857 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1858 while (true) {
1859 // Look through typedefs.
1860 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1861 if (TypeSourceInfo *InnerTSInfo
1862 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1863 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1864 continue;
1865 }
1866 }
1867
1868 // Look through qualified types
1869 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1870 TL = QualifiedTL->getUnqualifiedLoc();
1871 continue;
1872 }
1873
1874 // Try to get the function prototype behind the block pointer type,
1875 // then we're done.
1876 if (BlockPointerTypeLoc *BlockPtr
1877 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1878 TL = BlockPtr->getPointeeLoc();
1879 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1880 }
1881 break;
1882 }
1883 }
1884
1885 if (!Block) {
1886 // We were unable to find a FunctionProtoTypeLoc with parameter names
1887 // for the block; just use the parameter type as a placeholder.
1888 std::string Result;
1889 Param->getType().getUnqualifiedType().
1890 getAsStringInternal(Result, Context.PrintingPolicy);
1891
1892 if (ObjCMethodParam) {
1893 Result = "(" + Result;
1894 Result += ")";
1895 if (Param->getIdentifier())
1896 Result += Param->getIdentifier()->getName();
1897 }
1898
1899 return Result;
1900 }
1901
1902 // We have the function prototype behind the block pointer type, as it was
1903 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001904 std::string Result;
1905 QualType ResultType = Block->getTypePtr()->getResultType();
1906 if (!ResultType->isVoidType())
1907 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1908
1909 Result = '^' + Result;
1910 if (Block->getNumArgs() == 0) {
1911 if (Block->getTypePtr()->isVariadic())
1912 Result += "(...)";
1913 } else {
1914 Result += "(";
1915 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1916 if (I)
1917 Result += ", ";
1918 Result += FormatFunctionParameter(Context, Block->getArg(I));
1919
1920 if (I == N - 1 && Block->getTypePtr()->isVariadic())
1921 Result += ", ...";
1922 }
1923 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00001924 }
Douglas Gregor38276252010-09-08 22:47:51 +00001925
Douglas Gregor83482d12010-08-24 16:15:59 +00001926 return Result;
1927}
1928
Douglas Gregor86d9a522009-09-21 16:56:56 +00001929/// \brief Add function parameter chunks to the given code completion string.
1930static void AddFunctionParameterChunks(ASTContext &Context,
1931 FunctionDecl *Function,
1932 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001933 typedef CodeCompletionString::Chunk Chunk;
1934
Douglas Gregor86d9a522009-09-21 16:56:56 +00001935 CodeCompletionString *CCStr = Result;
1936
1937 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1938 ParmVarDecl *Param = Function->getParamDecl(P);
1939
1940 if (Param->hasDefaultArg()) {
1941 // When we see an optional default argument, put that argument and
1942 // the remaining default arguments into a new, optional string.
1943 CodeCompletionString *Opt = new CodeCompletionString;
1944 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1945 CCStr = Opt;
1946 }
1947
1948 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001949 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001950
1951 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001952 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1953
Douglas Gregore17794f2010-08-31 05:13:43 +00001954 if (Function->isVariadic() && P == N - 1)
1955 PlaceholderStr += ", ...";
1956
Douglas Gregor86d9a522009-09-21 16:56:56 +00001957 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001958 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001959 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001960
1961 if (const FunctionProtoType *Proto
1962 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001963 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00001964 if (Proto->getNumArgs() == 0)
1965 CCStr->AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001966
1967 MaybeAddSentinel(Context, Function, CCStr);
1968 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001969}
1970
1971/// \brief Add template parameter chunks to the given code completion string.
1972static void AddTemplateParameterChunks(ASTContext &Context,
1973 TemplateDecl *Template,
1974 CodeCompletionString *Result,
1975 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001976 typedef CodeCompletionString::Chunk Chunk;
1977
Douglas Gregor86d9a522009-09-21 16:56:56 +00001978 CodeCompletionString *CCStr = Result;
1979 bool FirstParameter = true;
1980
1981 TemplateParameterList *Params = Template->getTemplateParameters();
1982 TemplateParameterList::iterator PEnd = Params->end();
1983 if (MaxParameters)
1984 PEnd = Params->begin() + MaxParameters;
1985 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1986 bool HasDefaultArg = false;
1987 std::string PlaceholderStr;
1988 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1989 if (TTP->wasDeclaredWithTypename())
1990 PlaceholderStr = "typename";
1991 else
1992 PlaceholderStr = "class";
1993
1994 if (TTP->getIdentifier()) {
1995 PlaceholderStr += ' ';
1996 PlaceholderStr += TTP->getIdentifier()->getName();
1997 }
1998
1999 HasDefaultArg = TTP->hasDefaultArgument();
2000 } else if (NonTypeTemplateParmDecl *NTTP
2001 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2002 if (NTTP->getIdentifier())
2003 PlaceholderStr = NTTP->getIdentifier()->getName();
2004 NTTP->getType().getAsStringInternal(PlaceholderStr,
2005 Context.PrintingPolicy);
2006 HasDefaultArg = NTTP->hasDefaultArgument();
2007 } else {
2008 assert(isa<TemplateTemplateParmDecl>(*P));
2009 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2010
2011 // Since putting the template argument list into the placeholder would
2012 // be very, very long, we just use an abbreviation.
2013 PlaceholderStr = "template<...> class";
2014 if (TTP->getIdentifier()) {
2015 PlaceholderStr += ' ';
2016 PlaceholderStr += TTP->getIdentifier()->getName();
2017 }
2018
2019 HasDefaultArg = TTP->hasDefaultArgument();
2020 }
2021
2022 if (HasDefaultArg) {
2023 // When we see an optional default argument, put that argument and
2024 // the remaining default arguments into a new, optional string.
2025 CodeCompletionString *Opt = new CodeCompletionString;
2026 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
2027 CCStr = Opt;
2028 }
2029
2030 if (FirstParameter)
2031 FirstParameter = false;
2032 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002033 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002034
2035 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002036 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002037 }
2038}
2039
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002040/// \brief Add a qualifier to the given code-completion string, if the
2041/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002042static void
2043AddQualifierToCompletionString(CodeCompletionString *Result,
2044 NestedNameSpecifier *Qualifier,
2045 bool QualifierIsInformative,
2046 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002047 if (!Qualifier)
2048 return;
2049
2050 std::string PrintedNNS;
2051 {
2052 llvm::raw_string_ostream OS(PrintedNNS);
2053 Qualifier->print(OS, Context.PrintingPolicy);
2054 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002055 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002056 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00002057 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002058 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002059}
2060
Douglas Gregora61a8792009-12-11 18:44:16 +00002061static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
2062 FunctionDecl *Function) {
2063 const FunctionProtoType *Proto
2064 = Function->getType()->getAs<FunctionProtoType>();
2065 if (!Proto || !Proto->getTypeQuals())
2066 return;
2067
2068 std::string QualsStr;
2069 if (Proto->getTypeQuals() & Qualifiers::Const)
2070 QualsStr += " const";
2071 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2072 QualsStr += " volatile";
2073 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2074 QualsStr += " restrict";
2075 Result->AddInformativeChunk(QualsStr);
2076}
2077
Douglas Gregor6f942b22010-09-21 16:06:22 +00002078/// \brief Add the name of the given declaration
2079static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
2080 CodeCompletionString *Result) {
2081 typedef CodeCompletionString::Chunk Chunk;
2082
2083 DeclarationName Name = ND->getDeclName();
2084 if (!Name)
2085 return;
2086
2087 switch (Name.getNameKind()) {
2088 case DeclarationName::Identifier:
2089 case DeclarationName::CXXConversionFunctionName:
2090 case DeclarationName::CXXOperatorName:
2091 case DeclarationName::CXXDestructorName:
2092 case DeclarationName::CXXLiteralOperatorName:
2093 Result->AddTypedTextChunk(ND->getNameAsString());
2094 break;
2095
2096 case DeclarationName::CXXUsingDirective:
2097 case DeclarationName::ObjCZeroArgSelector:
2098 case DeclarationName::ObjCOneArgSelector:
2099 case DeclarationName::ObjCMultiArgSelector:
2100 break;
2101
2102 case DeclarationName::CXXConstructorName: {
2103 CXXRecordDecl *Record = 0;
2104 QualType Ty = Name.getCXXNameType();
2105 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2106 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2107 else if (const InjectedClassNameType *InjectedTy
2108 = Ty->getAs<InjectedClassNameType>())
2109 Record = InjectedTy->getDecl();
2110 else {
2111 Result->AddTypedTextChunk(ND->getNameAsString());
2112 break;
2113 }
2114
2115 Result->AddTypedTextChunk(Record->getNameAsString());
2116 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2117 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2118 AddTemplateParameterChunks(Context, Template, Result);
2119 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2120 }
2121 break;
2122 }
2123 }
2124}
2125
Douglas Gregor86d9a522009-09-21 16:56:56 +00002126/// \brief If possible, create a new code completion string for the given
2127/// result.
2128///
2129/// \returns Either a new, heap-allocated code completion string describing
2130/// how to use this result, or NULL to indicate that the string or name of the
2131/// result is all that is needed.
2132CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002133CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor6f942b22010-09-21 16:06:22 +00002134 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002135 typedef CodeCompletionString::Chunk Chunk;
2136
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002137 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002138 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002139
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002140 if (!Result)
2141 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002142
2143 if (Kind == RK_Keyword) {
2144 Result->AddTypedTextChunk(Keyword);
2145 return Result;
2146 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002147
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002148 if (Kind == RK_Macro) {
2149 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002150 assert(MI && "Not a macro?");
2151
2152 Result->AddTypedTextChunk(Macro->getName());
2153
2154 if (!MI->isFunctionLike())
2155 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002156
2157 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002158 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002159 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2160 A != AEnd; ++A) {
2161 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002162 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002163
2164 if (!MI->isVariadic() || A != AEnd - 1) {
2165 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002166 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002167 continue;
2168 }
2169
2170 // Variadic argument; cope with the different between GNU and C99
2171 // variadic macros, providing a single placeholder for the rest of the
2172 // arguments.
2173 if ((*A)->isStr("__VA_ARGS__"))
2174 Result->AddPlaceholderChunk("...");
2175 else {
2176 std::string Arg = (*A)->getName();
2177 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00002178 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002179 }
2180 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002181 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002182 return Result;
2183 }
2184
Douglas Gregord8e8a582010-05-25 21:41:55 +00002185 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002186 NamedDecl *ND = Declaration;
2187
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002188 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002189 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002190 Result->AddTextChunk("::");
2191 return Result;
2192 }
2193
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002194 AddResultTypeChunk(S.Context, ND, Result);
2195
Douglas Gregor86d9a522009-09-21 16:56:56 +00002196 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002197 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2198 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002199 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002200 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002201 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002202 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002203 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002204 return Result;
2205 }
2206
2207 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002208 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2209 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002210 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002211 AddTypedNameChunk(S.Context, Function, Result);
2212
Douglas Gregor86d9a522009-09-21 16:56:56 +00002213 // Figure out which template parameters are deduced (or have default
2214 // arguments).
2215 llvm::SmallVector<bool, 16> Deduced;
2216 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2217 unsigned LastDeducibleArgument;
2218 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2219 --LastDeducibleArgument) {
2220 if (!Deduced[LastDeducibleArgument - 1]) {
2221 // C++0x: Figure out if the template argument has a default. If so,
2222 // the user doesn't need to type this argument.
2223 // FIXME: We need to abstract template parameters better!
2224 bool HasDefaultArg = false;
2225 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2226 LastDeducibleArgument - 1);
2227 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2228 HasDefaultArg = TTP->hasDefaultArgument();
2229 else if (NonTypeTemplateParmDecl *NTTP
2230 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2231 HasDefaultArg = NTTP->hasDefaultArgument();
2232 else {
2233 assert(isa<TemplateTemplateParmDecl>(Param));
2234 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002235 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002236 }
2237
2238 if (!HasDefaultArg)
2239 break;
2240 }
2241 }
2242
2243 if (LastDeducibleArgument) {
2244 // Some of the function template arguments cannot be deduced from a
2245 // function call, so we introduce an explicit template argument list
2246 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002247 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002248 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2249 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002250 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002251 }
2252
2253 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002254 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002255 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002256 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002257 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002258 return Result;
2259 }
2260
2261 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002262 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2263 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002264 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002265 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002266 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002267 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002268 return Result;
2269 }
2270
Douglas Gregor9630eb62009-11-17 16:44:22 +00002271 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002272 Selector Sel = Method->getSelector();
2273 if (Sel.isUnarySelector()) {
2274 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2275 return Result;
2276 }
2277
Douglas Gregord3c68542009-11-19 01:08:35 +00002278 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2279 SelName += ':';
2280 if (StartParameter == 0)
2281 Result->AddTypedTextChunk(SelName);
2282 else {
2283 Result->AddInformativeChunk(SelName);
2284
2285 // If there is only one parameter, and we're past it, add an empty
2286 // typed-text chunk since there is nothing to type.
2287 if (Method->param_size() == 1)
2288 Result->AddTypedTextChunk("");
2289 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002290 unsigned Idx = 0;
2291 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2292 PEnd = Method->param_end();
2293 P != PEnd; (void)++P, ++Idx) {
2294 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002295 std::string Keyword;
2296 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002297 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002298 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2299 Keyword += II->getName().str();
2300 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002301 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002302 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002303 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00002304 Result->AddTypedTextChunk(Keyword);
2305 else
2306 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002307 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002308
2309 // If we're before the starting parameter, skip the placeholder.
2310 if (Idx < StartParameter)
2311 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002312
2313 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002314
2315 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002316 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002317 else {
2318 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2319 Arg = "(" + Arg + ")";
2320 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002321 if (DeclaringEntity || AllParametersAreInformative)
2322 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002323 }
2324
Douglas Gregore17794f2010-08-31 05:13:43 +00002325 if (Method->isVariadic() && (P + 1) == PEnd)
2326 Arg += ", ...";
2327
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002328 if (DeclaringEntity)
2329 Result->AddTextChunk(Arg);
2330 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002331 Result->AddInformativeChunk(Arg);
2332 else
2333 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002334 }
2335
Douglas Gregor2a17af02009-12-23 00:21:46 +00002336 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002337 if (Method->param_size() == 0) {
2338 if (DeclaringEntity)
2339 Result->AddTextChunk(", ...");
2340 else if (AllParametersAreInformative)
2341 Result->AddInformativeChunk(", ...");
2342 else
2343 Result->AddPlaceholderChunk(", ...");
2344 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002345
2346 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002347 }
2348
Douglas Gregor9630eb62009-11-17 16:44:22 +00002349 return Result;
2350 }
2351
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002352 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002353 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2354 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002355
2356 Result->AddTypedTextChunk(ND->getNameAsString());
2357 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002358}
2359
Douglas Gregor86d802e2009-09-23 00:34:09 +00002360CodeCompletionString *
2361CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2362 unsigned CurrentArg,
2363 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002364 typedef CodeCompletionString::Chunk Chunk;
2365
Douglas Gregor86d802e2009-09-23 00:34:09 +00002366 CodeCompletionString *Result = new CodeCompletionString;
2367 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002368 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002369 const FunctionProtoType *Proto
2370 = dyn_cast<FunctionProtoType>(getFunctionType());
2371 if (!FDecl && !Proto) {
2372 // Function without a prototype. Just give the return type and a
2373 // highlighted ellipsis.
2374 const FunctionType *FT = getFunctionType();
2375 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002376 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002377 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2378 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2379 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002380 return Result;
2381 }
2382
2383 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002384 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002385 else
2386 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002387 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002388
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002389 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002390 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2391 for (unsigned I = 0; I != NumParams; ++I) {
2392 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002393 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002394
2395 std::string ArgString;
2396 QualType ArgType;
2397
2398 if (FDecl) {
2399 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2400 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2401 } else {
2402 ArgType = Proto->getArgType(I);
2403 }
2404
2405 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2406
2407 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002408 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002409 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002410 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002411 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002412 }
2413
2414 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002415 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002416 if (CurrentArg < NumParams)
2417 Result->AddTextChunk("...");
2418 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002419 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002420 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002421 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002422
2423 return Result;
2424}
2425
Douglas Gregor1827e102010-08-16 16:18:59 +00002426unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002427 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002428 bool PreferredTypeIsPointer) {
2429 unsigned Priority = CCP_Macro;
2430
Douglas Gregorb05496d2010-09-20 21:11:48 +00002431 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2432 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2433 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002434 Priority = CCP_Constant;
2435 if (PreferredTypeIsPointer)
2436 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002437 }
2438 // Treat "YES", "NO", "true", and "false" as constants.
2439 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2440 MacroName.equals("true") || MacroName.equals("false"))
2441 Priority = CCP_Constant;
2442 // Treat "bool" as a type.
2443 else if (MacroName.equals("bool"))
2444 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2445
Douglas Gregor1827e102010-08-16 16:18:59 +00002446
2447 return Priority;
2448}
2449
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002450CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2451 if (!D)
2452 return CXCursor_UnexposedDecl;
2453
2454 switch (D->getKind()) {
2455 case Decl::Enum: return CXCursor_EnumDecl;
2456 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2457 case Decl::Field: return CXCursor_FieldDecl;
2458 case Decl::Function:
2459 return CXCursor_FunctionDecl;
2460 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2461 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2462 case Decl::ObjCClass:
2463 // FIXME
2464 return CXCursor_UnexposedDecl;
2465 case Decl::ObjCForwardProtocol:
2466 // FIXME
2467 return CXCursor_UnexposedDecl;
2468 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2469 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2470 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2471 case Decl::ObjCMethod:
2472 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2473 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2474 case Decl::CXXMethod: return CXCursor_CXXMethod;
2475 case Decl::CXXConstructor: return CXCursor_Constructor;
2476 case Decl::CXXDestructor: return CXCursor_Destructor;
2477 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2478 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2479 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2480 case Decl::ParmVar: return CXCursor_ParmDecl;
2481 case Decl::Typedef: return CXCursor_TypedefDecl;
2482 case Decl::Var: return CXCursor_VarDecl;
2483 case Decl::Namespace: return CXCursor_Namespace;
2484 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2485 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2486 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2487 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2488 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2489 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2490 case Decl::ClassTemplatePartialSpecialization:
2491 return CXCursor_ClassTemplatePartialSpecialization;
2492 case Decl::UsingDirective: return CXCursor_UsingDirective;
2493
2494 case Decl::Using:
2495 case Decl::UnresolvedUsingValue:
2496 case Decl::UnresolvedUsingTypename:
2497 return CXCursor_UsingDeclaration;
2498
2499 default:
2500 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2501 switch (TD->getTagKind()) {
2502 case TTK_Struct: return CXCursor_StructDecl;
2503 case TTK_Class: return CXCursor_ClassDecl;
2504 case TTK_Union: return CXCursor_UnionDecl;
2505 case TTK_Enum: return CXCursor_EnumDecl;
2506 }
2507 }
2508 }
2509
2510 return CXCursor_UnexposedDecl;
2511}
2512
Douglas Gregor590c7d52010-07-08 20:55:51 +00002513static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2514 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002515 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002516
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002517 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002518 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2519 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002520 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002521 Results.AddResult(Result(M->first,
2522 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002523 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002524 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002525 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002526 Results.ExitScope();
2527}
2528
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002529static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2530 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002531 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002532
2533 Results.EnterNewScope();
2534 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2535 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2536 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2537 Results.AddResult(Result("__func__", CCP_Constant));
2538 Results.ExitScope();
2539}
2540
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002541static void HandleCodeCompleteResults(Sema *S,
2542 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002543 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002544 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002545 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002546 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002547 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002548
2549 for (unsigned I = 0; I != NumResults; ++I)
2550 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002551}
2552
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002553static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2554 Sema::ParserCompletionContext PCC) {
2555 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002556 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002557 return CodeCompletionContext::CCC_TopLevel;
2558
John McCallf312b1e2010-08-26 23:41:50 +00002559 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002560 return CodeCompletionContext::CCC_ClassStructUnion;
2561
John McCallf312b1e2010-08-26 23:41:50 +00002562 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002563 return CodeCompletionContext::CCC_ObjCInterface;
2564
John McCallf312b1e2010-08-26 23:41:50 +00002565 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002566 return CodeCompletionContext::CCC_ObjCImplementation;
2567
John McCallf312b1e2010-08-26 23:41:50 +00002568 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002569 return CodeCompletionContext::CCC_ObjCIvarList;
2570
John McCallf312b1e2010-08-26 23:41:50 +00002571 case Sema::PCC_Template:
2572 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002573 if (S.CurContext->isFileContext())
2574 return CodeCompletionContext::CCC_TopLevel;
2575 else if (S.CurContext->isRecord())
2576 return CodeCompletionContext::CCC_ClassStructUnion;
2577 else
2578 return CodeCompletionContext::CCC_Other;
2579
John McCallf312b1e2010-08-26 23:41:50 +00002580 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002581 return CodeCompletionContext::CCC_Recovery;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002582
John McCallf312b1e2010-08-26 23:41:50 +00002583 case Sema::PCC_Expression:
2584 case Sema::PCC_ForInit:
2585 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002586 return CodeCompletionContext::CCC_Expression;
2587
John McCallf312b1e2010-08-26 23:41:50 +00002588 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002589 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002590
John McCallf312b1e2010-08-26 23:41:50 +00002591 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002592 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002593
2594 case Sema::PCC_ParenthesizedExpression:
2595 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002596 }
2597
2598 return CodeCompletionContext::CCC_Other;
2599}
2600
Douglas Gregorf6961522010-08-27 21:18:54 +00002601/// \brief If we're in a C++ virtual member function, add completion results
2602/// that invoke the functions we override, since it's common to invoke the
2603/// overridden function as well as adding new functionality.
2604///
2605/// \param S The semantic analysis object for which we are generating results.
2606///
2607/// \param InContext This context in which the nested-name-specifier preceding
2608/// the code-completion point
2609static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2610 ResultBuilder &Results) {
2611 // Look through blocks.
2612 DeclContext *CurContext = S.CurContext;
2613 while (isa<BlockDecl>(CurContext))
2614 CurContext = CurContext->getParent();
2615
2616
2617 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2618 if (!Method || !Method->isVirtual())
2619 return;
2620
2621 // We need to have names for all of the parameters, if we're going to
2622 // generate a forwarding call.
2623 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2624 PEnd = Method->param_end();
2625 P != PEnd;
2626 ++P) {
2627 if (!(*P)->getDeclName())
2628 return;
2629 }
2630
2631 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2632 MEnd = Method->end_overridden_methods();
2633 M != MEnd; ++M) {
2634 CodeCompletionString *Pattern = new CodeCompletionString;
2635 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2636 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2637 continue;
2638
2639 // If we need a nested-name-specifier, add one now.
2640 if (!InContext) {
2641 NestedNameSpecifier *NNS
2642 = getRequiredQualification(S.Context, CurContext,
2643 Overridden->getDeclContext());
2644 if (NNS) {
2645 std::string Str;
2646 llvm::raw_string_ostream OS(Str);
2647 NNS->print(OS, S.Context.PrintingPolicy);
2648 Pattern->AddTextChunk(OS.str());
2649 }
2650 } else if (!InContext->Equals(Overridden->getDeclContext()))
2651 continue;
2652
2653 Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2654 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2655 bool FirstParam = true;
2656 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2657 PEnd = Method->param_end();
2658 P != PEnd; ++P) {
2659 if (FirstParam)
2660 FirstParam = false;
2661 else
2662 Pattern->AddChunk(CodeCompletionString::CK_Comma);
2663
2664 Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2665 }
2666 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2667 Results.AddResult(CodeCompletionResult(Pattern,
2668 CCP_SuperCompletion,
2669 CXCursor_CXXMethod));
2670 Results.Ignore(Overridden);
2671 }
2672}
2673
Douglas Gregor01dfea02010-01-10 23:08:15 +00002674void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002675 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002676 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002677 ResultBuilder Results(*this,
2678 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002679 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002680
Douglas Gregor01dfea02010-01-10 23:08:15 +00002681 // Determine how to filter results, e.g., so that the names of
2682 // values (functions, enumerators, function templates, etc.) are
2683 // only allowed where we can have an expression.
2684 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002685 case PCC_Namespace:
2686 case PCC_Class:
2687 case PCC_ObjCInterface:
2688 case PCC_ObjCImplementation:
2689 case PCC_ObjCInstanceVariableList:
2690 case PCC_Template:
2691 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002692 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002693 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2694 break;
2695
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002696 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002697 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002698 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002699 case PCC_ForInit:
2700 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002701 if (WantTypesInContext(CompletionContext, getLangOptions()))
2702 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2703 else
2704 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002705
2706 if (getLangOptions().CPlusPlus)
2707 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002708 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002709
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002710 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002711 // Unfiltered
2712 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002713 }
2714
Douglas Gregor3cdee122010-08-26 16:36:48 +00002715 // If we are in a C++ non-static member function, check the qualifiers on
2716 // the member function to filter/prioritize the results list.
2717 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2718 if (CurMethod->isInstance())
2719 Results.setObjectTypeQualifiers(
2720 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2721
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002722 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002723 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2724 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002725
Douglas Gregorbca403c2010-01-13 23:51:12 +00002726 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002727 Results.ExitScope();
2728
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002729 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002730 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002731 case PCC_Expression:
2732 case PCC_Statement:
2733 case PCC_RecoveryInFunction:
2734 if (S->getFnParent())
2735 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2736 break;
2737
2738 case PCC_Namespace:
2739 case PCC_Class:
2740 case PCC_ObjCInterface:
2741 case PCC_ObjCImplementation:
2742 case PCC_ObjCInstanceVariableList:
2743 case PCC_Template:
2744 case PCC_MemberTemplate:
2745 case PCC_ForInit:
2746 case PCC_Condition:
2747 case PCC_Type:
2748 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002749 }
2750
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002751 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002752 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002753
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002754 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002755 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002756}
2757
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002758static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2759 ParsedType Receiver,
2760 IdentifierInfo **SelIdents,
2761 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002762 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002763 bool IsSuper,
2764 ResultBuilder &Results);
2765
2766void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2767 bool AllowNonIdentifiers,
2768 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002769 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002770 ResultBuilder Results(*this,
2771 AllowNestedNameSpecifiers
2772 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2773 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002774 Results.EnterNewScope();
2775
2776 // Type qualifiers can come after names.
2777 Results.AddResult(Result("const"));
2778 Results.AddResult(Result("volatile"));
2779 if (getLangOptions().C99)
2780 Results.AddResult(Result("restrict"));
2781
2782 if (getLangOptions().CPlusPlus) {
2783 if (AllowNonIdentifiers) {
2784 Results.AddResult(Result("operator"));
2785 }
2786
2787 // Add nested-name-specifiers.
2788 if (AllowNestedNameSpecifiers) {
2789 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00002790 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002791 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2792 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2793 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00002794 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002795 }
2796 }
2797 Results.ExitScope();
2798
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002799 // If we're in a context where we might have an expression (rather than a
2800 // declaration), and what we've seen so far is an Objective-C type that could
2801 // be a receiver of a class message, this may be a class message send with
2802 // the initial opening bracket '[' missing. Add appropriate completions.
2803 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2804 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2805 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2806 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2807 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2808 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2809 DS.getTypeQualifiers() == 0 &&
2810 S &&
2811 (S->getFlags() & Scope::DeclScope) != 0 &&
2812 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2813 Scope::FunctionPrototypeScope |
2814 Scope::AtCatchScope)) == 0) {
2815 ParsedType T = DS.getRepAsType();
2816 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002817 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002818 }
2819
Douglas Gregor4497dd42010-08-24 04:59:56 +00002820 // Note that we intentionally suppress macro results here, since we do not
2821 // encourage using macros to produce the names of entities.
2822
Douglas Gregor52779fb2010-09-23 23:01:17 +00002823 HandleCodeCompleteResults(this, CodeCompleter,
2824 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002825 Results.data(), Results.size());
2826}
2827
Douglas Gregorfb629412010-08-23 21:17:50 +00002828struct Sema::CodeCompleteExpressionData {
2829 CodeCompleteExpressionData(QualType PreferredType = QualType())
2830 : PreferredType(PreferredType), IntegralConstantExpression(false),
2831 ObjCCollection(false) { }
2832
2833 QualType PreferredType;
2834 bool IntegralConstantExpression;
2835 bool ObjCCollection;
2836 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2837};
2838
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002839/// \brief Perform code-completion in an expression context when we know what
2840/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002841///
2842/// \param IntegralConstantExpression Only permit integral constant
2843/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002844void Sema::CodeCompleteExpression(Scope *S,
2845 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002846 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002847 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00002848 if (Data.ObjCCollection)
2849 Results.setFilter(&ResultBuilder::IsObjCCollection);
2850 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002851 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002852 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002853 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2854 else
2855 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002856
2857 if (!Data.PreferredType.isNull())
2858 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2859
2860 // Ignore any declarations that we were told that we don't care about.
2861 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2862 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002863
2864 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002865 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2866 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002867
2868 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002869 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002870 Results.ExitScope();
2871
Douglas Gregor590c7d52010-07-08 20:55:51 +00002872 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002873 if (!Data.PreferredType.isNull())
2874 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2875 || Data.PreferredType->isMemberPointerType()
2876 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002877
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002878 if (S->getFnParent() &&
2879 !Data.ObjCCollection &&
2880 !Data.IntegralConstantExpression)
2881 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2882
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002883 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002884 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002885 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002886 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2887 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002888 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002889}
2890
Douglas Gregorac5fd842010-09-18 01:28:11 +00002891void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
2892 if (E.isInvalid())
2893 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
2894 else if (getLangOptions().ObjC1)
2895 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00002896}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002897
Douglas Gregor95ac6552009-11-18 01:29:26 +00002898static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002899 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002900 DeclContext *CurContext,
2901 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002902 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002903
2904 // Add properties in this container.
2905 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2906 PEnd = Container->prop_end();
2907 P != PEnd;
2908 ++P)
2909 Results.MaybeAddResult(Result(*P, 0), CurContext);
2910
2911 // Add properties in referenced protocols.
2912 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2913 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2914 PEnd = Protocol->protocol_end();
2915 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002916 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002917 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002918 if (AllowCategories) {
2919 // Look through categories.
2920 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2921 Category; Category = Category->getNextClassCategory())
2922 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2923 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002924
2925 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002926 for (ObjCInterfaceDecl::all_protocol_iterator
2927 I = IFace->all_referenced_protocol_begin(),
2928 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002929 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002930
2931 // Look in the superclass.
2932 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002933 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2934 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002935 } else if (const ObjCCategoryDecl *Category
2936 = dyn_cast<ObjCCategoryDecl>(Container)) {
2937 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002938 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
2939 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002940 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002941 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002942 }
2943}
2944
Douglas Gregor81b747b2009-09-17 21:32:03 +00002945void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2946 SourceLocation OpLoc,
2947 bool IsArrow) {
2948 if (!BaseE || !CodeCompleter)
2949 return;
2950
John McCall0a2c5e22010-08-25 06:19:51 +00002951 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002952
Douglas Gregor81b747b2009-09-17 21:32:03 +00002953 Expr *Base = static_cast<Expr *>(BaseE);
2954 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002955
2956 if (IsArrow) {
2957 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2958 BaseType = Ptr->getPointeeType();
2959 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00002960 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002961 else
2962 return;
2963 }
2964
Douglas Gregor52779fb2010-09-23 23:01:17 +00002965 ResultBuilder Results(*this,
2966 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2967 BaseType),
2968 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002969 Results.EnterNewScope();
2970 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00002971 // Indicate that we are performing a member access, and the cv-qualifiers
2972 // for the base object type.
2973 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
2974
Douglas Gregor95ac6552009-11-18 01:29:26 +00002975 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002976 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002977 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002978 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2979 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002980
Douglas Gregor95ac6552009-11-18 01:29:26 +00002981 if (getLangOptions().CPlusPlus) {
2982 if (!Results.empty()) {
2983 // The "template" keyword can follow "->" or "." in the grammar.
2984 // However, we only want to suggest the template keyword if something
2985 // is dependent.
2986 bool IsDependent = BaseType->isDependentType();
2987 if (!IsDependent) {
2988 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2989 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2990 IsDependent = Ctx->isDependentContext();
2991 break;
2992 }
2993 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002994
Douglas Gregor95ac6552009-11-18 01:29:26 +00002995 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002996 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002997 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002998 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002999 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3000 // Objective-C property reference.
3001
3002 // Add property results based on our interface.
3003 const ObjCObjectPointerType *ObjCPtr
3004 = BaseType->getAsObjCInterfacePointerType();
3005 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00003006 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003007
3008 // Add properties from the protocols in a qualified interface.
3009 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3010 E = ObjCPtr->qual_end();
3011 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00003012 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003013 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003014 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003015 // Objective-C instance variable access.
3016 ObjCInterfaceDecl *Class = 0;
3017 if (const ObjCObjectPointerType *ObjCPtr
3018 = BaseType->getAs<ObjCObjectPointerType>())
3019 Class = ObjCPtr->getInterfaceDecl();
3020 else
John McCallc12c5bb2010-05-15 11:32:37 +00003021 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003022
3023 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003024 if (Class) {
3025 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3026 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003027 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3028 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003029 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003030 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003031
3032 // FIXME: How do we cope with isa?
3033
3034 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003035
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003036 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003037 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003038 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003039 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003040}
3041
Douglas Gregor374929f2009-09-18 15:37:17 +00003042void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3043 if (!CodeCompleter)
3044 return;
3045
John McCall0a2c5e22010-08-25 06:19:51 +00003046 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003047 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003048 enum CodeCompletionContext::Kind ContextKind
3049 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003050 switch ((DeclSpec::TST)TagSpec) {
3051 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003052 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003053 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003054 break;
3055
3056 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003057 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003058 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003059 break;
3060
3061 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003062 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003063 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003064 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003065 break;
3066
3067 default:
3068 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3069 return;
3070 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003071
Douglas Gregor52779fb2010-09-23 23:01:17 +00003072 ResultBuilder Results(*this, ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003073 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003074
3075 // First pass: look for tags.
3076 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003077 LookupVisibleDecls(S, LookupTagName, Consumer,
3078 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003079
Douglas Gregor8071e422010-08-15 06:18:01 +00003080 if (CodeCompleter->includeGlobals()) {
3081 // Second pass: look for nested name specifiers.
3082 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3083 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3084 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003085
Douglas Gregor52779fb2010-09-23 23:01:17 +00003086 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003087 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003088}
3089
Douglas Gregor1a480c42010-08-27 17:35:51 +00003090void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003091 ResultBuilder Results(*this, CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003092 Results.EnterNewScope();
3093 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3094 Results.AddResult("const");
3095 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3096 Results.AddResult("volatile");
3097 if (getLangOptions().C99 &&
3098 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3099 Results.AddResult("restrict");
3100 Results.ExitScope();
3101 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003102 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003103 Results.data(), Results.size());
3104}
3105
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003106void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003107 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003108 return;
3109
John McCall781472f2010-08-25 08:40:02 +00003110 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003111 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003112 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3113 Data.IntegralConstantExpression = true;
3114 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003115 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003116 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003117
3118 // Code-complete the cases of a switch statement over an enumeration type
3119 // by providing the list of
3120 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3121
3122 // Determine which enumerators we have already seen in the switch statement.
3123 // FIXME: Ideally, we would also be able to look *past* the code-completion
3124 // token, in case we are code-completing in the middle of the switch and not
3125 // at the end. However, we aren't able to do so at the moment.
3126 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003127 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003128 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3129 SC = SC->getNextSwitchCase()) {
3130 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3131 if (!Case)
3132 continue;
3133
3134 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3135 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3136 if (EnumConstantDecl *Enumerator
3137 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3138 // We look into the AST of the case statement to determine which
3139 // enumerator was named. Alternatively, we could compute the value of
3140 // the integral constant expression, then compare it against the
3141 // values of each enumerator. However, value-based approach would not
3142 // work as well with C++ templates where enumerators declared within a
3143 // template are type- and value-dependent.
3144 EnumeratorsSeen.insert(Enumerator);
3145
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003146 // If this is a qualified-id, keep track of the nested-name-specifier
3147 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003148 //
3149 // switch (TagD.getKind()) {
3150 // case TagDecl::TK_enum:
3151 // break;
3152 // case XXX
3153 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003154 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003155 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3156 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003157 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003158 }
3159 }
3160
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003161 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3162 // If there are no prior enumerators in C++, check whether we have to
3163 // qualify the names of the enumerators that we suggest, because they
3164 // may not be visible in this scope.
3165 Qualifier = getRequiredQualification(Context, CurContext,
3166 Enum->getDeclContext());
3167
3168 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3169 }
3170
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003171 // Add any enumerators that have not yet been mentioned.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003172 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003173 Results.EnterNewScope();
3174 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3175 EEnd = Enum->enumerator_end();
3176 E != EEnd; ++E) {
3177 if (EnumeratorsSeen.count(*E))
3178 continue;
3179
John McCall0a2c5e22010-08-25 06:19:51 +00003180 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00003181 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003182 }
3183 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003184
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003185 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003186 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003187 HandleCodeCompleteResults(this, CodeCompleter,
3188 CodeCompletionContext::CCC_Expression,
3189 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003190}
3191
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003192namespace {
3193 struct IsBetterOverloadCandidate {
3194 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003195 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003196
3197 public:
John McCall5769d612010-02-08 23:07:23 +00003198 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3199 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003200
3201 bool
3202 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003203 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003204 }
3205 };
3206}
3207
Douglas Gregord28dcd72010-05-30 06:10:08 +00003208static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3209 if (NumArgs && !Args)
3210 return true;
3211
3212 for (unsigned I = 0; I != NumArgs; ++I)
3213 if (!Args[I])
3214 return true;
3215
3216 return false;
3217}
3218
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003219void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3220 ExprTy **ArgsIn, unsigned NumArgs) {
3221 if (!CodeCompleter)
3222 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003223
3224 // When we're code-completing for a call, we fall back to ordinary
3225 // name code-completion whenever we can't produce specific
3226 // results. We may want to revisit this strategy in the future,
3227 // e.g., by merging the two kinds of results.
3228
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003229 Expr *Fn = (Expr *)FnIn;
3230 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003231
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003232 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003233 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003234 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003235 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003236 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003237 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003238
John McCall3b4294e2009-12-16 12:17:52 +00003239 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003240 SourceLocation Loc = Fn->getExprLoc();
3241 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003242
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003243 // FIXME: What if we're calling something that isn't a function declaration?
3244 // FIXME: What if we're calling a pseudo-destructor?
3245 // FIXME: What if we're calling a member function?
3246
Douglas Gregorc0265402010-01-21 15:46:19 +00003247 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3248 llvm::SmallVector<ResultCandidate, 8> Results;
3249
John McCall3b4294e2009-12-16 12:17:52 +00003250 Expr *NakedFn = Fn->IgnoreParenCasts();
3251 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3252 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3253 /*PartialOverloading=*/ true);
3254 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3255 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003256 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003257 if (!getLangOptions().CPlusPlus ||
3258 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003259 Results.push_back(ResultCandidate(FDecl));
3260 else
John McCall86820f52010-01-26 01:37:31 +00003261 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003262 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3263 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003264 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003265 }
John McCall3b4294e2009-12-16 12:17:52 +00003266 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003267
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003268 QualType ParamType;
3269
Douglas Gregorc0265402010-01-21 15:46:19 +00003270 if (!CandidateSet.empty()) {
3271 // Sort the overload candidate set by placing the best overloads first.
3272 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003273 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003274
Douglas Gregorc0265402010-01-21 15:46:19 +00003275 // Add the remaining viable overload candidates as code-completion reslults.
3276 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3277 CandEnd = CandidateSet.end();
3278 Cand != CandEnd; ++Cand) {
3279 if (Cand->Viable)
3280 Results.push_back(ResultCandidate(Cand->Function));
3281 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003282
3283 // From the viable candidates, try to determine the type of this parameter.
3284 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3285 if (const FunctionType *FType = Results[I].getFunctionType())
3286 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3287 if (NumArgs < Proto->getNumArgs()) {
3288 if (ParamType.isNull())
3289 ParamType = Proto->getArgType(NumArgs);
3290 else if (!Context.hasSameUnqualifiedType(
3291 ParamType.getNonReferenceType(),
3292 Proto->getArgType(NumArgs).getNonReferenceType())) {
3293 ParamType = QualType();
3294 break;
3295 }
3296 }
3297 }
3298 } else {
3299 // Try to determine the parameter type from the type of the expression
3300 // being called.
3301 QualType FunctionType = Fn->getType();
3302 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3303 FunctionType = Ptr->getPointeeType();
3304 else if (const BlockPointerType *BlockPtr
3305 = FunctionType->getAs<BlockPointerType>())
3306 FunctionType = BlockPtr->getPointeeType();
3307 else if (const MemberPointerType *MemPtr
3308 = FunctionType->getAs<MemberPointerType>())
3309 FunctionType = MemPtr->getPointeeType();
3310
3311 if (const FunctionProtoType *Proto
3312 = FunctionType->getAs<FunctionProtoType>()) {
3313 if (NumArgs < Proto->getNumArgs())
3314 ParamType = Proto->getArgType(NumArgs);
3315 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003316 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003317
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003318 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003319 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003320 else
3321 CodeCompleteExpression(S, ParamType);
3322
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003323 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003324 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3325 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003326}
3327
John McCalld226f652010-08-21 09:40:31 +00003328void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3329 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003330 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003331 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003332 return;
3333 }
3334
3335 CodeCompleteExpression(S, VD->getType());
3336}
3337
3338void Sema::CodeCompleteReturn(Scope *S) {
3339 QualType ResultType;
3340 if (isa<BlockDecl>(CurContext)) {
3341 if (BlockScopeInfo *BSI = getCurBlock())
3342 ResultType = BSI->ReturnType;
3343 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3344 ResultType = Function->getResultType();
3345 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3346 ResultType = Method->getResultType();
3347
3348 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003349 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003350 else
3351 CodeCompleteExpression(S, ResultType);
3352}
3353
3354void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3355 if (LHS)
3356 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3357 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003358 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003359}
3360
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003361void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003362 bool EnteringContext) {
3363 if (!SS.getScopeRep() || !CodeCompleter)
3364 return;
3365
Douglas Gregor86d9a522009-09-21 16:56:56 +00003366 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3367 if (!Ctx)
3368 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003369
3370 // Try to instantiate any non-dependent declaration contexts before
3371 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003372 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003373 return;
3374
Douglas Gregor52779fb2010-09-23 23:01:17 +00003375 ResultBuilder Results(*this, CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003376 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003377
Douglas Gregor86d9a522009-09-21 16:56:56 +00003378 // The "template" keyword can follow "::" in the grammar, but only
3379 // put it into the grammar if the nested-name-specifier is dependent.
3380 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3381 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003382 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003383
3384 // Add calls to overridden virtual functions, if there are any.
3385 //
3386 // FIXME: This isn't wonderful, because we don't know whether we're actually
3387 // in a context that permits expressions. This is a general issue with
3388 // qualified-id completions.
3389 if (!EnteringContext)
3390 MaybeAddOverrideCalls(*this, Ctx, Results);
3391 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003392
Douglas Gregorf6961522010-08-27 21:18:54 +00003393 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3394 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3395
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003396 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003397 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003398 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003399}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003400
3401void Sema::CodeCompleteUsing(Scope *S) {
3402 if (!CodeCompleter)
3403 return;
3404
Douglas Gregor52779fb2010-09-23 23:01:17 +00003405 ResultBuilder Results(*this,
3406 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3407 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003408 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003409
3410 // If we aren't in class scope, we could see the "namespace" keyword.
3411 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003412 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003413
3414 // After "using", we can see anything that would start a
3415 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003416 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003417 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3418 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003419 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003420
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003421 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003422 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003423 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003424}
3425
3426void Sema::CodeCompleteUsingDirective(Scope *S) {
3427 if (!CodeCompleter)
3428 return;
3429
Douglas Gregor86d9a522009-09-21 16:56:56 +00003430 // After "using namespace", we expect to see a namespace name or namespace
3431 // alias.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003432 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3433 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003434 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003435 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003436 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3437 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003438 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003439 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003440 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003441 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003442}
3443
3444void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3445 if (!CodeCompleter)
3446 return;
3447
Douglas Gregor86d9a522009-09-21 16:56:56 +00003448 DeclContext *Ctx = (DeclContext *)S->getEntity();
3449 if (!S->getParent())
3450 Ctx = Context.getTranslationUnitDecl();
3451
Douglas Gregor52779fb2010-09-23 23:01:17 +00003452 bool SuppressedGlobalResults
3453 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3454
3455 ResultBuilder Results(*this,
3456 SuppressedGlobalResults
3457 ? CodeCompletionContext::CCC_Namespace
3458 : CodeCompletionContext::CCC_Other,
3459 &ResultBuilder::IsNamespace);
3460
3461 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003462 // We only want to see those namespaces that have already been defined
3463 // within this scope, because its likely that the user is creating an
3464 // extended namespace declaration. Keep track of the most recent
3465 // definition of each namespace.
3466 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3467 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3468 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3469 NS != NSEnd; ++NS)
3470 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3471
3472 // Add the most recent definition (or extended definition) of each
3473 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003474 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003475 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3476 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3477 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003478 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003479 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003480 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003481 }
3482
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003483 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003484 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003485 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003486}
3487
3488void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3489 if (!CodeCompleter)
3490 return;
3491
Douglas Gregor86d9a522009-09-21 16:56:56 +00003492 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003493 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3494 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003495 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003496 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3497 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003498 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003499 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003500 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003501}
3502
Douglas Gregored8d3222009-09-18 20:05:18 +00003503void Sema::CodeCompleteOperatorName(Scope *S) {
3504 if (!CodeCompleter)
3505 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003506
John McCall0a2c5e22010-08-25 06:19:51 +00003507 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003508 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type,
3509 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003510 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003511
Douglas Gregor86d9a522009-09-21 16:56:56 +00003512 // Add the names of overloadable operators.
3513#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3514 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003515 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003516#include "clang/Basic/OperatorKinds.def"
3517
3518 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003519 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003520 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003521 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3522 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003523
3524 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003525 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003526 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003527
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003528 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003529 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003530 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003531}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003532
Douglas Gregor0133f522010-08-28 00:00:50 +00003533void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3534 CXXBaseOrMemberInitializer** Initializers,
3535 unsigned NumInitializers) {
3536 CXXConstructorDecl *Constructor
3537 = static_cast<CXXConstructorDecl *>(ConstructorD);
3538 if (!Constructor)
3539 return;
3540
Douglas Gregor52779fb2010-09-23 23:01:17 +00003541 ResultBuilder Results(*this,
3542 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003543 Results.EnterNewScope();
3544
3545 // Fill in any already-initialized fields or base classes.
3546 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3547 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3548 for (unsigned I = 0; I != NumInitializers; ++I) {
3549 if (Initializers[I]->isBaseInitializer())
3550 InitializedBases.insert(
3551 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3552 else
3553 InitializedFields.insert(cast<FieldDecl>(Initializers[I]->getMember()));
3554 }
3555
3556 // Add completions for base classes.
Douglas Gregor0c431c82010-08-29 19:27:27 +00003557 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003558 CXXRecordDecl *ClassDecl = Constructor->getParent();
3559 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3560 BaseEnd = ClassDecl->bases_end();
3561 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003562 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3563 SawLastInitializer
3564 = NumInitializers > 0 &&
3565 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3566 Context.hasSameUnqualifiedType(Base->getType(),
3567 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003568 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003569 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003570
3571 CodeCompletionString *Pattern = new CodeCompletionString;
3572 Pattern->AddTypedTextChunk(
3573 Base->getType().getAsString(Context.PrintingPolicy));
3574 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3575 Pattern->AddPlaceholderChunk("args");
3576 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003577 Results.AddResult(CodeCompletionResult(Pattern,
3578 SawLastInitializer? CCP_NextInitializer
3579 : CCP_MemberDeclaration));
3580 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003581 }
3582
3583 // Add completions for virtual base classes.
3584 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3585 BaseEnd = ClassDecl->vbases_end();
3586 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003587 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3588 SawLastInitializer
3589 = NumInitializers > 0 &&
3590 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3591 Context.hasSameUnqualifiedType(Base->getType(),
3592 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003593 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003594 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003595
3596 CodeCompletionString *Pattern = new CodeCompletionString;
3597 Pattern->AddTypedTextChunk(
3598 Base->getType().getAsString(Context.PrintingPolicy));
3599 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3600 Pattern->AddPlaceholderChunk("args");
3601 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003602 Results.AddResult(CodeCompletionResult(Pattern,
3603 SawLastInitializer? CCP_NextInitializer
3604 : CCP_MemberDeclaration));
3605 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003606 }
3607
3608 // Add completions for members.
3609 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3610 FieldEnd = ClassDecl->field_end();
3611 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003612 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3613 SawLastInitializer
3614 = NumInitializers > 0 &&
3615 Initializers[NumInitializers - 1]->isMemberInitializer() &&
3616 Initializers[NumInitializers - 1]->getMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003617 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003618 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003619
3620 if (!Field->getDeclName())
3621 continue;
3622
3623 CodeCompletionString *Pattern = new CodeCompletionString;
3624 Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3625 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3626 Pattern->AddPlaceholderChunk("args");
3627 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003628 Results.AddResult(CodeCompletionResult(Pattern,
3629 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003630 : CCP_MemberDeclaration,
3631 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003632 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003633 }
3634 Results.ExitScope();
3635
Douglas Gregor52779fb2010-09-23 23:01:17 +00003636 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003637 Results.data(), Results.size());
3638}
3639
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003640// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3641// true or false.
3642#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003643static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003644 ResultBuilder &Results,
3645 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003646 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003647 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003648 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003649
3650 CodeCompletionString *Pattern = 0;
3651 if (LangOpts.ObjC2) {
3652 // @dynamic
3653 Pattern = new CodeCompletionString;
3654 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3655 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3656 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003657 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003658
3659 // @synthesize
3660 Pattern = new CodeCompletionString;
3661 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3662 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3663 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003664 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003665 }
3666}
3667
Douglas Gregorbca403c2010-01-13 23:51:12 +00003668static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003669 ResultBuilder &Results,
3670 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003671 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003672
3673 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003674 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003675
3676 if (LangOpts.ObjC2) {
3677 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003678 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003679
3680 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003681 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003682
3683 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003684 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003685 }
3686}
3687
Douglas Gregorbca403c2010-01-13 23:51:12 +00003688static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003689 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003690 CodeCompletionString *Pattern = 0;
3691
3692 // @class name ;
3693 Pattern = new CodeCompletionString;
3694 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3695 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003696 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003697 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003698
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003699 if (Results.includeCodePatterns()) {
3700 // @interface name
3701 // FIXME: Could introduce the whole pattern, including superclasses and
3702 // such.
3703 Pattern = new CodeCompletionString;
3704 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3705 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3706 Pattern->AddPlaceholderChunk("class");
3707 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003708
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003709 // @protocol name
3710 Pattern = new CodeCompletionString;
3711 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3712 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3713 Pattern->AddPlaceholderChunk("protocol");
3714 Results.AddResult(Result(Pattern));
3715
3716 // @implementation name
3717 Pattern = new CodeCompletionString;
3718 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3719 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3720 Pattern->AddPlaceholderChunk("class");
3721 Results.AddResult(Result(Pattern));
3722 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003723
3724 // @compatibility_alias name
3725 Pattern = new CodeCompletionString;
3726 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3727 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3728 Pattern->AddPlaceholderChunk("alias");
3729 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3730 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003731 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003732}
3733
John McCalld226f652010-08-21 09:40:31 +00003734void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003735 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003736 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003737 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003738 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003739 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003740 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003741 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003742 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003743 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003744 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003745 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003746 HandleCodeCompleteResults(this, CodeCompleter,
3747 CodeCompletionContext::CCC_Other,
3748 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003749}
3750
Douglas Gregorbca403c2010-01-13 23:51:12 +00003751static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003752 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003753 CodeCompletionString *Pattern = 0;
3754
3755 // @encode ( type-name )
3756 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003757 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003758 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3759 Pattern->AddPlaceholderChunk("type-name");
3760 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003761 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003762
3763 // @protocol ( protocol-name )
3764 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003765 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003766 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3767 Pattern->AddPlaceholderChunk("protocol-name");
3768 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003769 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003770
3771 // @selector ( selector )
3772 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003773 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003774 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3775 Pattern->AddPlaceholderChunk("selector");
3776 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003777 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003778}
3779
Douglas Gregorbca403c2010-01-13 23:51:12 +00003780static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003781 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003782 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003783
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003784 if (Results.includeCodePatterns()) {
3785 // @try { statements } @catch ( declaration ) { statements } @finally
3786 // { statements }
3787 Pattern = new CodeCompletionString;
3788 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3789 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3790 Pattern->AddPlaceholderChunk("statements");
3791 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3792 Pattern->AddTextChunk("@catch");
3793 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3794 Pattern->AddPlaceholderChunk("parameter");
3795 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3796 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3797 Pattern->AddPlaceholderChunk("statements");
3798 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3799 Pattern->AddTextChunk("@finally");
3800 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3801 Pattern->AddPlaceholderChunk("statements");
3802 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3803 Results.AddResult(Result(Pattern));
3804 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003805
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003806 // @throw
3807 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003808 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003809 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003810 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003811 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003812
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003813 if (Results.includeCodePatterns()) {
3814 // @synchronized ( expression ) { statements }
3815 Pattern = new CodeCompletionString;
3816 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3817 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3818 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3819 Pattern->AddPlaceholderChunk("expression");
3820 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3821 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3822 Pattern->AddPlaceholderChunk("statements");
3823 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3824 Results.AddResult(Result(Pattern));
3825 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003826}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003827
Douglas Gregorbca403c2010-01-13 23:51:12 +00003828static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003829 ResultBuilder &Results,
3830 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003831 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003832 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3833 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3834 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003835 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003836 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003837}
3838
3839void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003840 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003841 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003842 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003843 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003844 HandleCodeCompleteResults(this, CodeCompleter,
3845 CodeCompletionContext::CCC_Other,
3846 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003847}
3848
3849void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003850 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003851 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003852 AddObjCStatementResults(Results, false);
3853 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003854 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003855 HandleCodeCompleteResults(this, CodeCompleter,
3856 CodeCompletionContext::CCC_Other,
3857 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003858}
3859
3860void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003861 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003862 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003863 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003864 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003865 HandleCodeCompleteResults(this, CodeCompleter,
3866 CodeCompletionContext::CCC_Other,
3867 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003868}
3869
Douglas Gregor988358f2009-11-19 00:14:45 +00003870/// \brief Determine whether the addition of the given flag to an Objective-C
3871/// property's attributes will cause a conflict.
3872static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3873 // Check if we've already added this flag.
3874 if (Attributes & NewFlag)
3875 return true;
3876
3877 Attributes |= NewFlag;
3878
3879 // Check for collisions with "readonly".
3880 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3881 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3882 ObjCDeclSpec::DQ_PR_assign |
3883 ObjCDeclSpec::DQ_PR_copy |
3884 ObjCDeclSpec::DQ_PR_retain)))
3885 return true;
3886
3887 // Check for more than one of { assign, copy, retain }.
3888 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3889 ObjCDeclSpec::DQ_PR_copy |
3890 ObjCDeclSpec::DQ_PR_retain);
3891 if (AssignCopyRetMask &&
3892 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3893 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3894 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3895 return true;
3896
3897 return false;
3898}
3899
Douglas Gregora93b1082009-11-18 23:08:07 +00003900void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003901 if (!CodeCompleter)
3902 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003903
Steve Naroffece8e712009-10-08 21:55:05 +00003904 unsigned Attributes = ODS.getPropertyAttributes();
3905
John McCall0a2c5e22010-08-25 06:19:51 +00003906 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003907 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00003908 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003909 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003910 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003911 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003912 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003913 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003914 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003915 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003916 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003917 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003918 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003919 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003920 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003921 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003922 CodeCompletionString *Setter = new CodeCompletionString;
3923 Setter->AddTypedTextChunk("setter");
3924 Setter->AddTextChunk(" = ");
3925 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003926 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003927 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003928 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003929 CodeCompletionString *Getter = new CodeCompletionString;
3930 Getter->AddTypedTextChunk("getter");
3931 Getter->AddTextChunk(" = ");
3932 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003933 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003934 }
Steve Naroffece8e712009-10-08 21:55:05 +00003935 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003936 HandleCodeCompleteResults(this, CodeCompleter,
3937 CodeCompletionContext::CCC_Other,
3938 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003939}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003940
Douglas Gregor4ad96852009-11-19 07:41:15 +00003941/// \brief Descripts the kind of Objective-C method that we want to find
3942/// via code completion.
3943enum ObjCMethodKind {
3944 MK_Any, //< Any kind of method, provided it means other specified criteria.
3945 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3946 MK_OneArgSelector //< One-argument selector.
3947};
3948
Douglas Gregor458433d2010-08-26 15:07:07 +00003949static bool isAcceptableObjCSelector(Selector Sel,
3950 ObjCMethodKind WantKind,
3951 IdentifierInfo **SelIdents,
3952 unsigned NumSelIdents) {
3953 if (NumSelIdents > Sel.getNumArgs())
3954 return false;
3955
3956 switch (WantKind) {
3957 case MK_Any: break;
3958 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3959 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3960 }
3961
3962 for (unsigned I = 0; I != NumSelIdents; ++I)
3963 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3964 return false;
3965
3966 return true;
3967}
3968
Douglas Gregor4ad96852009-11-19 07:41:15 +00003969static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3970 ObjCMethodKind WantKind,
3971 IdentifierInfo **SelIdents,
3972 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00003973 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3974 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003975}
Douglas Gregord36adf52010-09-16 16:06:31 +00003976
3977namespace {
3978 /// \brief A set of selectors, which is used to avoid introducing multiple
3979 /// completions with the same selector into the result set.
3980 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
3981}
3982
Douglas Gregor36ecb042009-11-17 23:22:23 +00003983/// \brief Add all of the Objective-C methods in the given Objective-C
3984/// container to the set of results.
3985///
3986/// The container will be a class, protocol, category, or implementation of
3987/// any of the above. This mether will recurse to include methods from
3988/// the superclasses of classes along with their categories, protocols, and
3989/// implementations.
3990///
3991/// \param Container the container in which we'll look to find methods.
3992///
3993/// \param WantInstance whether to add instance methods (only); if false, this
3994/// routine will add factory methods (only).
3995///
3996/// \param CurContext the context in which we're performing the lookup that
3997/// finds methods.
3998///
3999/// \param Results the structure into which we'll add results.
4000static void AddObjCMethods(ObjCContainerDecl *Container,
4001 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004002 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004003 IdentifierInfo **SelIdents,
4004 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004005 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004006 VisitedSelectorSet &Selectors,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004007 ResultBuilder &Results,
4008 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004009 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004010 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4011 MEnd = Container->meth_end();
4012 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004013 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4014 // Check whether the selector identifiers we've been given are a
4015 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004016 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00004017 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004018
Douglas Gregord36adf52010-09-16 16:06:31 +00004019 if (!Selectors.insert((*M)->getSelector()))
4020 continue;
4021
Douglas Gregord3c68542009-11-19 01:08:35 +00004022 Result R = Result(*M, 0);
4023 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004024 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004025 if (!InOriginalClass)
4026 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004027 Results.MaybeAddResult(R, CurContext);
4028 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004029 }
4030
Douglas Gregore396c7b2010-09-16 15:34:59 +00004031 // Visit the protocols of protocols.
4032 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4033 const ObjCList<ObjCProtocolDecl> &Protocols
4034 = Protocol->getReferencedProtocols();
4035 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4036 E = Protocols.end();
4037 I != E; ++I)
4038 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004039 CurContext, Selectors, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004040 }
4041
Douglas Gregor36ecb042009-11-17 23:22:23 +00004042 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4043 if (!IFace)
4044 return;
4045
4046 // Add methods in protocols.
4047 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4048 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4049 E = Protocols.end();
4050 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004051 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004052 CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004053
4054 // Add methods in categories.
4055 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4056 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004057 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004058 NumSelIdents, CurContext, Selectors, Results,
4059 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004060
4061 // Add a categories protocol methods.
4062 const ObjCList<ObjCProtocolDecl> &Protocols
4063 = CatDecl->getReferencedProtocols();
4064 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4065 E = Protocols.end();
4066 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004067 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004068 NumSelIdents, CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004069
4070 // Add methods in category implementations.
4071 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004072 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004073 NumSelIdents, CurContext, Selectors, Results,
4074 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004075 }
4076
4077 // Add methods in superclass.
4078 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004079 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregord36adf52010-09-16 16:06:31 +00004080 SelIdents, NumSelIdents, CurContext, Selectors, Results,
4081 false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004082
4083 // Add methods in our implementation, if any.
4084 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004085 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004086 NumSelIdents, CurContext, Selectors, Results,
4087 InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004088}
4089
4090
John McCalld226f652010-08-21 09:40:31 +00004091void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
4092 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004093 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00004094 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004095
4096 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004097 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004098 if (!Class) {
4099 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004100 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004101 Class = Category->getClassInterface();
4102
4103 if (!Class)
4104 return;
4105 }
4106
4107 // Find all of the potential getters.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004108 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004109 Results.EnterNewScope();
4110
4111 // FIXME: We need to do this because Objective-C methods don't get
4112 // pushed into DeclContexts early enough. Argh!
4113 for (unsigned I = 0; I != NumMethods; ++I) {
4114 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00004115 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004116 if (Method->isInstanceMethod() &&
4117 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
4118 Result R = Result(Method, 0);
4119 R.AllParametersAreInformative = true;
4120 Results.MaybeAddResult(R, CurContext);
4121 }
4122 }
4123
Douglas Gregord36adf52010-09-16 16:06:31 +00004124 VisitedSelectorSet Selectors;
4125 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
4126 Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004127 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004128 HandleCodeCompleteResults(this, CodeCompleter,
4129 CodeCompletionContext::CCC_Other,
4130 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004131}
4132
John McCalld226f652010-08-21 09:40:31 +00004133void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
4134 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004135 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00004136 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004137
4138 // Try to find the interface where setters might live.
4139 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004140 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004141 if (!Class) {
4142 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004143 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004144 Class = Category->getClassInterface();
4145
4146 if (!Class)
4147 return;
4148 }
4149
4150 // Find all of the potential getters.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004151 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004152 Results.EnterNewScope();
4153
4154 // FIXME: We need to do this because Objective-C methods don't get
4155 // pushed into DeclContexts early enough. Argh!
4156 for (unsigned I = 0; I != NumMethods; ++I) {
4157 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00004158 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004159 if (Method->isInstanceMethod() &&
4160 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
4161 Result R = Result(Method, 0);
4162 R.AllParametersAreInformative = true;
4163 Results.MaybeAddResult(R, CurContext);
4164 }
4165 }
4166
Douglas Gregord36adf52010-09-16 16:06:31 +00004167 VisitedSelectorSet Selectors;
4168 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4169 Selectors, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004170
4171 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004172 HandleCodeCompleteResults(this, CodeCompleter,
4173 CodeCompletionContext::CCC_Other,
4174 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004175}
4176
Douglas Gregord32b0222010-08-24 01:06:58 +00004177void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00004178 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00004179 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004180 Results.EnterNewScope();
4181
4182 // Add context-sensitive, Objective-C parameter-passing keywords.
4183 bool AddedInOut = false;
4184 if ((DS.getObjCDeclQualifier() &
4185 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4186 Results.AddResult("in");
4187 Results.AddResult("inout");
4188 AddedInOut = true;
4189 }
4190 if ((DS.getObjCDeclQualifier() &
4191 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4192 Results.AddResult("out");
4193 if (!AddedInOut)
4194 Results.AddResult("inout");
4195 }
4196 if ((DS.getObjCDeclQualifier() &
4197 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4198 ObjCDeclSpec::DQ_Oneway)) == 0) {
4199 Results.AddResult("bycopy");
4200 Results.AddResult("byref");
4201 Results.AddResult("oneway");
4202 }
4203
4204 // Add various builtin type names and specifiers.
4205 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4206 Results.ExitScope();
4207
4208 // Add the various type names
4209 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4210 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4211 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4212 CodeCompleter->includeGlobals());
4213
4214 if (CodeCompleter->includeMacros())
4215 AddMacroResults(PP, Results);
4216
4217 HandleCodeCompleteResults(this, CodeCompleter,
4218 CodeCompletionContext::CCC_Type,
4219 Results.data(), Results.size());
4220}
4221
Douglas Gregor22f56992010-04-06 19:22:33 +00004222/// \brief When we have an expression with type "id", we may assume
4223/// that it has some more-specific class type based on knowledge of
4224/// common uses of Objective-C. This routine returns that class type,
4225/// or NULL if no better result could be determined.
4226static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004227 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004228 if (!Msg)
4229 return 0;
4230
4231 Selector Sel = Msg->getSelector();
4232 if (Sel.isNull())
4233 return 0;
4234
4235 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4236 if (!Id)
4237 return 0;
4238
4239 ObjCMethodDecl *Method = Msg->getMethodDecl();
4240 if (!Method)
4241 return 0;
4242
4243 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004244 ObjCInterfaceDecl *IFace = 0;
4245 switch (Msg->getReceiverKind()) {
4246 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004247 if (const ObjCObjectType *ObjType
4248 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4249 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004250 break;
4251
4252 case ObjCMessageExpr::Instance: {
4253 QualType T = Msg->getInstanceReceiver()->getType();
4254 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4255 IFace = Ptr->getInterfaceDecl();
4256 break;
4257 }
4258
4259 case ObjCMessageExpr::SuperInstance:
4260 case ObjCMessageExpr::SuperClass:
4261 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004262 }
4263
4264 if (!IFace)
4265 return 0;
4266
4267 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4268 if (Method->isInstanceMethod())
4269 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4270 .Case("retain", IFace)
4271 .Case("autorelease", IFace)
4272 .Case("copy", IFace)
4273 .Case("copyWithZone", IFace)
4274 .Case("mutableCopy", IFace)
4275 .Case("mutableCopyWithZone", IFace)
4276 .Case("awakeFromCoder", IFace)
4277 .Case("replacementObjectFromCoder", IFace)
4278 .Case("class", IFace)
4279 .Case("classForCoder", IFace)
4280 .Case("superclass", Super)
4281 .Default(0);
4282
4283 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4284 .Case("new", IFace)
4285 .Case("alloc", IFace)
4286 .Case("allocWithZone", IFace)
4287 .Case("class", IFace)
4288 .Case("superclass", Super)
4289 .Default(0);
4290}
4291
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004292// Add a special completion for a message send to "super", which fills in the
4293// most likely case of forwarding all of our arguments to the superclass
4294// function.
4295///
4296/// \param S The semantic analysis object.
4297///
4298/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4299/// the "super" keyword. Otherwise, we just need to provide the arguments.
4300///
4301/// \param SelIdents The identifiers in the selector that have already been
4302/// provided as arguments for a send to "super".
4303///
4304/// \param NumSelIdents The number of identifiers in \p SelIdents.
4305///
4306/// \param Results The set of results to augment.
4307///
4308/// \returns the Objective-C method declaration that would be invoked by
4309/// this "super" completion. If NULL, no completion was added.
4310static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4311 IdentifierInfo **SelIdents,
4312 unsigned NumSelIdents,
4313 ResultBuilder &Results) {
4314 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4315 if (!CurMethod)
4316 return 0;
4317
4318 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4319 if (!Class)
4320 return 0;
4321
4322 // Try to find a superclass method with the same selector.
4323 ObjCMethodDecl *SuperMethod = 0;
4324 while ((Class = Class->getSuperClass()) && !SuperMethod)
4325 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4326 CurMethod->isInstanceMethod());
4327
4328 if (!SuperMethod)
4329 return 0;
4330
4331 // Check whether the superclass method has the same signature.
4332 if (CurMethod->param_size() != SuperMethod->param_size() ||
4333 CurMethod->isVariadic() != SuperMethod->isVariadic())
4334 return 0;
4335
4336 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4337 CurPEnd = CurMethod->param_end(),
4338 SuperP = SuperMethod->param_begin();
4339 CurP != CurPEnd; ++CurP, ++SuperP) {
4340 // Make sure the parameter types are compatible.
4341 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4342 (*SuperP)->getType()))
4343 return 0;
4344
4345 // Make sure we have a parameter name to forward!
4346 if (!(*CurP)->getIdentifier())
4347 return 0;
4348 }
4349
4350 // We have a superclass method. Now, form the send-to-super completion.
4351 CodeCompletionString *Pattern = new CodeCompletionString;
4352
4353 // Give this completion a return type.
4354 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4355
4356 // If we need the "super" keyword, add it (plus some spacing).
4357 if (NeedSuperKeyword) {
4358 Pattern->AddTypedTextChunk("super");
4359 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4360 }
4361
4362 Selector Sel = CurMethod->getSelector();
4363 if (Sel.isUnarySelector()) {
4364 if (NeedSuperKeyword)
4365 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4366 else
4367 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4368 } else {
4369 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4370 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4371 if (I > NumSelIdents)
4372 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4373
4374 if (I < NumSelIdents)
4375 Pattern->AddInformativeChunk(
4376 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4377 else if (NeedSuperKeyword || I > NumSelIdents) {
4378 Pattern->AddTextChunk(
4379 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4380 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4381 } else {
4382 Pattern->AddTypedTextChunk(
4383 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4384 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4385 }
4386 }
4387 }
4388
4389 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4390 SuperMethod->isInstanceMethod()
4391 ? CXCursor_ObjCInstanceMethodDecl
4392 : CXCursor_ObjCClassMethodDecl));
4393 return SuperMethod;
4394}
4395
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004396void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004397 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00004398 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCMessageReceiver,
4399 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004400
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004401 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4402 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004403 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4404 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004405
4406 // If we are in an Objective-C method inside a class that has a superclass,
4407 // add "super" as an option.
4408 if (ObjCMethodDecl *Method = getCurMethodDecl())
4409 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004410 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004411 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004412
4413 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4414 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004415
4416 Results.ExitScope();
4417
4418 if (CodeCompleter->includeMacros())
4419 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004420 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004421 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004422
4423}
4424
Douglas Gregor2725ca82010-04-21 19:57:20 +00004425void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4426 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004427 unsigned NumSelIdents,
4428 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004429 ObjCInterfaceDecl *CDecl = 0;
4430 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4431 // Figure out which interface we're in.
4432 CDecl = CurMethod->getClassInterface();
4433 if (!CDecl)
4434 return;
4435
4436 // Find the superclass of this class.
4437 CDecl = CDecl->getSuperClass();
4438 if (!CDecl)
4439 return;
4440
4441 if (CurMethod->isInstanceMethod()) {
4442 // We are inside an instance method, which means that the message
4443 // send [super ...] is actually calling an instance method on the
4444 // current object. Build the super expression and handle this like
4445 // an instance method.
4446 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
4447 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall60d7b3a2010-08-24 06:29:42 +00004448 ExprResult Super
Douglas Gregor2725ca82010-04-21 19:57:20 +00004449 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
4450 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004451 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004452 AtArgumentExpression,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004453 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004454 }
4455
4456 // Fall through to send to the superclass in CDecl.
4457 } else {
4458 // "super" may be the name of a type or variable. Figure out which
4459 // it is.
4460 IdentifierInfo *Super = &Context.Idents.get("super");
4461 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4462 LookupOrdinaryName);
4463 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4464 // "super" names an interface. Use it.
4465 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004466 if (const ObjCObjectType *Iface
4467 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4468 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004469 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4470 // "super" names an unresolved type; we can't be more specific.
4471 } else {
4472 // Assume that "super" names some kind of value and parse that way.
4473 CXXScopeSpec SS;
4474 UnqualifiedId id;
4475 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004476 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004477 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004478 SelIdents, NumSelIdents,
4479 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004480 }
4481
4482 // Fall through
4483 }
4484
John McCallb3d87482010-08-24 05:47:05 +00004485 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004486 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004487 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004488 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004489 NumSelIdents, AtArgumentExpression,
4490 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004491}
4492
Douglas Gregorb9d77572010-09-21 00:03:25 +00004493/// \brief Given a set of code-completion results for the argument of a message
4494/// send, determine the preferred type (if any) for that argument expression.
4495static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4496 unsigned NumSelIdents) {
4497 typedef CodeCompletionResult Result;
4498 ASTContext &Context = Results.getSema().Context;
4499
4500 QualType PreferredType;
4501 unsigned BestPriority = CCP_Unlikely * 2;
4502 Result *ResultsData = Results.data();
4503 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4504 Result &R = ResultsData[I];
4505 if (R.Kind == Result::RK_Declaration &&
4506 isa<ObjCMethodDecl>(R.Declaration)) {
4507 if (R.Priority <= BestPriority) {
4508 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4509 if (NumSelIdents <= Method->param_size()) {
4510 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4511 ->getType();
4512 if (R.Priority < BestPriority || PreferredType.isNull()) {
4513 BestPriority = R.Priority;
4514 PreferredType = MyPreferredType;
4515 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4516 MyPreferredType)) {
4517 PreferredType = QualType();
4518 }
4519 }
4520 }
4521 }
4522 }
4523
4524 return PreferredType;
4525}
4526
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004527static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4528 ParsedType Receiver,
4529 IdentifierInfo **SelIdents,
4530 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004531 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004532 bool IsSuper,
4533 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004534 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004535 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004536
Douglas Gregor24a069f2009-11-17 17:59:40 +00004537 // If the given name refers to an interface type, retrieve the
4538 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004539 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004540 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004541 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004542 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4543 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004544 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004545
Douglas Gregor36ecb042009-11-17 23:22:23 +00004546 // Add all of the factory methods in this Objective-C class, its protocols,
4547 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004548 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004549
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004550 // If this is a send-to-super, try to add the special "super" send
4551 // completion.
4552 if (IsSuper) {
4553 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004554 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4555 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004556 Results.Ignore(SuperMethod);
4557 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004558
Douglas Gregor265f7492010-08-27 15:29:55 +00004559 // If we're inside an Objective-C method definition, prefer its selector to
4560 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004561 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004562 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004563
Douglas Gregord36adf52010-09-16 16:06:31 +00004564 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004565 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004566 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004567 SemaRef.CurContext, Selectors, Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004568 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004569 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004570
Douglas Gregor719770d2010-04-06 17:30:22 +00004571 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004572 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004573 if (SemaRef.ExternalSource) {
4574 for (uint32_t I = 0,
4575 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004576 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004577 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4578 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004579 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004580
4581 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004582 }
4583 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004584
4585 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4586 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004587 M != MEnd; ++M) {
4588 for (ObjCMethodList *MethList = &M->second.second;
4589 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004590 MethList = MethList->Next) {
4591 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4592 NumSelIdents))
4593 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004594
Douglas Gregor13438f92010-04-06 16:40:00 +00004595 Result R(MethList->Method, 0);
4596 R.StartParameter = NumSelIdents;
4597 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004598 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004599 }
4600 }
4601 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004602
4603 Results.ExitScope();
4604}
Douglas Gregor13438f92010-04-06 16:40:00 +00004605
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004606void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4607 IdentifierInfo **SelIdents,
4608 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004609 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004610 bool IsSuper) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004611 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004612 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4613 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004614
4615 // If we're actually at the argument expression (rather than prior to the
4616 // selector), we're actually performing code completion for an expression.
4617 // Determine whether we have a single, best method. If so, we can
4618 // code-complete the expression using the corresponding parameter type as
4619 // our preferred type, improving completion results.
4620 if (AtArgumentExpression) {
4621 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4622 NumSelIdents);
4623 if (PreferredType.isNull())
4624 CodeCompleteOrdinaryName(S, PCC_Expression);
4625 else
4626 CodeCompleteExpression(S, PreferredType);
4627 return;
4628 }
4629
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004630 HandleCodeCompleteResults(this, CodeCompleter,
4631 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004632 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004633}
4634
Douglas Gregord3c68542009-11-19 01:08:35 +00004635void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4636 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004637 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004638 bool AtArgumentExpression,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004639 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004640 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004641
4642 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004643
Douglas Gregor36ecb042009-11-17 23:22:23 +00004644 // If necessary, apply function/array conversion to the receiver.
4645 // C99 6.7.5.3p[7,8].
Douglas Gregor78edf512010-09-15 16:23:04 +00004646 if (RecExpr)
4647 DefaultFunctionArrayLvalueConversion(RecExpr);
4648 QualType ReceiverType = RecExpr? RecExpr->getType() : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004649
Douglas Gregor36ecb042009-11-17 23:22:23 +00004650 // Build the set of methods we can see.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004651 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004652 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004653
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004654 // If this is a send-to-super, try to add the special "super" send
4655 // completion.
4656 if (IsSuper) {
4657 if (ObjCMethodDecl *SuperMethod
4658 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4659 Results))
4660 Results.Ignore(SuperMethod);
4661 }
4662
Douglas Gregor265f7492010-08-27 15:29:55 +00004663 // If we're inside an Objective-C method definition, prefer its selector to
4664 // others.
4665 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4666 Results.setPreferredSelector(CurMethod->getSelector());
4667
Douglas Gregor22f56992010-04-06 19:22:33 +00004668 // If we're messaging an expression with type "id" or "Class", check
4669 // whether we know something special about the receiver that allows
4670 // us to assume a more-specific receiver type.
4671 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4672 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4673 ReceiverType = Context.getObjCObjectPointerType(
4674 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00004675
Douglas Gregord36adf52010-09-16 16:06:31 +00004676 // Keep track of the selectors we've already added.
4677 VisitedSelectorSet Selectors;
4678
Douglas Gregorf74a4192009-11-18 00:06:18 +00004679 // Handle messages to Class. This really isn't a message to an instance
4680 // method, so we treat it the same way we would treat a message send to a
4681 // class method.
4682 if (ReceiverType->isObjCClassType() ||
4683 ReceiverType->isObjCQualifiedClassType()) {
4684 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4685 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004686 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004687 CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004688 }
4689 }
4690 // Handle messages to a qualified ID ("id<foo>").
4691 else if (const ObjCObjectPointerType *QualID
4692 = ReceiverType->getAsObjCQualifiedIdType()) {
4693 // Search protocols for instance methods.
4694 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4695 E = QualID->qual_end();
4696 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004697 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004698 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004699 }
4700 // Handle messages to a pointer to interface type.
4701 else if (const ObjCObjectPointerType *IFacePtr
4702 = ReceiverType->getAsObjCInterfacePointerType()) {
4703 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004704 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004705 NumSelIdents, CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004706
4707 // Search protocols for instance methods.
4708 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4709 E = IFacePtr->qual_end();
4710 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004711 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004712 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004713 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004714 // Handle messages to "id".
4715 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004716 // We're messaging "id", so provide all instance methods we know
4717 // about as code-completion results.
4718
4719 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004720 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004721 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004722 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4723 I != N; ++I) {
4724 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004725 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004726 continue;
4727
Sebastian Redldb9d2142010-08-02 23:18:59 +00004728 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004729 }
4730 }
4731
Sebastian Redldb9d2142010-08-02 23:18:59 +00004732 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4733 MEnd = MethodPool.end();
4734 M != MEnd; ++M) {
4735 for (ObjCMethodList *MethList = &M->second.first;
4736 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004737 MethList = MethList->Next) {
4738 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4739 NumSelIdents))
4740 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00004741
4742 if (!Selectors.insert(MethList->Method->getSelector()))
4743 continue;
4744
Douglas Gregor13438f92010-04-06 16:40:00 +00004745 Result R(MethList->Method, 0);
4746 R.StartParameter = NumSelIdents;
4747 R.AllParametersAreInformative = false;
4748 Results.MaybeAddResult(R, CurContext);
4749 }
4750 }
4751 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00004752 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00004753
4754
4755 // If we're actually at the argument expression (rather than prior to the
4756 // selector), we're actually performing code completion for an expression.
4757 // Determine whether we have a single, best method. If so, we can
4758 // code-complete the expression using the corresponding parameter type as
4759 // our preferred type, improving completion results.
4760 if (AtArgumentExpression) {
4761 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4762 NumSelIdents);
4763 if (PreferredType.isNull())
4764 CodeCompleteOrdinaryName(S, PCC_Expression);
4765 else
4766 CodeCompleteExpression(S, PreferredType);
4767 return;
4768 }
4769
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004770 HandleCodeCompleteResults(this, CodeCompleter,
4771 CodeCompletionContext::CCC_Other,
4772 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004773}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004774
Douglas Gregorfb629412010-08-23 21:17:50 +00004775void Sema::CodeCompleteObjCForCollection(Scope *S,
4776 DeclGroupPtrTy IterationVar) {
4777 CodeCompleteExpressionData Data;
4778 Data.ObjCCollection = true;
4779
4780 if (IterationVar.getAsOpaquePtr()) {
4781 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4782 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4783 if (*I)
4784 Data.IgnoreDecls.push_back(*I);
4785 }
4786 }
4787
4788 CodeCompleteExpression(S, Data);
4789}
4790
Douglas Gregor458433d2010-08-26 15:07:07 +00004791void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4792 unsigned NumSelIdents) {
4793 // If we have an external source, load the entire class method
4794 // pool from the AST file.
4795 if (ExternalSource) {
4796 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4797 I != N; ++I) {
4798 Selector Sel = ExternalSource->GetExternalSelector(I);
4799 if (Sel.isNull() || MethodPool.count(Sel))
4800 continue;
4801
4802 ReadMethodPool(Sel);
4803 }
4804 }
4805
Douglas Gregor52779fb2010-09-23 23:01:17 +00004806 ResultBuilder Results(*this, CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00004807 Results.EnterNewScope();
4808 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4809 MEnd = MethodPool.end();
4810 M != MEnd; ++M) {
4811
4812 Selector Sel = M->first;
4813 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4814 continue;
4815
4816 CodeCompletionString *Pattern = new CodeCompletionString;
4817 if (Sel.isUnarySelector()) {
4818 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4819 Results.AddResult(Pattern);
4820 continue;
4821 }
4822
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004823 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004824 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004825 if (I == NumSelIdents) {
4826 if (!Accumulator.empty()) {
4827 Pattern->AddInformativeChunk(Accumulator);
4828 Accumulator.clear();
4829 }
4830 }
4831
4832 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4833 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004834 }
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004835 Pattern->AddTypedTextChunk(Accumulator);
Douglas Gregor458433d2010-08-26 15:07:07 +00004836 Results.AddResult(Pattern);
4837 }
4838 Results.ExitScope();
4839
4840 HandleCodeCompleteResults(this, CodeCompleter,
4841 CodeCompletionContext::CCC_SelectorName,
4842 Results.data(), Results.size());
4843}
4844
Douglas Gregor55385fe2009-11-18 04:19:12 +00004845/// \brief Add all of the protocol declarations that we find in the given
4846/// (translation unit) context.
4847static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004848 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004849 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004850 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004851
4852 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4853 DEnd = Ctx->decls_end();
4854 D != DEnd; ++D) {
4855 // Record any protocols we find.
4856 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004857 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004858 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004859
4860 // Record any forward-declared protocols we find.
4861 if (ObjCForwardProtocolDecl *Forward
4862 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4863 for (ObjCForwardProtocolDecl::protocol_iterator
4864 P = Forward->protocol_begin(),
4865 PEnd = Forward->protocol_end();
4866 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004867 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004868 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004869 }
4870 }
4871}
4872
4873void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4874 unsigned NumProtocols) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004875 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004876 Results.EnterNewScope();
4877
4878 // Tell the result set to ignore all of the protocols we have
4879 // already seen.
4880 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004881 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4882 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004883 Results.Ignore(Protocol);
4884
4885 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004886 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4887 Results);
4888
4889 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004890 HandleCodeCompleteResults(this, CodeCompleter,
4891 CodeCompletionContext::CCC_ObjCProtocolName,
4892 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004893}
4894
4895void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004896 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00004897 Results.EnterNewScope();
4898
4899 // Add all protocols.
4900 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4901 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004902
4903 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004904 HandleCodeCompleteResults(this, CodeCompleter,
4905 CodeCompletionContext::CCC_ObjCProtocolName,
4906 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004907}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004908
4909/// \brief Add all of the Objective-C interface declarations that we find in
4910/// the given (translation unit) context.
4911static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4912 bool OnlyForwardDeclarations,
4913 bool OnlyUnimplemented,
4914 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004915 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004916
4917 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4918 DEnd = Ctx->decls_end();
4919 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004920 // Record any interfaces we find.
4921 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4922 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4923 (!OnlyUnimplemented || !Class->getImplementation()))
4924 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004925
4926 // Record any forward-declared interfaces we find.
4927 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4928 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004929 C != CEnd; ++C)
4930 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4931 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4932 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004933 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004934 }
4935 }
4936}
4937
4938void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004939 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004940 Results.EnterNewScope();
4941
4942 // Add all classes.
4943 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4944 false, Results);
4945
4946 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00004947 // FIXME: Add a special context for this, use cached global completion
4948 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004949 HandleCodeCompleteResults(this, CodeCompleter,
4950 CodeCompletionContext::CCC_Other,
4951 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004952}
4953
Douglas Gregorc83c6872010-04-15 22:33:43 +00004954void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4955 SourceLocation ClassNameLoc) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004956 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004957 Results.EnterNewScope();
4958
4959 // Make sure that we ignore the class we're currently defining.
4960 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004961 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004962 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004963 Results.Ignore(CurClass);
4964
4965 // Add all classes.
4966 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4967 false, Results);
4968
4969 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00004970 // FIXME: Add a special context for this, use cached global completion
4971 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004972 HandleCodeCompleteResults(this, CodeCompleter,
4973 CodeCompletionContext::CCC_Other,
4974 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004975}
4976
4977void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004978 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004979 Results.EnterNewScope();
4980
4981 // Add all unimplemented classes.
4982 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4983 true, Results);
4984
4985 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00004986 // FIXME: Add a special context for this, use cached global completion
4987 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004988 HandleCodeCompleteResults(this, CodeCompleter,
4989 CodeCompletionContext::CCC_Other,
4990 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004991}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004992
4993void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004994 IdentifierInfo *ClassName,
4995 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004996 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004997
Douglas Gregor52779fb2010-09-23 23:01:17 +00004998 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004999
5000 // Ignore any categories we find that have already been implemented by this
5001 // interface.
5002 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5003 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005004 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005005 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5006 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5007 Category = Category->getNextClassCategory())
5008 CategoryNames.insert(Category->getIdentifier());
5009
5010 // Add all of the categories we know about.
5011 Results.EnterNewScope();
5012 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5013 for (DeclContext::decl_iterator D = TU->decls_begin(),
5014 DEnd = TU->decls_end();
5015 D != DEnd; ++D)
5016 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5017 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005018 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005019 Results.ExitScope();
5020
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005021 HandleCodeCompleteResults(this, CodeCompleter,
5022 CodeCompletionContext::CCC_Other,
5023 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005024}
5025
5026void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005027 IdentifierInfo *ClassName,
5028 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005029 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005030
5031 // Find the corresponding interface. If we couldn't find the interface, the
5032 // program itself is ill-formed. However, we'll try to be helpful still by
5033 // providing the list of all of the categories we know about.
5034 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005035 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005036 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5037 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005038 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005039
Douglas Gregor52779fb2010-09-23 23:01:17 +00005040 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005041
5042 // Add all of the categories that have have corresponding interface
5043 // declarations in this class and any of its superclasses, except for
5044 // already-implemented categories in the class itself.
5045 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5046 Results.EnterNewScope();
5047 bool IgnoreImplemented = true;
5048 while (Class) {
5049 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5050 Category = Category->getNextClassCategory())
5051 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5052 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005053 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005054
5055 Class = Class->getSuperClass();
5056 IgnoreImplemented = false;
5057 }
5058 Results.ExitScope();
5059
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005060 HandleCodeCompleteResults(this, CodeCompleter,
5061 CodeCompletionContext::CCC_Other,
5062 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005063}
Douglas Gregor322328b2009-11-18 22:32:06 +00005064
John McCalld226f652010-08-21 09:40:31 +00005065void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005066 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005067 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005068
5069 // Figure out where this @synthesize lives.
5070 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005071 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005072 if (!Container ||
5073 (!isa<ObjCImplementationDecl>(Container) &&
5074 !isa<ObjCCategoryImplDecl>(Container)))
5075 return;
5076
5077 // Ignore any properties that have already been implemented.
5078 for (DeclContext::decl_iterator D = Container->decls_begin(),
5079 DEnd = Container->decls_end();
5080 D != DEnd; ++D)
5081 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5082 Results.Ignore(PropertyImpl->getPropertyDecl());
5083
5084 // Add any properties that we find.
5085 Results.EnterNewScope();
5086 if (ObjCImplementationDecl *ClassImpl
5087 = dyn_cast<ObjCImplementationDecl>(Container))
5088 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
5089 Results);
5090 else
5091 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
5092 false, CurContext, Results);
5093 Results.ExitScope();
5094
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005095 HandleCodeCompleteResults(this, CodeCompleter,
5096 CodeCompletionContext::CCC_Other,
5097 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005098}
5099
5100void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5101 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005102 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005103 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005104 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005105
5106 // Figure out where this @synthesize lives.
5107 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005108 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005109 if (!Container ||
5110 (!isa<ObjCImplementationDecl>(Container) &&
5111 !isa<ObjCCategoryImplDecl>(Container)))
5112 return;
5113
5114 // Figure out which interface we're looking into.
5115 ObjCInterfaceDecl *Class = 0;
5116 if (ObjCImplementationDecl *ClassImpl
5117 = dyn_cast<ObjCImplementationDecl>(Container))
5118 Class = ClassImpl->getClassInterface();
5119 else
5120 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5121 ->getClassInterface();
5122
5123 // Add all of the instance variables in this class and its superclasses.
5124 Results.EnterNewScope();
5125 for(; Class; Class = Class->getSuperClass()) {
5126 // FIXME: We could screen the type of each ivar for compatibility with
5127 // the property, but is that being too paternal?
5128 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
5129 IVarEnd = Class->ivar_end();
5130 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00005131 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00005132 }
5133 Results.ExitScope();
5134
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005135 HandleCodeCompleteResults(this, CodeCompleter,
5136 CodeCompletionContext::CCC_Other,
5137 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005138}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005139
Douglas Gregor408be5a2010-08-25 01:08:01 +00005140// Mapping from selectors to the methods that implement that selector, along
5141// with the "in original class" flag.
5142typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5143 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005144
5145/// \brief Find all of the methods that reside in the given container
5146/// (and its superclasses, protocols, etc.) that meet the given
5147/// criteria. Insert those methods into the map of known methods,
5148/// indexed by selector so they can be easily found.
5149static void FindImplementableMethods(ASTContext &Context,
5150 ObjCContainerDecl *Container,
5151 bool WantInstanceMethods,
5152 QualType ReturnType,
5153 bool IsInImplementation,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005154 KnownMethodsMap &KnownMethods,
5155 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005156 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5157 // Recurse into protocols.
5158 const ObjCList<ObjCProtocolDecl> &Protocols
5159 = IFace->getReferencedProtocols();
5160 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5161 E = Protocols.end();
5162 I != E; ++I)
5163 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005164 IsInImplementation, KnownMethods,
5165 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005166
5167 // If we're not in the implementation of a class, also visit the
5168 // superclass.
5169 if (!IsInImplementation && IFace->getSuperClass())
5170 FindImplementableMethods(Context, IFace->getSuperClass(),
5171 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005172 IsInImplementation, KnownMethods,
5173 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005174
5175 // Add methods from any class extensions (but not from categories;
5176 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005177 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
5178 Cat = Cat->getNextClassExtension())
5179 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5180 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005181 IsInImplementation, KnownMethods,
5182 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005183 }
5184
5185 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5186 // Recurse into protocols.
5187 const ObjCList<ObjCProtocolDecl> &Protocols
5188 = Category->getReferencedProtocols();
5189 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5190 E = Protocols.end();
5191 I != E; ++I)
5192 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005193 IsInImplementation, KnownMethods,
5194 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005195 }
5196
5197 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5198 // Recurse into protocols.
5199 const ObjCList<ObjCProtocolDecl> &Protocols
5200 = Protocol->getReferencedProtocols();
5201 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5202 E = Protocols.end();
5203 I != E; ++I)
5204 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005205 IsInImplementation, KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005206 }
5207
5208 // Add methods in this container. This operation occurs last because
5209 // we want the methods from this container to override any methods
5210 // we've previously seen with the same selector.
5211 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5212 MEnd = Container->meth_end();
5213 M != MEnd; ++M) {
5214 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5215 if (!ReturnType.isNull() &&
5216 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5217 continue;
5218
Douglas Gregor408be5a2010-08-25 01:08:01 +00005219 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005220 }
5221 }
5222}
5223
5224void Sema::CodeCompleteObjCMethodDecl(Scope *S,
5225 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00005226 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00005227 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005228 // Determine the return type of the method we're declaring, if
5229 // provided.
5230 QualType ReturnType = GetTypeFromParser(ReturnTy);
5231
5232 // Determine where we should start searching for methods, and where we
5233 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
5234 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00005235 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005236 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
5237 SearchDecl = Impl->getClassInterface();
5238 CurrentDecl = Impl;
5239 IsInImplementation = true;
5240 } else if (ObjCCategoryImplDecl *CatImpl
5241 = dyn_cast<ObjCCategoryImplDecl>(D)) {
5242 SearchDecl = CatImpl->getCategoryDecl();
5243 CurrentDecl = CatImpl;
5244 IsInImplementation = true;
5245 } else {
5246 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
5247 CurrentDecl = SearchDecl;
5248 }
5249 }
5250
5251 if (!SearchDecl && S) {
5252 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
5253 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
5254 CurrentDecl = SearchDecl;
5255 }
5256 }
5257
5258 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005259 HandleCodeCompleteResults(this, CodeCompleter,
5260 CodeCompletionContext::CCC_Other,
5261 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005262 return;
5263 }
5264
5265 // Find all of the methods that we could declare/implement here.
5266 KnownMethodsMap KnownMethods;
5267 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
5268 ReturnType, IsInImplementation, KnownMethods);
5269
5270 // Erase any methods that have already been declared or
5271 // implemented here.
5272 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
5273 MEnd = CurrentDecl->meth_end();
5274 M != MEnd; ++M) {
5275 if ((*M)->isInstanceMethod() != IsInstanceMethod)
5276 continue;
5277
5278 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
5279 if (Pos != KnownMethods.end())
5280 KnownMethods.erase(Pos);
5281 }
5282
5283 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00005284 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005285 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005286 Results.EnterNewScope();
5287 PrintingPolicy Policy(Context.PrintingPolicy);
5288 Policy.AnonymousTagLocations = false;
5289 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
5290 MEnd = KnownMethods.end();
5291 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00005292 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005293 CodeCompletionString *Pattern = new CodeCompletionString;
5294
5295 // If the result type was not already provided, add it to the
5296 // pattern as (type).
5297 if (ReturnType.isNull()) {
5298 std::string TypeStr;
5299 Method->getResultType().getAsStringInternal(TypeStr, Policy);
5300 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5301 Pattern->AddTextChunk(TypeStr);
5302 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5303 }
5304
5305 Selector Sel = Method->getSelector();
5306
5307 // Add the first part of the selector to the pattern.
5308 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
5309
5310 // Add parameters to the pattern.
5311 unsigned I = 0;
5312 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5313 PEnd = Method->param_end();
5314 P != PEnd; (void)++P, ++I) {
5315 // Add the part of the selector name.
5316 if (I == 0)
5317 Pattern->AddChunk(CodeCompletionString::CK_Colon);
5318 else if (I < Sel.getNumArgs()) {
5319 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor47c03a72010-08-17 15:53:35 +00005320 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005321 Pattern->AddChunk(CodeCompletionString::CK_Colon);
5322 } else
5323 break;
5324
5325 // Add the parameter type.
5326 std::string TypeStr;
5327 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
5328 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5329 Pattern->AddTextChunk(TypeStr);
5330 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5331
5332 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregore17794f2010-08-31 05:13:43 +00005333 Pattern->AddTextChunk(Id->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005334 }
5335
5336 if (Method->isVariadic()) {
5337 if (Method->param_size() > 0)
5338 Pattern->AddChunk(CodeCompletionString::CK_Comma);
5339 Pattern->AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00005340 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005341
Douglas Gregor447107d2010-05-28 00:57:46 +00005342 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005343 // We will be defining the method here, so add a compound statement.
5344 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5345 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
5346 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5347 if (!Method->getResultType()->isVoidType()) {
5348 // If the result type is not void, add a return clause.
5349 Pattern->AddTextChunk("return");
5350 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5351 Pattern->AddPlaceholderChunk("expression");
5352 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
5353 } else
5354 Pattern->AddPlaceholderChunk("statements");
5355
5356 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5357 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
5358 }
5359
Douglas Gregor408be5a2010-08-25 01:08:01 +00005360 unsigned Priority = CCP_CodePattern;
5361 if (!M->second.second)
5362 Priority += CCD_InBaseClass;
5363
5364 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00005365 Method->isInstanceMethod()
5366 ? CXCursor_ObjCInstanceMethodDecl
5367 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005368 }
5369
5370 Results.ExitScope();
5371
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005372 HandleCodeCompleteResults(this, CodeCompleter,
5373 CodeCompletionContext::CCC_Other,
5374 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005375}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005376
5377void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5378 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005379 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00005380 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005381 IdentifierInfo **SelIdents,
5382 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005383 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005384 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005385 if (ExternalSource) {
5386 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5387 I != N; ++I) {
5388 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005389 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005390 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00005391
5392 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005393 }
5394 }
5395
5396 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00005397 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005398 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005399
5400 if (ReturnTy)
5401 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00005402
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005403 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005404 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5405 MEnd = MethodPool.end();
5406 M != MEnd; ++M) {
5407 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5408 &M->second.second;
5409 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005410 MethList = MethList->Next) {
5411 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5412 NumSelIdents))
5413 continue;
5414
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005415 if (AtParameterName) {
5416 // Suggest parameter names we've seen before.
5417 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5418 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5419 if (Param->getIdentifier()) {
5420 CodeCompletionString *Pattern = new CodeCompletionString;
5421 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5422 Results.AddResult(Pattern);
5423 }
5424 }
5425
5426 continue;
5427 }
5428
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005429 Result R(MethList->Method, 0);
5430 R.StartParameter = NumSelIdents;
5431 R.AllParametersAreInformative = false;
5432 R.DeclaringEntity = true;
5433 Results.MaybeAddResult(R, CurContext);
5434 }
5435 }
5436
5437 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005438 HandleCodeCompleteResults(this, CodeCompleter,
5439 CodeCompletionContext::CCC_Other,
5440 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005441}
Douglas Gregor87c08a52010-08-13 22:48:40 +00005442
Douglas Gregorf29c5232010-08-24 22:20:20 +00005443void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005444 ResultBuilder Results(*this,
5445 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005446 Results.EnterNewScope();
5447
5448 // #if <condition>
5449 CodeCompletionString *Pattern = new CodeCompletionString;
5450 Pattern->AddTypedTextChunk("if");
5451 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5452 Pattern->AddPlaceholderChunk("condition");
5453 Results.AddResult(Pattern);
5454
5455 // #ifdef <macro>
5456 Pattern = new CodeCompletionString;
5457 Pattern->AddTypedTextChunk("ifdef");
5458 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5459 Pattern->AddPlaceholderChunk("macro");
5460 Results.AddResult(Pattern);
5461
5462 // #ifndef <macro>
5463 Pattern = new CodeCompletionString;
5464 Pattern->AddTypedTextChunk("ifndef");
5465 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5466 Pattern->AddPlaceholderChunk("macro");
5467 Results.AddResult(Pattern);
5468
5469 if (InConditional) {
5470 // #elif <condition>
5471 Pattern = new CodeCompletionString;
5472 Pattern->AddTypedTextChunk("elif");
5473 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5474 Pattern->AddPlaceholderChunk("condition");
5475 Results.AddResult(Pattern);
5476
5477 // #else
5478 Pattern = new CodeCompletionString;
5479 Pattern->AddTypedTextChunk("else");
5480 Results.AddResult(Pattern);
5481
5482 // #endif
5483 Pattern = new CodeCompletionString;
5484 Pattern->AddTypedTextChunk("endif");
5485 Results.AddResult(Pattern);
5486 }
5487
5488 // #include "header"
5489 Pattern = new CodeCompletionString;
5490 Pattern->AddTypedTextChunk("include");
5491 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5492 Pattern->AddTextChunk("\"");
5493 Pattern->AddPlaceholderChunk("header");
5494 Pattern->AddTextChunk("\"");
5495 Results.AddResult(Pattern);
5496
5497 // #include <header>
5498 Pattern = new CodeCompletionString;
5499 Pattern->AddTypedTextChunk("include");
5500 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5501 Pattern->AddTextChunk("<");
5502 Pattern->AddPlaceholderChunk("header");
5503 Pattern->AddTextChunk(">");
5504 Results.AddResult(Pattern);
5505
5506 // #define <macro>
5507 Pattern = new CodeCompletionString;
5508 Pattern->AddTypedTextChunk("define");
5509 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5510 Pattern->AddPlaceholderChunk("macro");
5511 Results.AddResult(Pattern);
5512
5513 // #define <macro>(<args>)
5514 Pattern = new CodeCompletionString;
5515 Pattern->AddTypedTextChunk("define");
5516 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5517 Pattern->AddPlaceholderChunk("macro");
5518 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5519 Pattern->AddPlaceholderChunk("args");
5520 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5521 Results.AddResult(Pattern);
5522
5523 // #undef <macro>
5524 Pattern = new CodeCompletionString;
5525 Pattern->AddTypedTextChunk("undef");
5526 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5527 Pattern->AddPlaceholderChunk("macro");
5528 Results.AddResult(Pattern);
5529
5530 // #line <number>
5531 Pattern = new CodeCompletionString;
5532 Pattern->AddTypedTextChunk("line");
5533 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5534 Pattern->AddPlaceholderChunk("number");
5535 Results.AddResult(Pattern);
5536
5537 // #line <number> "filename"
5538 Pattern = new CodeCompletionString;
5539 Pattern->AddTypedTextChunk("line");
5540 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5541 Pattern->AddPlaceholderChunk("number");
5542 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5543 Pattern->AddTextChunk("\"");
5544 Pattern->AddPlaceholderChunk("filename");
5545 Pattern->AddTextChunk("\"");
5546 Results.AddResult(Pattern);
5547
5548 // #error <message>
5549 Pattern = new CodeCompletionString;
5550 Pattern->AddTypedTextChunk("error");
5551 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5552 Pattern->AddPlaceholderChunk("message");
5553 Results.AddResult(Pattern);
5554
5555 // #pragma <arguments>
5556 Pattern = new CodeCompletionString;
5557 Pattern->AddTypedTextChunk("pragma");
5558 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5559 Pattern->AddPlaceholderChunk("arguments");
5560 Results.AddResult(Pattern);
5561
5562 if (getLangOptions().ObjC1) {
5563 // #import "header"
5564 Pattern = new CodeCompletionString;
5565 Pattern->AddTypedTextChunk("import");
5566 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5567 Pattern->AddTextChunk("\"");
5568 Pattern->AddPlaceholderChunk("header");
5569 Pattern->AddTextChunk("\"");
5570 Results.AddResult(Pattern);
5571
5572 // #import <header>
5573 Pattern = new CodeCompletionString;
5574 Pattern->AddTypedTextChunk("import");
5575 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5576 Pattern->AddTextChunk("<");
5577 Pattern->AddPlaceholderChunk("header");
5578 Pattern->AddTextChunk(">");
5579 Results.AddResult(Pattern);
5580 }
5581
5582 // #include_next "header"
5583 Pattern = new CodeCompletionString;
5584 Pattern->AddTypedTextChunk("include_next");
5585 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5586 Pattern->AddTextChunk("\"");
5587 Pattern->AddPlaceholderChunk("header");
5588 Pattern->AddTextChunk("\"");
5589 Results.AddResult(Pattern);
5590
5591 // #include_next <header>
5592 Pattern = new CodeCompletionString;
5593 Pattern->AddTypedTextChunk("include_next");
5594 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5595 Pattern->AddTextChunk("<");
5596 Pattern->AddPlaceholderChunk("header");
5597 Pattern->AddTextChunk(">");
5598 Results.AddResult(Pattern);
5599
5600 // #warning <message>
5601 Pattern = new CodeCompletionString;
5602 Pattern->AddTypedTextChunk("warning");
5603 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5604 Pattern->AddPlaceholderChunk("message");
5605 Results.AddResult(Pattern);
5606
5607 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5608 // completions for them. And __include_macros is a Clang-internal extension
5609 // that we don't want to encourage anyone to use.
5610
5611 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5612 Results.ExitScope();
5613
Douglas Gregorf44e8542010-08-24 19:08:16 +00005614 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005615 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005616 Results.data(), Results.size());
5617}
5618
5619void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005620 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005621 S->getFnParent()? Sema::PCC_RecoveryInFunction
5622 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005623}
5624
Douglas Gregorf29c5232010-08-24 22:20:20 +00005625void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005626 ResultBuilder Results(*this,
5627 IsDefinition? CodeCompletionContext::CCC_MacroName
5628 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005629 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5630 // Add just the names of macros, not their arguments.
5631 Results.EnterNewScope();
5632 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5633 MEnd = PP.macro_end();
5634 M != MEnd; ++M) {
5635 CodeCompletionString *Pattern = new CodeCompletionString;
5636 Pattern->AddTypedTextChunk(M->first->getName());
5637 Results.AddResult(Pattern);
5638 }
5639 Results.ExitScope();
5640 } else if (IsDefinition) {
5641 // FIXME: Can we detect when the user just wrote an include guard above?
5642 }
5643
Douglas Gregor52779fb2010-09-23 23:01:17 +00005644 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005645 Results.data(), Results.size());
5646}
5647
Douglas Gregorf29c5232010-08-24 22:20:20 +00005648void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005649 ResultBuilder Results(*this,
5650 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005651
5652 if (!CodeCompleter || CodeCompleter->includeMacros())
5653 AddMacroResults(PP, Results);
5654
5655 // defined (<macro>)
5656 Results.EnterNewScope();
5657 CodeCompletionString *Pattern = new CodeCompletionString;
5658 Pattern->AddTypedTextChunk("defined");
5659 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5660 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5661 Pattern->AddPlaceholderChunk("macro");
5662 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5663 Results.AddResult(Pattern);
5664 Results.ExitScope();
5665
5666 HandleCodeCompleteResults(this, CodeCompleter,
5667 CodeCompletionContext::CCC_PreprocessorExpression,
5668 Results.data(), Results.size());
5669}
5670
5671void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5672 IdentifierInfo *Macro,
5673 MacroInfo *MacroInfo,
5674 unsigned Argument) {
5675 // FIXME: In the future, we could provide "overload" results, much like we
5676 // do for function calls.
5677
5678 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005679 S->getFnParent()? Sema::PCC_RecoveryInFunction
5680 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005681}
5682
Douglas Gregor55817af2010-08-25 17:04:25 +00005683void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005684 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005685 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005686 0, 0);
5687}
5688
Douglas Gregor87c08a52010-08-13 22:48:40 +00005689void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00005690 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005691 ResultBuilder Builder(*this, CodeCompletionContext::CCC_Recovery);
Douglas Gregor87c08a52010-08-13 22:48:40 +00005692
Douglas Gregor8071e422010-08-15 06:18:01 +00005693 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5694 CodeCompletionDeclConsumer Consumer(Builder,
5695 Context.getTranslationUnitDecl());
5696 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5697 Consumer);
5698 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005699
5700 if (!CodeCompleter || CodeCompleter->includeMacros())
5701 AddMacroResults(PP, Builder);
5702
5703 Results.clear();
5704 Results.insert(Results.end(),
5705 Builder.data(), Builder.data() + Builder.size());
5706}