blob: c245e38bb408bd7b5880f66b3a6f79652369499c [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 Gregorca45da02010-11-02 20:36:02 +0000150 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000151 CodeCompletionContext CompletionContext;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief If we are in an instance method definition, the @implementation
154 /// object.
155 ObjCImplementationDecl *ObjCImplementation;
156
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000157 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000158
Douglas Gregor6f942b22010-09-21 16:06:22 +0000159 void MaybeAddConstructorResults(Result R);
160
Douglas Gregor86d9a522009-09-21 16:56:56 +0000161 public:
Douglas Gregor52779fb2010-09-23 23:01:17 +0000162 explicit ResultBuilder(Sema &SemaRef,
163 const CodeCompletionContext &CompletionContext,
164 LookupFilter Filter = 0)
Douglas Gregor3cdee122010-08-26 16:36:48 +0000165 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000166 HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000167 CompletionContext(CompletionContext),
168 ObjCImplementation(0)
169 {
170 // If this is an Objective-C instance method definition, dig out the
171 // corresponding implementation.
172 switch (CompletionContext.getKind()) {
173 case CodeCompletionContext::CCC_Expression:
174 case CodeCompletionContext::CCC_ObjCMessageReceiver:
175 case CodeCompletionContext::CCC_ParenthesizedExpression:
176 case CodeCompletionContext::CCC_Statement:
177 case CodeCompletionContext::CCC_Recovery:
178 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
179 if (Method->isInstanceMethod())
180 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
181 ObjCImplementation = Interface->getImplementation();
182 break;
183
184 default:
185 break;
186 }
187 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000188
Douglas Gregord8e8a582010-05-25 21:41:55 +0000189 /// \brief Whether we should include code patterns in the completion
190 /// results.
191 bool includeCodePatterns() const {
192 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000193 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000194 }
195
Douglas Gregor86d9a522009-09-21 16:56:56 +0000196 /// \brief Set the filter used for code-completion results.
197 void setFilter(LookupFilter Filter) {
198 this->Filter = Filter;
199 }
200
Douglas Gregor86d9a522009-09-21 16:56:56 +0000201 Result *data() { return Results.empty()? 0 : &Results.front(); }
202 unsigned size() const { return Results.size(); }
203 bool empty() const { return Results.empty(); }
204
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000205 /// \brief Specify the preferred type.
206 void setPreferredType(QualType T) {
207 PreferredType = SemaRef.Context.getCanonicalType(T);
208 }
209
Douglas Gregor3cdee122010-08-26 16:36:48 +0000210 /// \brief Set the cv-qualifiers on the object type, for us in filtering
211 /// calls to member functions.
212 ///
213 /// When there are qualifiers in this set, they will be used to filter
214 /// out member functions that aren't available (because there will be a
215 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
216 /// match.
217 void setObjectTypeQualifiers(Qualifiers Quals) {
218 ObjectTypeQualifiers = Quals;
219 HasObjectTypeQualifiers = true;
220 }
221
Douglas Gregor265f7492010-08-27 15:29:55 +0000222 /// \brief Set the preferred selector.
223 ///
224 /// When an Objective-C method declaration result is added, and that
225 /// method's selector matches this preferred selector, we give that method
226 /// a slight priority boost.
227 void setPreferredSelector(Selector Sel) {
228 PreferredSelector = Sel;
229 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000230
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000231 /// \brief Retrieve the code-completion context for which results are
232 /// being collected.
233 const CodeCompletionContext &getCompletionContext() const {
234 return CompletionContext;
235 }
236
Douglas Gregor45bcd432010-01-14 03:21:49 +0000237 /// \brief Specify whether nested-name-specifiers are allowed.
238 void allowNestedNameSpecifiers(bool Allow = true) {
239 AllowNestedNameSpecifiers = Allow;
240 }
241
Douglas Gregorb9d77572010-09-21 00:03:25 +0000242 /// \brief Return the semantic analysis object for which we are collecting
243 /// code completion results.
244 Sema &getSema() const { return SemaRef; }
245
Douglas Gregore495b7f2010-01-14 00:20:49 +0000246 /// \brief Determine whether the given declaration is at all interesting
247 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000248 ///
249 /// \param ND the declaration that we are inspecting.
250 ///
251 /// \param AsNestedNameSpecifier will be set true if this declaration is
252 /// only interesting when it is a nested-name-specifier.
253 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000254
255 /// \brief Check whether the result is hidden by the Hiding declaration.
256 ///
257 /// \returns true if the result is hidden and cannot be found, false if
258 /// the hidden result could still be found. When false, \p R may be
259 /// modified to describe how the result can be found (e.g., via extra
260 /// qualification).
261 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
262 NamedDecl *Hiding);
263
Douglas Gregor86d9a522009-09-21 16:56:56 +0000264 /// \brief Add a new result to this result set (if it isn't already in one
265 /// of the shadow maps), or replace an existing result (for, e.g., a
266 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000267 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000268 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000269 ///
270 /// \param R the context in which this result will be named.
271 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000272
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000273 /// \brief Add a new result to this result set, where we already know
274 /// the hiding declation (if any).
275 ///
276 /// \param R the result to add (if it is unique).
277 ///
278 /// \param CurContext the context in which this result will be named.
279 ///
280 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000281 ///
282 /// \param InBaseClass whether the result was found in a base
283 /// class of the searched context.
284 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
285 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000286
Douglas Gregora4477812010-01-14 16:01:26 +0000287 /// \brief Add a new non-declaration result to this result set.
288 void AddResult(Result R);
289
Douglas Gregor86d9a522009-09-21 16:56:56 +0000290 /// \brief Enter into a new scope.
291 void EnterNewScope();
292
293 /// \brief Exit from the current scope.
294 void ExitScope();
295
Douglas Gregor55385fe2009-11-18 04:19:12 +0000296 /// \brief Ignore this declaration, if it is seen again.
297 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
298
Douglas Gregor86d9a522009-09-21 16:56:56 +0000299 /// \name Name lookup predicates
300 ///
301 /// These predicates can be passed to the name lookup functions to filter the
302 /// results of name lookup. All of the predicates have the same type, so that
303 ///
304 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000305 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000306 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000307 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000308 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000309 bool IsNestedNameSpecifier(NamedDecl *ND) const;
310 bool IsEnum(NamedDecl *ND) const;
311 bool IsClassOrStruct(NamedDecl *ND) const;
312 bool IsUnion(NamedDecl *ND) const;
313 bool IsNamespace(NamedDecl *ND) const;
314 bool IsNamespaceOrAlias(NamedDecl *ND) const;
315 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000316 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000317 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000318 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000319 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000320 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000321 //@}
322 };
323}
324
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000325class ResultBuilder::ShadowMapEntry::iterator {
326 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
327 unsigned SingleDeclIndex;
328
329public:
330 typedef DeclIndexPair value_type;
331 typedef value_type reference;
332 typedef std::ptrdiff_t difference_type;
333 typedef std::input_iterator_tag iterator_category;
334
335 class pointer {
336 DeclIndexPair Value;
337
338 public:
339 pointer(const DeclIndexPair &Value) : Value(Value) { }
340
341 const DeclIndexPair *operator->() const {
342 return &Value;
343 }
344 };
345
346 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
347
348 iterator(NamedDecl *SingleDecl, unsigned Index)
349 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
350
351 iterator(const DeclIndexPair *Iterator)
352 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
353
354 iterator &operator++() {
355 if (DeclOrIterator.is<NamedDecl *>()) {
356 DeclOrIterator = (NamedDecl *)0;
357 SingleDeclIndex = 0;
358 return *this;
359 }
360
361 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
362 ++I;
363 DeclOrIterator = I;
364 return *this;
365 }
366
Chris Lattner66392d42010-09-04 18:12:20 +0000367 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000368 iterator tmp(*this);
369 ++(*this);
370 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000371 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000372
373 reference operator*() const {
374 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
375 return reference(ND, SingleDeclIndex);
376
Douglas Gregord490f952009-12-06 21:27:58 +0000377 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378 }
379
380 pointer operator->() const {
381 return pointer(**this);
382 }
383
384 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000385 return X.DeclOrIterator.getOpaqueValue()
386 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000387 X.SingleDeclIndex == Y.SingleDeclIndex;
388 }
389
390 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000392 }
393};
394
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000395ResultBuilder::ShadowMapEntry::iterator
396ResultBuilder::ShadowMapEntry::begin() const {
397 if (DeclOrVector.isNull())
398 return iterator();
399
400 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
401 return iterator(ND, SingleDeclIndex);
402
403 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
404}
405
406ResultBuilder::ShadowMapEntry::iterator
407ResultBuilder::ShadowMapEntry::end() const {
408 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
409 return iterator();
410
411 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
412}
413
Douglas Gregor456c4a12009-09-21 20:12:40 +0000414/// \brief Compute the qualification required to get from the current context
415/// (\p CurContext) to the target context (\p TargetContext).
416///
417/// \param Context the AST context in which the qualification will be used.
418///
419/// \param CurContext the context where an entity is being named, which is
420/// typically based on the current scope.
421///
422/// \param TargetContext the context in which the named entity actually
423/// resides.
424///
425/// \returns a nested name specifier that refers into the target context, or
426/// NULL if no qualification is needed.
427static NestedNameSpecifier *
428getRequiredQualification(ASTContext &Context,
429 DeclContext *CurContext,
430 DeclContext *TargetContext) {
431 llvm::SmallVector<DeclContext *, 4> TargetParents;
432
433 for (DeclContext *CommonAncestor = TargetContext;
434 CommonAncestor && !CommonAncestor->Encloses(CurContext);
435 CommonAncestor = CommonAncestor->getLookupParent()) {
436 if (CommonAncestor->isTransparentContext() ||
437 CommonAncestor->isFunctionOrMethod())
438 continue;
439
440 TargetParents.push_back(CommonAncestor);
441 }
442
443 NestedNameSpecifier *Result = 0;
444 while (!TargetParents.empty()) {
445 DeclContext *Parent = TargetParents.back();
446 TargetParents.pop_back();
447
Douglas Gregorfb629412010-08-23 21:17:50 +0000448 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
449 if (!Namespace->getIdentifier())
450 continue;
451
Douglas Gregor456c4a12009-09-21 20:12:40 +0000452 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000453 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000454 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
455 Result = NestedNameSpecifier::Create(Context, Result,
456 false,
457 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000458 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000459 return Result;
460}
461
Douglas Gregor45bcd432010-01-14 03:21:49 +0000462bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
463 bool &AsNestedNameSpecifier) const {
464 AsNestedNameSpecifier = false;
465
Douglas Gregore495b7f2010-01-14 00:20:49 +0000466 ND = ND->getUnderlyingDecl();
467 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000468
469 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000470 if (!ND->getDeclName())
471 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000472
473 // Friend declarations and declarations introduced due to friends are never
474 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000475 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 return false;
477
Douglas Gregor76282942009-12-11 17:31:05 +0000478 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000479 if (isa<ClassTemplateSpecializationDecl>(ND) ||
480 isa<ClassTemplatePartialSpecializationDecl>(ND))
481 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000482
Douglas Gregor76282942009-12-11 17:31:05 +0000483 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000484 if (isa<UsingDecl>(ND))
485 return false;
486
487 // Some declarations have reserved names that we don't want to ever show.
488 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000489 // __va_list_tag is a freak of nature. Find it and skip it.
490 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000491 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000492
Douglas Gregorf52cede2009-10-09 22:16:47 +0000493 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000494 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000495 //
496 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000497 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000498 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
501 (ND->getLocation().isInvalid() ||
502 SemaRef.SourceMgr.isInSystemHeader(
503 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000504 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000506 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000507
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000508 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
509 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
510 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000511 Filter != &ResultBuilder::IsNamespaceOrAlias &&
512 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000513 AsNestedNameSpecifier = true;
514
Douglas Gregor86d9a522009-09-21 16:56:56 +0000515 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000516 if (Filter && !(this->*Filter)(ND)) {
517 // Check whether it is interesting as a nested-name-specifier.
518 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
519 IsNestedNameSpecifier(ND) &&
520 (Filter != &ResultBuilder::IsMember ||
521 (isa<CXXRecordDecl>(ND) &&
522 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
523 AsNestedNameSpecifier = true;
524 return true;
525 }
526
Douglas Gregore495b7f2010-01-14 00:20:49 +0000527 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000528 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000529 // ... then it must be interesting!
530 return true;
531}
532
Douglas Gregor6660d842010-01-14 00:41:07 +0000533bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
534 NamedDecl *Hiding) {
535 // In C, there is no way to refer to a hidden name.
536 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
537 // name if we introduce the tag type.
538 if (!SemaRef.getLangOptions().CPlusPlus)
539 return true;
540
Sebastian Redl7a126a42010-08-31 00:36:30 +0000541 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000542
543 // There is no way to qualify a name declared in a function or method.
544 if (HiddenCtx->isFunctionOrMethod())
545 return true;
546
Sebastian Redl7a126a42010-08-31 00:36:30 +0000547 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000548 return true;
549
550 // We can refer to the result with the appropriate qualification. Do it.
551 R.Hidden = true;
552 R.QualifierIsInformative = false;
553
554 if (!R.Qualifier)
555 R.Qualifier = getRequiredQualification(SemaRef.Context,
556 CurContext,
557 R.Declaration->getDeclContext());
558 return false;
559}
560
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000561/// \brief A simplified classification of types used to determine whether two
562/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000563SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000564 switch (T->getTypeClass()) {
565 case Type::Builtin:
566 switch (cast<BuiltinType>(T)->getKind()) {
567 case BuiltinType::Void:
568 return STC_Void;
569
570 case BuiltinType::NullPtr:
571 return STC_Pointer;
572
573 case BuiltinType::Overload:
574 case BuiltinType::Dependent:
575 case BuiltinType::UndeducedAuto:
576 return STC_Other;
577
578 case BuiltinType::ObjCId:
579 case BuiltinType::ObjCClass:
580 case BuiltinType::ObjCSel:
581 return STC_ObjectiveC;
582
583 default:
584 return STC_Arithmetic;
585 }
586 return STC_Other;
587
588 case Type::Complex:
589 return STC_Arithmetic;
590
591 case Type::Pointer:
592 return STC_Pointer;
593
594 case Type::BlockPointer:
595 return STC_Block;
596
597 case Type::LValueReference:
598 case Type::RValueReference:
599 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
600
601 case Type::ConstantArray:
602 case Type::IncompleteArray:
603 case Type::VariableArray:
604 case Type::DependentSizedArray:
605 return STC_Array;
606
607 case Type::DependentSizedExtVector:
608 case Type::Vector:
609 case Type::ExtVector:
610 return STC_Arithmetic;
611
612 case Type::FunctionProto:
613 case Type::FunctionNoProto:
614 return STC_Function;
615
616 case Type::Record:
617 return STC_Record;
618
619 case Type::Enum:
620 return STC_Arithmetic;
621
622 case Type::ObjCObject:
623 case Type::ObjCInterface:
624 case Type::ObjCObjectPointer:
625 return STC_ObjectiveC;
626
627 default:
628 return STC_Other;
629 }
630}
631
632/// \brief Get the type that a given expression will have if this declaration
633/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000634QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000635 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
636
637 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
638 return C.getTypeDeclType(Type);
639 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
640 return C.getObjCInterfaceType(Iface);
641
642 QualType T;
643 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000644 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000645 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000646 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000647 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000648 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000649 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
650 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
651 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
652 T = Property->getType();
653 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
654 T = Value->getType();
655 else
656 return QualType();
657
658 return T.getNonReferenceType();
659}
660
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000661void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
662 // If this is an Objective-C method declaration whose selector matches our
663 // preferred selector, give it a priority boost.
664 if (!PreferredSelector.isNull())
665 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
666 if (PreferredSelector == Method->getSelector())
667 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000668
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000669 // If we have a preferred type, adjust the priority for results with exactly-
670 // matching or nearly-matching types.
671 if (!PreferredType.isNull()) {
672 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
673 if (!T.isNull()) {
674 CanQualType TC = SemaRef.Context.getCanonicalType(T);
675 // Check for exactly-matching types (modulo qualifiers).
676 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
677 R.Priority /= CCF_ExactTypeMatch;
678 // Check for nearly-matching types, based on classification of each.
679 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000680 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000681 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
682 R.Priority /= CCF_SimilarTypeMatch;
683 }
684 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000685}
686
Douglas Gregor6f942b22010-09-21 16:06:22 +0000687void ResultBuilder::MaybeAddConstructorResults(Result R) {
688 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
689 !CompletionContext.wantConstructorResults())
690 return;
691
692 ASTContext &Context = SemaRef.Context;
693 NamedDecl *D = R.Declaration;
694 CXXRecordDecl *Record = 0;
695 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
696 Record = ClassTemplate->getTemplatedDecl();
697 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
698 // Skip specializations and partial specializations.
699 if (isa<ClassTemplateSpecializationDecl>(Record))
700 return;
701 } else {
702 // There are no constructors here.
703 return;
704 }
705
706 Record = Record->getDefinition();
707 if (!Record)
708 return;
709
710
711 QualType RecordTy = Context.getTypeDeclType(Record);
712 DeclarationName ConstructorName
713 = Context.DeclarationNames.getCXXConstructorName(
714 Context.getCanonicalType(RecordTy));
715 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
716 Ctors.first != Ctors.second; ++Ctors.first) {
717 R.Declaration = *Ctors.first;
718 R.CursorKind = getCursorKindForDecl(R.Declaration);
719 Results.push_back(R);
720 }
721}
722
Douglas Gregore495b7f2010-01-14 00:20:49 +0000723void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
724 assert(!ShadowMaps.empty() && "Must enter into a results scope");
725
726 if (R.Kind != Result::RK_Declaration) {
727 // For non-declaration results, just add the result.
728 Results.push_back(R);
729 return;
730 }
731
732 // Look through using declarations.
733 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
734 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
735 return;
736 }
737
738 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
739 unsigned IDNS = CanonDecl->getIdentifierNamespace();
740
Douglas Gregor45bcd432010-01-14 03:21:49 +0000741 bool AsNestedNameSpecifier = false;
742 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000743 return;
744
Douglas Gregor6f942b22010-09-21 16:06:22 +0000745 // C++ constructors are never found by name lookup.
746 if (isa<CXXConstructorDecl>(R.Declaration))
747 return;
748
Douglas Gregor86d9a522009-09-21 16:56:56 +0000749 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000750 ShadowMapEntry::iterator I, IEnd;
751 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
752 if (NamePos != SMap.end()) {
753 I = NamePos->second.begin();
754 IEnd = NamePos->second.end();
755 }
756
757 for (; I != IEnd; ++I) {
758 NamedDecl *ND = I->first;
759 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000760 if (ND->getCanonicalDecl() == CanonDecl) {
761 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000762 Results[Index].Declaration = R.Declaration;
763
Douglas Gregor86d9a522009-09-21 16:56:56 +0000764 // We're done.
765 return;
766 }
767 }
768
769 // This is a new declaration in this scope. However, check whether this
770 // declaration name is hidden by a similarly-named declaration in an outer
771 // scope.
772 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
773 --SMEnd;
774 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000775 ShadowMapEntry::iterator I, IEnd;
776 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
777 if (NamePos != SM->end()) {
778 I = NamePos->second.begin();
779 IEnd = NamePos->second.end();
780 }
781 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000782 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000783 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000784 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
785 Decl::IDNS_ObjCProtocol)))
786 continue;
787
788 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000789 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000790 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000791 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000792 continue;
793
794 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000795 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000796 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000797
798 break;
799 }
800 }
801
802 // Make sure that any given declaration only shows up in the result set once.
803 if (!AllDeclsFound.insert(CanonDecl))
804 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000805
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000806 // If the filter is for nested-name-specifiers, then this result starts a
807 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000808 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000809 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000810 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000811 } else
812 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000813
Douglas Gregor0563c262009-09-22 23:15:58 +0000814 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000815 if (R.QualifierIsInformative && !R.Qualifier &&
816 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000817 DeclContext *Ctx = R.Declaration->getDeclContext();
818 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
819 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
820 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
821 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
822 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
823 else
824 R.QualifierIsInformative = false;
825 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000826
Douglas Gregor86d9a522009-09-21 16:56:56 +0000827 // Insert this result into the set of results and into the current shadow
828 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000829 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000830 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000831
832 if (!AsNestedNameSpecifier)
833 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834}
835
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000836void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000837 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000838 if (R.Kind != Result::RK_Declaration) {
839 // For non-declaration results, just add the result.
840 Results.push_back(R);
841 return;
842 }
843
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000844 // Look through using declarations.
845 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
846 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
847 return;
848 }
849
Douglas Gregor45bcd432010-01-14 03:21:49 +0000850 bool AsNestedNameSpecifier = false;
851 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000852 return;
853
Douglas Gregor6f942b22010-09-21 16:06:22 +0000854 // C++ constructors are never found by name lookup.
855 if (isa<CXXConstructorDecl>(R.Declaration))
856 return;
857
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000858 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
859 return;
860
861 // Make sure that any given declaration only shows up in the result set once.
862 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
863 return;
864
865 // If the filter is for nested-name-specifiers, then this result starts a
866 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000867 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000868 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000869 R.Priority = CCP_NestedNameSpecifier;
870 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000871 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
872 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000873 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000874 R.QualifierIsInformative = true;
875
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000876 // If this result is supposed to have an informative qualifier, add one.
877 if (R.QualifierIsInformative && !R.Qualifier &&
878 !R.StartsNestedNameSpecifier) {
879 DeclContext *Ctx = R.Declaration->getDeclContext();
880 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
881 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
882 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
883 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000884 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000885 else
886 R.QualifierIsInformative = false;
887 }
888
Douglas Gregor12e13132010-05-26 22:00:08 +0000889 // Adjust the priority if this result comes from a base class.
890 if (InBaseClass)
891 R.Priority += CCD_InBaseClass;
892
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000893 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000894
Douglas Gregor3cdee122010-08-26 16:36:48 +0000895 if (HasObjectTypeQualifiers)
896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
897 if (Method->isInstance()) {
898 Qualifiers MethodQuals
899 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
900 if (ObjectTypeQualifiers == MethodQuals)
901 R.Priority += CCD_ObjectQualifierMatch;
902 else if (ObjectTypeQualifiers - MethodQuals) {
903 // The method cannot be invoked, because doing so would drop
904 // qualifiers.
905 return;
906 }
907 }
908
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000909 // Insert this result into the set of results.
910 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000911
912 if (!AsNestedNameSpecifier)
913 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000914}
915
Douglas Gregora4477812010-01-14 16:01:26 +0000916void ResultBuilder::AddResult(Result R) {
917 assert(R.Kind != Result::RK_Declaration &&
918 "Declaration results need more context");
919 Results.push_back(R);
920}
921
Douglas Gregor86d9a522009-09-21 16:56:56 +0000922/// \brief Enter into a new scope.
923void ResultBuilder::EnterNewScope() {
924 ShadowMaps.push_back(ShadowMap());
925}
926
927/// \brief Exit from the current scope.
928void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000929 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
930 EEnd = ShadowMaps.back().end();
931 E != EEnd;
932 ++E)
933 E->second.Destroy();
934
Douglas Gregor86d9a522009-09-21 16:56:56 +0000935 ShadowMaps.pop_back();
936}
937
Douglas Gregor791215b2009-09-21 20:51:25 +0000938/// \brief Determines whether this given declaration will be found by
939/// ordinary name lookup.
940bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000941 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
942
Douglas Gregor791215b2009-09-21 20:51:25 +0000943 unsigned IDNS = Decl::IDNS_Ordinary;
944 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000945 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000946 else if (SemaRef.getLangOptions().ObjC1) {
947 if (isa<ObjCIvarDecl>(ND))
948 return true;
949 if (isa<ObjCPropertyDecl>(ND) &&
950 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
951 return true;
952 }
953
Douglas Gregor791215b2009-09-21 20:51:25 +0000954 return ND->getIdentifierNamespace() & IDNS;
955}
956
Douglas Gregor01dfea02010-01-10 23:08:15 +0000957/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000958/// ordinary name lookup but is not a type name.
959bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
960 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
961 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
962 return false;
963
964 unsigned IDNS = Decl::IDNS_Ordinary;
965 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000966 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000967 else if (SemaRef.getLangOptions().ObjC1) {
968 if (isa<ObjCIvarDecl>(ND))
969 return true;
970 if (isa<ObjCPropertyDecl>(ND) &&
971 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
972 return true;
973 }
974
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000975 return ND->getIdentifierNamespace() & IDNS;
976}
977
Douglas Gregorf9578432010-07-28 21:50:18 +0000978bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
979 if (!IsOrdinaryNonTypeName(ND))
980 return 0;
981
982 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
983 if (VD->getType()->isIntegralOrEnumerationType())
984 return true;
985
986 return false;
987}
988
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000989/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000990/// ordinary name lookup.
991bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000992 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
993
Douglas Gregor01dfea02010-01-10 23:08:15 +0000994 unsigned IDNS = Decl::IDNS_Ordinary;
995 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000996 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000997
998 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000999 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1000 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001}
1002
Douglas Gregor86d9a522009-09-21 16:56:56 +00001003/// \brief Determines whether the given declaration is suitable as the
1004/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1005bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1006 // Allow us to find class templates, too.
1007 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1008 ND = ClassTemplate->getTemplatedDecl();
1009
1010 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1011}
1012
1013/// \brief Determines whether the given declaration is an enumeration.
1014bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1015 return isa<EnumDecl>(ND);
1016}
1017
1018/// \brief Determines whether the given declaration is a class or struct.
1019bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1020 // Allow us to find class templates, too.
1021 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1022 ND = ClassTemplate->getTemplatedDecl();
1023
1024 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001025 return RD->getTagKind() == TTK_Class ||
1026 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001027
1028 return false;
1029}
1030
1031/// \brief Determines whether the given declaration is a union.
1032bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1033 // Allow us to find class templates, too.
1034 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1035 ND = ClassTemplate->getTemplatedDecl();
1036
1037 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001038 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001039
1040 return false;
1041}
1042
1043/// \brief Determines whether the given declaration is a namespace.
1044bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1045 return isa<NamespaceDecl>(ND);
1046}
1047
1048/// \brief Determines whether the given declaration is a namespace or
1049/// namespace alias.
1050bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1051 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1052}
1053
Douglas Gregor76282942009-12-11 17:31:05 +00001054/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001055bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001056 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1057 ND = Using->getTargetDecl();
1058
1059 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001060}
1061
Douglas Gregor76282942009-12-11 17:31:05 +00001062/// \brief Determines which members of a class should be visible via
1063/// "." or "->". Only value declarations, nested name specifiers, and
1064/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001065bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001066 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1067 ND = Using->getTargetDecl();
1068
Douglas Gregorce821962009-12-11 18:14:22 +00001069 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1070 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001071}
1072
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001073static bool isObjCReceiverType(ASTContext &C, QualType T) {
1074 T = C.getCanonicalType(T);
1075 switch (T->getTypeClass()) {
1076 case Type::ObjCObject:
1077 case Type::ObjCInterface:
1078 case Type::ObjCObjectPointer:
1079 return true;
1080
1081 case Type::Builtin:
1082 switch (cast<BuiltinType>(T)->getKind()) {
1083 case BuiltinType::ObjCId:
1084 case BuiltinType::ObjCClass:
1085 case BuiltinType::ObjCSel:
1086 return true;
1087
1088 default:
1089 break;
1090 }
1091 return false;
1092
1093 default:
1094 break;
1095 }
1096
1097 if (!C.getLangOptions().CPlusPlus)
1098 return false;
1099
1100 // FIXME: We could perform more analysis here to determine whether a
1101 // particular class type has any conversions to Objective-C types. For now,
1102 // just accept all class types.
1103 return T->isDependentType() || T->isRecordType();
1104}
1105
1106bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1107 QualType T = getDeclUsageType(SemaRef.Context, ND);
1108 if (T.isNull())
1109 return false;
1110
1111 T = SemaRef.Context.getBaseElementType(T);
1112 return isObjCReceiverType(SemaRef.Context, T);
1113}
1114
Douglas Gregorfb629412010-08-23 21:17:50 +00001115bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1116 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1117 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1118 return false;
1119
1120 QualType T = getDeclUsageType(SemaRef.Context, ND);
1121 if (T.isNull())
1122 return false;
1123
1124 T = SemaRef.Context.getBaseElementType(T);
1125 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1126 T->isObjCIdType() ||
1127 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1128}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001129
Douglas Gregor52779fb2010-09-23 23:01:17 +00001130bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1131 return false;
1132}
1133
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001134/// \rief Determines whether the given declaration is an Objective-C
1135/// instance variable.
1136bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1137 return isa<ObjCIvarDecl>(ND);
1138}
1139
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001140namespace {
1141 /// \brief Visible declaration consumer that adds a code-completion result
1142 /// for each visible declaration.
1143 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1144 ResultBuilder &Results;
1145 DeclContext *CurContext;
1146
1147 public:
1148 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1149 : Results(Results), CurContext(CurContext) { }
1150
Douglas Gregor0cc84042010-01-14 15:47:35 +00001151 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1152 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001153 }
1154 };
1155}
1156
Douglas Gregor86d9a522009-09-21 16:56:56 +00001157/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001158static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001159 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001160 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001161 Results.AddResult(Result("short", CCP_Type));
1162 Results.AddResult(Result("long", CCP_Type));
1163 Results.AddResult(Result("signed", CCP_Type));
1164 Results.AddResult(Result("unsigned", CCP_Type));
1165 Results.AddResult(Result("void", CCP_Type));
1166 Results.AddResult(Result("char", CCP_Type));
1167 Results.AddResult(Result("int", CCP_Type));
1168 Results.AddResult(Result("float", CCP_Type));
1169 Results.AddResult(Result("double", CCP_Type));
1170 Results.AddResult(Result("enum", CCP_Type));
1171 Results.AddResult(Result("struct", CCP_Type));
1172 Results.AddResult(Result("union", CCP_Type));
1173 Results.AddResult(Result("const", CCP_Type));
1174 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001175
Douglas Gregor86d9a522009-09-21 16:56:56 +00001176 if (LangOpts.C99) {
1177 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001178 Results.AddResult(Result("_Complex", CCP_Type));
1179 Results.AddResult(Result("_Imaginary", CCP_Type));
1180 Results.AddResult(Result("_Bool", CCP_Type));
1181 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001182 }
1183
1184 if (LangOpts.CPlusPlus) {
1185 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001186 Results.AddResult(Result("bool", CCP_Type +
1187 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001188 Results.AddResult(Result("class", CCP_Type));
1189 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001190
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001191 // typename qualified-id
1192 CodeCompletionString *Pattern = new CodeCompletionString;
1193 Pattern->AddTypedTextChunk("typename");
1194 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1195 Pattern->AddPlaceholderChunk("qualifier");
1196 Pattern->AddTextChunk("::");
1197 Pattern->AddPlaceholderChunk("name");
1198 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001199
Douglas Gregor86d9a522009-09-21 16:56:56 +00001200 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001201 Results.AddResult(Result("auto", CCP_Type));
1202 Results.AddResult(Result("char16_t", CCP_Type));
1203 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001204
1205 CodeCompletionString *Pattern = new CodeCompletionString;
1206 Pattern->AddTypedTextChunk("decltype");
1207 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1208 Pattern->AddPlaceholderChunk("expression");
1209 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1210 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001211 }
1212 }
1213
1214 // GNU extensions
1215 if (LangOpts.GNUMode) {
1216 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001217 // Results.AddResult(Result("_Decimal32"));
1218 // Results.AddResult(Result("_Decimal64"));
1219 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001220
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001221 CodeCompletionString *Pattern = new CodeCompletionString;
1222 Pattern->AddTypedTextChunk("typeof");
1223 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1224 Pattern->AddPlaceholderChunk("expression");
1225 Results.AddResult(Result(Pattern));
1226
1227 Pattern = new CodeCompletionString;
1228 Pattern->AddTypedTextChunk("typeof");
1229 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1230 Pattern->AddPlaceholderChunk("type");
1231 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1232 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001233 }
1234}
1235
John McCallf312b1e2010-08-26 23:41:50 +00001236static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001237 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001238 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001239 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001240 // Note: we don't suggest either "auto" or "register", because both
1241 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1242 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001243 Results.AddResult(Result("extern"));
1244 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001245}
1246
John McCallf312b1e2010-08-26 23:41:50 +00001247static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001248 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001249 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001250 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001251 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001252 case Sema::PCC_Class:
1253 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001254 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001255 Results.AddResult(Result("explicit"));
1256 Results.AddResult(Result("friend"));
1257 Results.AddResult(Result("mutable"));
1258 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001259 }
1260 // Fall through
1261
John McCallf312b1e2010-08-26 23:41:50 +00001262 case Sema::PCC_ObjCInterface:
1263 case Sema::PCC_ObjCImplementation:
1264 case Sema::PCC_Namespace:
1265 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001266 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001267 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001268 break;
1269
John McCallf312b1e2010-08-26 23:41:50 +00001270 case Sema::PCC_ObjCInstanceVariableList:
1271 case Sema::PCC_Expression:
1272 case Sema::PCC_Statement:
1273 case Sema::PCC_ForInit:
1274 case Sema::PCC_Condition:
1275 case Sema::PCC_RecoveryInFunction:
1276 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001277 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 break;
1279 }
1280}
1281
Douglas Gregorbca403c2010-01-13 23:51:12 +00001282static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1283static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1284static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001285 ResultBuilder &Results,
1286 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001287static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001288 ResultBuilder &Results,
1289 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001290static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001291 ResultBuilder &Results,
1292 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001293static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001294
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001295static void AddTypedefResult(ResultBuilder &Results) {
1296 CodeCompletionString *Pattern = new CodeCompletionString;
1297 Pattern->AddTypedTextChunk("typedef");
1298 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1299 Pattern->AddPlaceholderChunk("type");
1300 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1301 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001302 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001303}
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001306 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001307 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001308 case Sema::PCC_Namespace:
1309 case Sema::PCC_Class:
1310 case Sema::PCC_ObjCInstanceVariableList:
1311 case Sema::PCC_Template:
1312 case Sema::PCC_MemberTemplate:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_RecoveryInFunction:
1315 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001316 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001317 return true;
1318
John McCallf312b1e2010-08-26 23:41:50 +00001319 case Sema::PCC_Expression:
1320 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001321 return LangOpts.CPlusPlus;
1322
1323 case Sema::PCC_ObjCInterface:
1324 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001325 return false;
1326
John McCallf312b1e2010-08-26 23:41:50 +00001327 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001328 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001329 }
1330
1331 return false;
1332}
1333
Douglas Gregor01dfea02010-01-10 23:08:15 +00001334/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001335static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001336 Scope *S,
1337 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001338 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001339 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001340 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001341 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001342 if (SemaRef.getLangOptions().CPlusPlus) {
1343 CodeCompletionString *Pattern = 0;
1344
1345 if (Results.includeCodePatterns()) {
1346 // namespace <identifier> { declarations }
1347 CodeCompletionString *Pattern = new CodeCompletionString;
1348 Pattern->AddTypedTextChunk("namespace");
1349 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1350 Pattern->AddPlaceholderChunk("identifier");
1351 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1352 Pattern->AddPlaceholderChunk("declarations");
1353 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1354 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1355 Results.AddResult(Result(Pattern));
1356 }
1357
Douglas Gregor01dfea02010-01-10 23:08:15 +00001358 // namespace identifier = identifier ;
1359 Pattern = new CodeCompletionString;
1360 Pattern->AddTypedTextChunk("namespace");
1361 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001362 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001363 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001364 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001365 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001366
1367 // Using directives
1368 Pattern = new CodeCompletionString;
1369 Pattern->AddTypedTextChunk("using");
1370 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1371 Pattern->AddTextChunk("namespace");
1372 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1373 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001374 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001375
1376 // asm(string-literal)
1377 Pattern = new CodeCompletionString;
1378 Pattern->AddTypedTextChunk("asm");
1379 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1380 Pattern->AddPlaceholderChunk("string-literal");
1381 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001382 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001383
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001384 if (Results.includeCodePatterns()) {
1385 // Explicit template instantiation
1386 Pattern = new CodeCompletionString;
1387 Pattern->AddTypedTextChunk("template");
1388 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1389 Pattern->AddPlaceholderChunk("declaration");
1390 Results.AddResult(Result(Pattern));
1391 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001392 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001393
1394 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001395 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001396
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001397 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001398 // Fall through
1399
John McCallf312b1e2010-08-26 23:41:50 +00001400 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001401 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001402 // Using declaration
1403 CodeCompletionString *Pattern = new CodeCompletionString;
1404 Pattern->AddTypedTextChunk("using");
1405 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001406 Pattern->AddPlaceholderChunk("qualifier");
1407 Pattern->AddTextChunk("::");
1408 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001409 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001410
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001411 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001412 if (SemaRef.CurContext->isDependentContext()) {
1413 Pattern = new CodeCompletionString;
1414 Pattern->AddTypedTextChunk("using");
1415 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1416 Pattern->AddTextChunk("typename");
1417 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001418 Pattern->AddPlaceholderChunk("qualifier");
1419 Pattern->AddTextChunk("::");
1420 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001421 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422 }
1423
John McCallf312b1e2010-08-26 23:41:50 +00001424 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001425 AddTypedefResult(Results);
1426
Douglas Gregor01dfea02010-01-10 23:08:15 +00001427 // public:
1428 Pattern = new CodeCompletionString;
1429 Pattern->AddTypedTextChunk("public");
1430 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001431 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001432
1433 // protected:
1434 Pattern = new CodeCompletionString;
1435 Pattern->AddTypedTextChunk("protected");
1436 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001437 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001438
1439 // private:
1440 Pattern = new CodeCompletionString;
1441 Pattern->AddTypedTextChunk("private");
1442 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001443 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001444 }
1445 }
1446 // Fall through
1447
John McCallf312b1e2010-08-26 23:41:50 +00001448 case Sema::PCC_Template:
1449 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001450 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451 // template < parameters >
1452 CodeCompletionString *Pattern = new CodeCompletionString;
1453 Pattern->AddTypedTextChunk("template");
1454 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1455 Pattern->AddPlaceholderChunk("parameters");
1456 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001457 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458 }
1459
Douglas Gregorbca403c2010-01-13 23:51:12 +00001460 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1461 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001462 break;
1463
John McCallf312b1e2010-08-26 23:41:50 +00001464 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001465 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1466 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1467 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001468 break;
1469
John McCallf312b1e2010-08-26 23:41:50 +00001470 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001471 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1472 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1473 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001474 break;
1475
John McCallf312b1e2010-08-26 23:41:50 +00001476 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001477 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001478 break;
1479
John McCallf312b1e2010-08-26 23:41:50 +00001480 case Sema::PCC_RecoveryInFunction:
1481 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001482 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001483
1484 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001485 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486 Pattern = new CodeCompletionString;
1487 Pattern->AddTypedTextChunk("try");
1488 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1489 Pattern->AddPlaceholderChunk("statements");
1490 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1491 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1492 Pattern->AddTextChunk("catch");
1493 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1494 Pattern->AddPlaceholderChunk("declaration");
1495 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1496 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1497 Pattern->AddPlaceholderChunk("statements");
1498 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1499 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001500 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001501 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001502 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001504
Douglas Gregord8e8a582010-05-25 21:41:55 +00001505 if (Results.includeCodePatterns()) {
1506 // if (condition) { statements }
1507 Pattern = new CodeCompletionString;
1508 Pattern->AddTypedTextChunk("if");
1509 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1510 if (SemaRef.getLangOptions().CPlusPlus)
1511 Pattern->AddPlaceholderChunk("condition");
1512 else
1513 Pattern->AddPlaceholderChunk("expression");
1514 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1515 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1516 Pattern->AddPlaceholderChunk("statements");
1517 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1518 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1519 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001520
Douglas Gregord8e8a582010-05-25 21:41:55 +00001521 // switch (condition) { }
1522 Pattern = new CodeCompletionString;
1523 Pattern->AddTypedTextChunk("switch");
1524 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1525 if (SemaRef.getLangOptions().CPlusPlus)
1526 Pattern->AddPlaceholderChunk("condition");
1527 else
1528 Pattern->AddPlaceholderChunk("expression");
1529 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1530 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1531 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1532 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1533 Results.AddResult(Result(Pattern));
1534 }
1535
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001537 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001538 // case expression:
1539 Pattern = new CodeCompletionString;
1540 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001541 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001542 Pattern->AddPlaceholderChunk("expression");
1543 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001544 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001545
1546 // default:
1547 Pattern = new CodeCompletionString;
1548 Pattern->AddTypedTextChunk("default");
1549 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001550 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001551 }
1552
Douglas Gregord8e8a582010-05-25 21:41:55 +00001553 if (Results.includeCodePatterns()) {
1554 /// while (condition) { statements }
1555 Pattern = new CodeCompletionString;
1556 Pattern->AddTypedTextChunk("while");
1557 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1558 if (SemaRef.getLangOptions().CPlusPlus)
1559 Pattern->AddPlaceholderChunk("condition");
1560 else
1561 Pattern->AddPlaceholderChunk("expression");
1562 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1563 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1564 Pattern->AddPlaceholderChunk("statements");
1565 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1566 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1567 Results.AddResult(Result(Pattern));
1568
1569 // do { statements } while ( expression );
1570 Pattern = new CodeCompletionString;
1571 Pattern->AddTypedTextChunk("do");
1572 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1573 Pattern->AddPlaceholderChunk("statements");
1574 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1575 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1576 Pattern->AddTextChunk("while");
1577 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001579 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1580 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001581
Douglas Gregord8e8a582010-05-25 21:41:55 +00001582 // for ( for-init-statement ; condition ; expression ) { statements }
1583 Pattern = new CodeCompletionString;
1584 Pattern->AddTypedTextChunk("for");
1585 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1586 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1587 Pattern->AddPlaceholderChunk("init-statement");
1588 else
1589 Pattern->AddPlaceholderChunk("init-expression");
1590 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1591 Pattern->AddPlaceholderChunk("condition");
1592 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1593 Pattern->AddPlaceholderChunk("inc-expression");
1594 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1595 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +00001596 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001597 Pattern->AddPlaceholderChunk("statements");
1598 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1599 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1600 Results.AddResult(Result(Pattern));
1601 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001602
1603 if (S->getContinueParent()) {
1604 // continue ;
1605 Pattern = new CodeCompletionString;
1606 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001607 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001608 }
1609
1610 if (S->getBreakParent()) {
1611 // break ;
1612 Pattern = new CodeCompletionString;
1613 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001614 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001615 }
1616
1617 // "return expression ;" or "return ;", depending on whether we
1618 // know the function is void or not.
1619 bool isVoid = false;
1620 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1621 isVoid = Function->getResultType()->isVoidType();
1622 else if (ObjCMethodDecl *Method
1623 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1624 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001625 else if (SemaRef.getCurBlock() &&
1626 !SemaRef.getCurBlock()->ReturnType.isNull())
1627 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001628 Pattern = new CodeCompletionString;
1629 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001630 if (!isVoid) {
1631 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001632 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001633 }
Douglas Gregora4477812010-01-14 16:01:26 +00001634 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001635
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001636 // goto identifier ;
1637 Pattern = new CodeCompletionString;
1638 Pattern->AddTypedTextChunk("goto");
1639 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1640 Pattern->AddPlaceholderChunk("label");
1641 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001642
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001643 // Using directives
1644 Pattern = new CodeCompletionString;
1645 Pattern->AddTypedTextChunk("using");
1646 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1647 Pattern->AddTextChunk("namespace");
1648 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1649 Pattern->AddPlaceholderChunk("identifier");
1650 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001651 }
1652
1653 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001654 case Sema::PCC_ForInit:
1655 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001656 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001657 // Fall through: conditions and statements can have expressions.
1658
Douglas Gregor02688102010-09-14 23:59:36 +00001659 case Sema::PCC_ParenthesizedExpression:
John McCallf312b1e2010-08-26 23:41:50 +00001660 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001661 CodeCompletionString *Pattern = 0;
1662 if (SemaRef.getLangOptions().CPlusPlus) {
1663 // 'this', if we're in a non-static member function.
1664 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1665 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001666 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001667
1668 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001669 Results.AddResult(Result("true"));
1670 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001671
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001672 // dynamic_cast < type-id > ( expression )
1673 Pattern = new CodeCompletionString;
1674 Pattern->AddTypedTextChunk("dynamic_cast");
1675 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1676 Pattern->AddPlaceholderChunk("type");
1677 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1678 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1679 Pattern->AddPlaceholderChunk("expression");
1680 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1681 Results.AddResult(Result(Pattern));
1682
1683 // static_cast < type-id > ( expression )
1684 Pattern = new CodeCompletionString;
1685 Pattern->AddTypedTextChunk("static_cast");
1686 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1687 Pattern->AddPlaceholderChunk("type");
1688 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1689 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1690 Pattern->AddPlaceholderChunk("expression");
1691 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1692 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001693
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001694 // reinterpret_cast < type-id > ( expression )
1695 Pattern = new CodeCompletionString;
1696 Pattern->AddTypedTextChunk("reinterpret_cast");
1697 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1698 Pattern->AddPlaceholderChunk("type");
1699 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1700 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1701 Pattern->AddPlaceholderChunk("expression");
1702 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1703 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001704
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001705 // const_cast < type-id > ( expression )
1706 Pattern = new CodeCompletionString;
1707 Pattern->AddTypedTextChunk("const_cast");
1708 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1709 Pattern->AddPlaceholderChunk("type");
1710 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1711 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1712 Pattern->AddPlaceholderChunk("expression");
1713 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1714 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001715
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001716 // typeid ( expression-or-type )
1717 Pattern = new CodeCompletionString;
1718 Pattern->AddTypedTextChunk("typeid");
1719 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1720 Pattern->AddPlaceholderChunk("expression-or-type");
1721 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1722 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001723
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001724 // new T ( ... )
1725 Pattern = new CodeCompletionString;
1726 Pattern->AddTypedTextChunk("new");
1727 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1728 Pattern->AddPlaceholderChunk("type");
1729 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1730 Pattern->AddPlaceholderChunk("expressions");
1731 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1732 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001733
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001734 // new T [ ] ( ... )
1735 Pattern = new CodeCompletionString;
1736 Pattern->AddTypedTextChunk("new");
1737 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1738 Pattern->AddPlaceholderChunk("type");
1739 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1740 Pattern->AddPlaceholderChunk("size");
1741 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1742 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1743 Pattern->AddPlaceholderChunk("expressions");
1744 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1745 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001746
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001747 // delete expression
1748 Pattern = new CodeCompletionString;
1749 Pattern->AddTypedTextChunk("delete");
1750 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1751 Pattern->AddPlaceholderChunk("expression");
1752 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001753
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001754 // delete [] expression
1755 Pattern = new CodeCompletionString;
1756 Pattern->AddTypedTextChunk("delete");
1757 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1758 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1759 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1760 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1761 Pattern->AddPlaceholderChunk("expression");
1762 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001763
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001764 // throw expression
1765 Pattern = new CodeCompletionString;
1766 Pattern->AddTypedTextChunk("throw");
1767 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1768 Pattern->AddPlaceholderChunk("expression");
1769 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001770
1771 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001772 }
1773
1774 if (SemaRef.getLangOptions().ObjC1) {
1775 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001776 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1777 // The interface can be NULL.
1778 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1779 if (ID->getSuperClass())
1780 Results.AddResult(Result("super"));
1781 }
1782
Douglas Gregorbca403c2010-01-13 23:51:12 +00001783 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001784 }
1785
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001786 // sizeof expression
1787 Pattern = new CodeCompletionString;
1788 Pattern->AddTypedTextChunk("sizeof");
1789 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1790 Pattern->AddPlaceholderChunk("expression-or-type");
1791 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1792 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001793 break;
1794 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001795
John McCallf312b1e2010-08-26 23:41:50 +00001796 case Sema::PCC_Type:
Douglas Gregord32b0222010-08-24 01:06:58 +00001797 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001798 }
1799
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001800 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1801 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001802
John McCallf312b1e2010-08-26 23:41:50 +00001803 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001804 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001805}
1806
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001807/// \brief If the given declaration has an associated type, add it as a result
1808/// type chunk.
1809static void AddResultTypeChunk(ASTContext &Context,
1810 NamedDecl *ND,
1811 CodeCompletionString *Result) {
1812 if (!ND)
1813 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001814
1815 // Skip constructors and conversion functions, which have their return types
1816 // built into their names.
1817 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1818 return;
1819
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001820 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001821 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001822 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1823 T = Function->getResultType();
1824 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1825 T = Method->getResultType();
1826 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1827 T = FunTmpl->getTemplatedDecl()->getResultType();
1828 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1829 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1830 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1831 /* Do nothing: ignore unresolved using declarations*/
1832 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1833 T = Value->getType();
1834 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1835 T = Property->getType();
1836
1837 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1838 return;
1839
Douglas Gregor84139d62010-04-05 21:25:31 +00001840 PrintingPolicy Policy(Context.PrintingPolicy);
1841 Policy.AnonymousTagLocations = false;
1842
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001843 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001844 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001845 Result->AddResultTypeChunk(TypeStr);
1846}
1847
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001848static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1849 CodeCompletionString *Result) {
1850 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1851 if (Sentinel->getSentinel() == 0) {
1852 if (Context.getLangOptions().ObjC1 &&
1853 Context.Idents.get("nil").hasMacroDefinition())
1854 Result->AddTextChunk(", nil");
1855 else if (Context.Idents.get("NULL").hasMacroDefinition())
1856 Result->AddTextChunk(", NULL");
1857 else
1858 Result->AddTextChunk(", (void*)0");
1859 }
1860}
1861
Douglas Gregor83482d12010-08-24 16:15:59 +00001862static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001863 ParmVarDecl *Param,
1864 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001865 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1866 if (Param->getType()->isDependentType() ||
1867 !Param->getType()->isBlockPointerType()) {
1868 // The argument for a dependent or non-block parameter is a placeholder
1869 // containing that parameter's type.
1870 std::string Result;
1871
Douglas Gregoraba48082010-08-29 19:47:46 +00001872 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001873 Result = Param->getIdentifier()->getName();
1874
1875 Param->getType().getAsStringInternal(Result,
1876 Context.PrintingPolicy);
1877
1878 if (ObjCMethodParam) {
1879 Result = "(" + Result;
1880 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001881 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001882 Result += Param->getIdentifier()->getName();
1883 }
1884 return Result;
1885 }
1886
1887 // The argument for a block pointer parameter is a block literal with
1888 // the appropriate type.
1889 FunctionProtoTypeLoc *Block = 0;
1890 TypeLoc TL;
1891 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1892 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1893 while (true) {
1894 // Look through typedefs.
1895 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1896 if (TypeSourceInfo *InnerTSInfo
1897 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1898 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1899 continue;
1900 }
1901 }
1902
1903 // Look through qualified types
1904 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1905 TL = QualifiedTL->getUnqualifiedLoc();
1906 continue;
1907 }
1908
1909 // Try to get the function prototype behind the block pointer type,
1910 // then we're done.
1911 if (BlockPointerTypeLoc *BlockPtr
1912 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1913 TL = BlockPtr->getPointeeLoc();
1914 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1915 }
1916 break;
1917 }
1918 }
1919
1920 if (!Block) {
1921 // We were unable to find a FunctionProtoTypeLoc with parameter names
1922 // for the block; just use the parameter type as a placeholder.
1923 std::string Result;
1924 Param->getType().getUnqualifiedType().
1925 getAsStringInternal(Result, Context.PrintingPolicy);
1926
1927 if (ObjCMethodParam) {
1928 Result = "(" + Result;
1929 Result += ")";
1930 if (Param->getIdentifier())
1931 Result += Param->getIdentifier()->getName();
1932 }
1933
1934 return Result;
1935 }
1936
1937 // We have the function prototype behind the block pointer type, as it was
1938 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001939 std::string Result;
1940 QualType ResultType = Block->getTypePtr()->getResultType();
1941 if (!ResultType->isVoidType())
1942 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1943
1944 Result = '^' + Result;
1945 if (Block->getNumArgs() == 0) {
1946 if (Block->getTypePtr()->isVariadic())
1947 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001948 else
1949 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00001950 } else {
1951 Result += "(";
1952 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1953 if (I)
1954 Result += ", ";
1955 Result += FormatFunctionParameter(Context, Block->getArg(I));
1956
1957 if (I == N - 1 && Block->getTypePtr()->isVariadic())
1958 Result += ", ...";
1959 }
1960 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00001961 }
Douglas Gregor38276252010-09-08 22:47:51 +00001962
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001963 if (Param->getIdentifier())
1964 Result += Param->getIdentifier()->getName();
1965
Douglas Gregor83482d12010-08-24 16:15:59 +00001966 return Result;
1967}
1968
Douglas Gregor86d9a522009-09-21 16:56:56 +00001969/// \brief Add function parameter chunks to the given code completion string.
1970static void AddFunctionParameterChunks(ASTContext &Context,
1971 FunctionDecl *Function,
1972 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001973 typedef CodeCompletionString::Chunk Chunk;
1974
Douglas Gregor86d9a522009-09-21 16:56:56 +00001975 CodeCompletionString *CCStr = Result;
1976
1977 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1978 ParmVarDecl *Param = Function->getParamDecl(P);
1979
1980 if (Param->hasDefaultArg()) {
1981 // When we see an optional default argument, put that argument and
1982 // the remaining default arguments into a new, optional string.
1983 CodeCompletionString *Opt = new CodeCompletionString;
1984 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1985 CCStr = Opt;
1986 }
1987
1988 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001989 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001990
1991 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001992 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1993
Douglas Gregore17794f2010-08-31 05:13:43 +00001994 if (Function->isVariadic() && P == N - 1)
1995 PlaceholderStr += ", ...";
1996
Douglas Gregor86d9a522009-09-21 16:56:56 +00001997 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001998 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001999 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002000
2001 if (const FunctionProtoType *Proto
2002 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002003 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002004 if (Proto->getNumArgs() == 0)
2005 CCStr->AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002006
2007 MaybeAddSentinel(Context, Function, CCStr);
2008 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002009}
2010
2011/// \brief Add template parameter chunks to the given code completion string.
2012static void AddTemplateParameterChunks(ASTContext &Context,
2013 TemplateDecl *Template,
2014 CodeCompletionString *Result,
2015 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002016 typedef CodeCompletionString::Chunk Chunk;
2017
Douglas Gregor86d9a522009-09-21 16:56:56 +00002018 CodeCompletionString *CCStr = Result;
2019 bool FirstParameter = true;
2020
2021 TemplateParameterList *Params = Template->getTemplateParameters();
2022 TemplateParameterList::iterator PEnd = Params->end();
2023 if (MaxParameters)
2024 PEnd = Params->begin() + MaxParameters;
2025 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
2026 bool HasDefaultArg = false;
2027 std::string PlaceholderStr;
2028 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2029 if (TTP->wasDeclaredWithTypename())
2030 PlaceholderStr = "typename";
2031 else
2032 PlaceholderStr = "class";
2033
2034 if (TTP->getIdentifier()) {
2035 PlaceholderStr += ' ';
2036 PlaceholderStr += TTP->getIdentifier()->getName();
2037 }
2038
2039 HasDefaultArg = TTP->hasDefaultArgument();
2040 } else if (NonTypeTemplateParmDecl *NTTP
2041 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2042 if (NTTP->getIdentifier())
2043 PlaceholderStr = NTTP->getIdentifier()->getName();
2044 NTTP->getType().getAsStringInternal(PlaceholderStr,
2045 Context.PrintingPolicy);
2046 HasDefaultArg = NTTP->hasDefaultArgument();
2047 } else {
2048 assert(isa<TemplateTemplateParmDecl>(*P));
2049 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2050
2051 // Since putting the template argument list into the placeholder would
2052 // be very, very long, we just use an abbreviation.
2053 PlaceholderStr = "template<...> class";
2054 if (TTP->getIdentifier()) {
2055 PlaceholderStr += ' ';
2056 PlaceholderStr += TTP->getIdentifier()->getName();
2057 }
2058
2059 HasDefaultArg = TTP->hasDefaultArgument();
2060 }
2061
2062 if (HasDefaultArg) {
2063 // When we see an optional default argument, put that argument and
2064 // the remaining default arguments into a new, optional string.
2065 CodeCompletionString *Opt = new CodeCompletionString;
2066 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
2067 CCStr = Opt;
2068 }
2069
2070 if (FirstParameter)
2071 FirstParameter = false;
2072 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002073 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002074
2075 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002076 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002077 }
2078}
2079
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002080/// \brief Add a qualifier to the given code-completion string, if the
2081/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002082static void
2083AddQualifierToCompletionString(CodeCompletionString *Result,
2084 NestedNameSpecifier *Qualifier,
2085 bool QualifierIsInformative,
2086 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002087 if (!Qualifier)
2088 return;
2089
2090 std::string PrintedNNS;
2091 {
2092 llvm::raw_string_ostream OS(PrintedNNS);
2093 Qualifier->print(OS, Context.PrintingPolicy);
2094 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002095 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002096 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00002097 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002098 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002099}
2100
Douglas Gregora61a8792009-12-11 18:44:16 +00002101static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
2102 FunctionDecl *Function) {
2103 const FunctionProtoType *Proto
2104 = Function->getType()->getAs<FunctionProtoType>();
2105 if (!Proto || !Proto->getTypeQuals())
2106 return;
2107
2108 std::string QualsStr;
2109 if (Proto->getTypeQuals() & Qualifiers::Const)
2110 QualsStr += " const";
2111 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2112 QualsStr += " volatile";
2113 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2114 QualsStr += " restrict";
2115 Result->AddInformativeChunk(QualsStr);
2116}
2117
Douglas Gregor6f942b22010-09-21 16:06:22 +00002118/// \brief Add the name of the given declaration
2119static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
2120 CodeCompletionString *Result) {
2121 typedef CodeCompletionString::Chunk Chunk;
2122
2123 DeclarationName Name = ND->getDeclName();
2124 if (!Name)
2125 return;
2126
2127 switch (Name.getNameKind()) {
2128 case DeclarationName::Identifier:
2129 case DeclarationName::CXXConversionFunctionName:
2130 case DeclarationName::CXXOperatorName:
2131 case DeclarationName::CXXDestructorName:
2132 case DeclarationName::CXXLiteralOperatorName:
2133 Result->AddTypedTextChunk(ND->getNameAsString());
2134 break;
2135
2136 case DeclarationName::CXXUsingDirective:
2137 case DeclarationName::ObjCZeroArgSelector:
2138 case DeclarationName::ObjCOneArgSelector:
2139 case DeclarationName::ObjCMultiArgSelector:
2140 break;
2141
2142 case DeclarationName::CXXConstructorName: {
2143 CXXRecordDecl *Record = 0;
2144 QualType Ty = Name.getCXXNameType();
2145 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2146 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2147 else if (const InjectedClassNameType *InjectedTy
2148 = Ty->getAs<InjectedClassNameType>())
2149 Record = InjectedTy->getDecl();
2150 else {
2151 Result->AddTypedTextChunk(ND->getNameAsString());
2152 break;
2153 }
2154
2155 Result->AddTypedTextChunk(Record->getNameAsString());
2156 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2157 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2158 AddTemplateParameterChunks(Context, Template, Result);
2159 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2160 }
2161 break;
2162 }
2163 }
2164}
2165
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166/// \brief If possible, create a new code completion string for the given
2167/// result.
2168///
2169/// \returns Either a new, heap-allocated code completion string describing
2170/// how to use this result, or NULL to indicate that the string or name of the
2171/// result is all that is needed.
2172CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002173CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor6f942b22010-09-21 16:06:22 +00002174 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002175 typedef CodeCompletionString::Chunk Chunk;
2176
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002177 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002178 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002179
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002180 if (!Result)
2181 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002182
2183 if (Kind == RK_Keyword) {
2184 Result->AddTypedTextChunk(Keyword);
2185 return Result;
2186 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002187
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002188 if (Kind == RK_Macro) {
2189 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002190 assert(MI && "Not a macro?");
2191
2192 Result->AddTypedTextChunk(Macro->getName());
2193
2194 if (!MI->isFunctionLike())
2195 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002196
2197 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002198 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002199 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2200 A != AEnd; ++A) {
2201 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002202 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002203
2204 if (!MI->isVariadic() || A != AEnd - 1) {
2205 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002206 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002207 continue;
2208 }
2209
2210 // Variadic argument; cope with the different between GNU and C99
2211 // variadic macros, providing a single placeholder for the rest of the
2212 // arguments.
2213 if ((*A)->isStr("__VA_ARGS__"))
2214 Result->AddPlaceholderChunk("...");
2215 else {
2216 std::string Arg = (*A)->getName();
2217 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00002218 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002219 }
2220 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002221 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002222 return Result;
2223 }
2224
Douglas Gregord8e8a582010-05-25 21:41:55 +00002225 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002226 NamedDecl *ND = Declaration;
2227
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002228 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002229 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002230 Result->AddTextChunk("::");
2231 return Result;
2232 }
2233
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002234 AddResultTypeChunk(S.Context, ND, Result);
2235
Douglas Gregor86d9a522009-09-21 16:56:56 +00002236 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002237 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2238 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002239 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002240 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002241 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002242 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002243 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002244 return Result;
2245 }
2246
2247 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002248 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2249 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002250 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002251 AddTypedNameChunk(S.Context, Function, Result);
2252
Douglas Gregor86d9a522009-09-21 16:56:56 +00002253 // Figure out which template parameters are deduced (or have default
2254 // arguments).
2255 llvm::SmallVector<bool, 16> Deduced;
2256 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2257 unsigned LastDeducibleArgument;
2258 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2259 --LastDeducibleArgument) {
2260 if (!Deduced[LastDeducibleArgument - 1]) {
2261 // C++0x: Figure out if the template argument has a default. If so,
2262 // the user doesn't need to type this argument.
2263 // FIXME: We need to abstract template parameters better!
2264 bool HasDefaultArg = false;
2265 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2266 LastDeducibleArgument - 1);
2267 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2268 HasDefaultArg = TTP->hasDefaultArgument();
2269 else if (NonTypeTemplateParmDecl *NTTP
2270 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2271 HasDefaultArg = NTTP->hasDefaultArgument();
2272 else {
2273 assert(isa<TemplateTemplateParmDecl>(Param));
2274 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002275 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002276 }
2277
2278 if (!HasDefaultArg)
2279 break;
2280 }
2281 }
2282
2283 if (LastDeducibleArgument) {
2284 // Some of the function template arguments cannot be deduced from a
2285 // function call, so we introduce an explicit template argument list
2286 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002287 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002288 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2289 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002290 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002291 }
2292
2293 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002294 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002295 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002296 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002297 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002298 return Result;
2299 }
2300
2301 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002302 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2303 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002304 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002305 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002306 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002307 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002308 return Result;
2309 }
2310
Douglas Gregor9630eb62009-11-17 16:44:22 +00002311 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002312 Selector Sel = Method->getSelector();
2313 if (Sel.isUnarySelector()) {
2314 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2315 return Result;
2316 }
2317
Douglas Gregord3c68542009-11-19 01:08:35 +00002318 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2319 SelName += ':';
2320 if (StartParameter == 0)
2321 Result->AddTypedTextChunk(SelName);
2322 else {
2323 Result->AddInformativeChunk(SelName);
2324
2325 // If there is only one parameter, and we're past it, add an empty
2326 // typed-text chunk since there is nothing to type.
2327 if (Method->param_size() == 1)
2328 Result->AddTypedTextChunk("");
2329 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002330 unsigned Idx = 0;
2331 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2332 PEnd = Method->param_end();
2333 P != PEnd; (void)++P, ++Idx) {
2334 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002335 std::string Keyword;
2336 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002337 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002338 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2339 Keyword += II->getName().str();
2340 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002341 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002342 Result->AddInformativeChunk(Keyword);
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002343 else
Douglas Gregord3c68542009-11-19 01:08:35 +00002344 Result->AddTypedTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002345 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002346
2347 // If we're before the starting parameter, skip the placeholder.
2348 if (Idx < StartParameter)
2349 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002350
2351 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002352
2353 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002354 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002355 else {
2356 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2357 Arg = "(" + Arg + ")";
2358 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002359 if (DeclaringEntity || AllParametersAreInformative)
2360 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002361 }
2362
Douglas Gregore17794f2010-08-31 05:13:43 +00002363 if (Method->isVariadic() && (P + 1) == PEnd)
2364 Arg += ", ...";
2365
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002366 if (DeclaringEntity)
2367 Result->AddTextChunk(Arg);
2368 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002369 Result->AddInformativeChunk(Arg);
2370 else
2371 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002372 }
2373
Douglas Gregor2a17af02009-12-23 00:21:46 +00002374 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002375 if (Method->param_size() == 0) {
2376 if (DeclaringEntity)
2377 Result->AddTextChunk(", ...");
2378 else if (AllParametersAreInformative)
2379 Result->AddInformativeChunk(", ...");
2380 else
2381 Result->AddPlaceholderChunk(", ...");
2382 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002383
2384 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002385 }
2386
Douglas Gregor9630eb62009-11-17 16:44:22 +00002387 return Result;
2388 }
2389
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002390 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002391 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2392 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002393
2394 Result->AddTypedTextChunk(ND->getNameAsString());
2395 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002396}
2397
Douglas Gregor86d802e2009-09-23 00:34:09 +00002398CodeCompletionString *
2399CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2400 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002401 Sema &S,
2402 CodeCompletionString *Result) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002403 typedef CodeCompletionString::Chunk Chunk;
2404
Douglas Gregor32be4a52010-10-11 21:37:58 +00002405 if (!Result)
2406 Result = new CodeCompletionString;
Douglas Gregor86d802e2009-09-23 00:34:09 +00002407 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002408 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002409 const FunctionProtoType *Proto
2410 = dyn_cast<FunctionProtoType>(getFunctionType());
2411 if (!FDecl && !Proto) {
2412 // Function without a prototype. Just give the return type and a
2413 // highlighted ellipsis.
2414 const FunctionType *FT = getFunctionType();
2415 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002416 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002417 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2418 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2419 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002420 return Result;
2421 }
2422
2423 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002424 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002425 else
2426 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002427 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002428
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002429 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002430 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2431 for (unsigned I = 0; I != NumParams; ++I) {
2432 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002433 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002434
2435 std::string ArgString;
2436 QualType ArgType;
2437
2438 if (FDecl) {
2439 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2440 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2441 } else {
2442 ArgType = Proto->getArgType(I);
2443 }
2444
2445 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2446
2447 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002448 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002449 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002450 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002451 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002452 }
2453
2454 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002455 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002456 if (CurrentArg < NumParams)
2457 Result->AddTextChunk("...");
2458 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002459 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002460 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002461 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002462
2463 return Result;
2464}
2465
Douglas Gregor1827e102010-08-16 16:18:59 +00002466unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002467 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002468 bool PreferredTypeIsPointer) {
2469 unsigned Priority = CCP_Macro;
2470
Douglas Gregorb05496d2010-09-20 21:11:48 +00002471 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2472 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2473 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002474 Priority = CCP_Constant;
2475 if (PreferredTypeIsPointer)
2476 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002477 }
2478 // Treat "YES", "NO", "true", and "false" as constants.
2479 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2480 MacroName.equals("true") || MacroName.equals("false"))
2481 Priority = CCP_Constant;
2482 // Treat "bool" as a type.
2483 else if (MacroName.equals("bool"))
2484 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2485
Douglas Gregor1827e102010-08-16 16:18:59 +00002486
2487 return Priority;
2488}
2489
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002490CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2491 if (!D)
2492 return CXCursor_UnexposedDecl;
2493
2494 switch (D->getKind()) {
2495 case Decl::Enum: return CXCursor_EnumDecl;
2496 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2497 case Decl::Field: return CXCursor_FieldDecl;
2498 case Decl::Function:
2499 return CXCursor_FunctionDecl;
2500 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2501 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2502 case Decl::ObjCClass:
2503 // FIXME
2504 return CXCursor_UnexposedDecl;
2505 case Decl::ObjCForwardProtocol:
2506 // FIXME
2507 return CXCursor_UnexposedDecl;
2508 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2509 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2510 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2511 case Decl::ObjCMethod:
2512 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2513 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2514 case Decl::CXXMethod: return CXCursor_CXXMethod;
2515 case Decl::CXXConstructor: return CXCursor_Constructor;
2516 case Decl::CXXDestructor: return CXCursor_Destructor;
2517 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2518 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2519 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2520 case Decl::ParmVar: return CXCursor_ParmDecl;
2521 case Decl::Typedef: return CXCursor_TypedefDecl;
2522 case Decl::Var: return CXCursor_VarDecl;
2523 case Decl::Namespace: return CXCursor_Namespace;
2524 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2525 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2526 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2527 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2528 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2529 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2530 case Decl::ClassTemplatePartialSpecialization:
2531 return CXCursor_ClassTemplatePartialSpecialization;
2532 case Decl::UsingDirective: return CXCursor_UsingDirective;
2533
2534 case Decl::Using:
2535 case Decl::UnresolvedUsingValue:
2536 case Decl::UnresolvedUsingTypename:
2537 return CXCursor_UsingDeclaration;
2538
2539 default:
2540 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2541 switch (TD->getTagKind()) {
2542 case TTK_Struct: return CXCursor_StructDecl;
2543 case TTK_Class: return CXCursor_ClassDecl;
2544 case TTK_Union: return CXCursor_UnionDecl;
2545 case TTK_Enum: return CXCursor_EnumDecl;
2546 }
2547 }
2548 }
2549
2550 return CXCursor_UnexposedDecl;
2551}
2552
Douglas Gregor590c7d52010-07-08 20:55:51 +00002553static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2554 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002555 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002556
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002557 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002558
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002559 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2560 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002561 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002562 Results.AddResult(Result(M->first,
2563 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002564 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002565 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002566 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002567
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002568 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002569
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002570}
2571
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002572static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2573 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002574 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002575
2576 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002577
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002578 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2579 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2580 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2581 Results.AddResult(Result("__func__", CCP_Constant));
2582 Results.ExitScope();
2583}
2584
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002585static void HandleCodeCompleteResults(Sema *S,
2586 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002587 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002588 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002589 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002590 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002591 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002592
2593 for (unsigned I = 0; I != NumResults; ++I)
2594 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002595}
2596
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002597static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2598 Sema::ParserCompletionContext PCC) {
2599 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002600 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002601 return CodeCompletionContext::CCC_TopLevel;
2602
John McCallf312b1e2010-08-26 23:41:50 +00002603 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002604 return CodeCompletionContext::CCC_ClassStructUnion;
2605
John McCallf312b1e2010-08-26 23:41:50 +00002606 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002607 return CodeCompletionContext::CCC_ObjCInterface;
2608
John McCallf312b1e2010-08-26 23:41:50 +00002609 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002610 return CodeCompletionContext::CCC_ObjCImplementation;
2611
John McCallf312b1e2010-08-26 23:41:50 +00002612 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002613 return CodeCompletionContext::CCC_ObjCIvarList;
2614
John McCallf312b1e2010-08-26 23:41:50 +00002615 case Sema::PCC_Template:
2616 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002617 if (S.CurContext->isFileContext())
2618 return CodeCompletionContext::CCC_TopLevel;
2619 else if (S.CurContext->isRecord())
2620 return CodeCompletionContext::CCC_ClassStructUnion;
2621 else
2622 return CodeCompletionContext::CCC_Other;
2623
John McCallf312b1e2010-08-26 23:41:50 +00002624 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002625 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002626
John McCallf312b1e2010-08-26 23:41:50 +00002627 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002628 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2629 S.getLangOptions().ObjC1)
2630 return CodeCompletionContext::CCC_ParenthesizedExpression;
2631 else
2632 return CodeCompletionContext::CCC_Expression;
2633
2634 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002635 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002636 return CodeCompletionContext::CCC_Expression;
2637
John McCallf312b1e2010-08-26 23:41:50 +00002638 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002639 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002640
John McCallf312b1e2010-08-26 23:41:50 +00002641 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002642 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002643
2644 case Sema::PCC_ParenthesizedExpression:
2645 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002646 }
2647
2648 return CodeCompletionContext::CCC_Other;
2649}
2650
Douglas Gregorf6961522010-08-27 21:18:54 +00002651/// \brief If we're in a C++ virtual member function, add completion results
2652/// that invoke the functions we override, since it's common to invoke the
2653/// overridden function as well as adding new functionality.
2654///
2655/// \param S The semantic analysis object for which we are generating results.
2656///
2657/// \param InContext This context in which the nested-name-specifier preceding
2658/// the code-completion point
2659static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2660 ResultBuilder &Results) {
2661 // Look through blocks.
2662 DeclContext *CurContext = S.CurContext;
2663 while (isa<BlockDecl>(CurContext))
2664 CurContext = CurContext->getParent();
2665
2666
2667 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2668 if (!Method || !Method->isVirtual())
2669 return;
2670
2671 // We need to have names for all of the parameters, if we're going to
2672 // generate a forwarding call.
2673 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2674 PEnd = Method->param_end();
2675 P != PEnd;
2676 ++P) {
2677 if (!(*P)->getDeclName())
2678 return;
2679 }
2680
2681 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2682 MEnd = Method->end_overridden_methods();
2683 M != MEnd; ++M) {
2684 CodeCompletionString *Pattern = new CodeCompletionString;
2685 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2686 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2687 continue;
2688
2689 // If we need a nested-name-specifier, add one now.
2690 if (!InContext) {
2691 NestedNameSpecifier *NNS
2692 = getRequiredQualification(S.Context, CurContext,
2693 Overridden->getDeclContext());
2694 if (NNS) {
2695 std::string Str;
2696 llvm::raw_string_ostream OS(Str);
2697 NNS->print(OS, S.Context.PrintingPolicy);
2698 Pattern->AddTextChunk(OS.str());
2699 }
2700 } else if (!InContext->Equals(Overridden->getDeclContext()))
2701 continue;
2702
2703 Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2704 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2705 bool FirstParam = true;
2706 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2707 PEnd = Method->param_end();
2708 P != PEnd; ++P) {
2709 if (FirstParam)
2710 FirstParam = false;
2711 else
2712 Pattern->AddChunk(CodeCompletionString::CK_Comma);
2713
2714 Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2715 }
2716 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2717 Results.AddResult(CodeCompletionResult(Pattern,
2718 CCP_SuperCompletion,
2719 CXCursor_CXXMethod));
2720 Results.Ignore(Overridden);
2721 }
2722}
2723
Douglas Gregor01dfea02010-01-10 23:08:15 +00002724void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002725 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002726 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002727 ResultBuilder Results(*this,
2728 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002729 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002730
Douglas Gregor01dfea02010-01-10 23:08:15 +00002731 // Determine how to filter results, e.g., so that the names of
2732 // values (functions, enumerators, function templates, etc.) are
2733 // only allowed where we can have an expression.
2734 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002735 case PCC_Namespace:
2736 case PCC_Class:
2737 case PCC_ObjCInterface:
2738 case PCC_ObjCImplementation:
2739 case PCC_ObjCInstanceVariableList:
2740 case PCC_Template:
2741 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002742 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002743 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2744 break;
2745
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002746 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002747 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002748 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002749 case PCC_ForInit:
2750 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002751 if (WantTypesInContext(CompletionContext, getLangOptions()))
2752 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2753 else
2754 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002755
2756 if (getLangOptions().CPlusPlus)
2757 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002758 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002759
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002760 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002761 // Unfiltered
2762 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002763 }
2764
Douglas Gregor3cdee122010-08-26 16:36:48 +00002765 // If we are in a C++ non-static member function, check the qualifiers on
2766 // the member function to filter/prioritize the results list.
2767 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2768 if (CurMethod->isInstance())
2769 Results.setObjectTypeQualifiers(
2770 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2771
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002772 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002773 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2774 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002775
Douglas Gregorbca403c2010-01-13 23:51:12 +00002776 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002777 Results.ExitScope();
2778
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002779 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002780 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002781 case PCC_Expression:
2782 case PCC_Statement:
2783 case PCC_RecoveryInFunction:
2784 if (S->getFnParent())
2785 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2786 break;
2787
2788 case PCC_Namespace:
2789 case PCC_Class:
2790 case PCC_ObjCInterface:
2791 case PCC_ObjCImplementation:
2792 case PCC_ObjCInstanceVariableList:
2793 case PCC_Template:
2794 case PCC_MemberTemplate:
2795 case PCC_ForInit:
2796 case PCC_Condition:
2797 case PCC_Type:
2798 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002799 }
2800
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002801 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002802 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002803
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002804 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002806}
2807
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002808static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2809 ParsedType Receiver,
2810 IdentifierInfo **SelIdents,
2811 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002812 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002813 bool IsSuper,
2814 ResultBuilder &Results);
2815
2816void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2817 bool AllowNonIdentifiers,
2818 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002819 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002820 ResultBuilder Results(*this,
2821 AllowNestedNameSpecifiers
2822 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2823 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002824 Results.EnterNewScope();
2825
2826 // Type qualifiers can come after names.
2827 Results.AddResult(Result("const"));
2828 Results.AddResult(Result("volatile"));
2829 if (getLangOptions().C99)
2830 Results.AddResult(Result("restrict"));
2831
2832 if (getLangOptions().CPlusPlus) {
2833 if (AllowNonIdentifiers) {
2834 Results.AddResult(Result("operator"));
2835 }
2836
2837 // Add nested-name-specifiers.
2838 if (AllowNestedNameSpecifiers) {
2839 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00002840 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002841 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2842 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2843 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00002844 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002845 }
2846 }
2847 Results.ExitScope();
2848
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002849 // If we're in a context where we might have an expression (rather than a
2850 // declaration), and what we've seen so far is an Objective-C type that could
2851 // be a receiver of a class message, this may be a class message send with
2852 // the initial opening bracket '[' missing. Add appropriate completions.
2853 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2854 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2855 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2856 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2857 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2858 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2859 DS.getTypeQualifiers() == 0 &&
2860 S &&
2861 (S->getFlags() & Scope::DeclScope) != 0 &&
2862 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2863 Scope::FunctionPrototypeScope |
2864 Scope::AtCatchScope)) == 0) {
2865 ParsedType T = DS.getRepAsType();
2866 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002867 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002868 }
2869
Douglas Gregor4497dd42010-08-24 04:59:56 +00002870 // Note that we intentionally suppress macro results here, since we do not
2871 // encourage using macros to produce the names of entities.
2872
Douglas Gregor52779fb2010-09-23 23:01:17 +00002873 HandleCodeCompleteResults(this, CodeCompleter,
2874 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002875 Results.data(), Results.size());
2876}
2877
Douglas Gregorfb629412010-08-23 21:17:50 +00002878struct Sema::CodeCompleteExpressionData {
2879 CodeCompleteExpressionData(QualType PreferredType = QualType())
2880 : PreferredType(PreferredType), IntegralConstantExpression(false),
2881 ObjCCollection(false) { }
2882
2883 QualType PreferredType;
2884 bool IntegralConstantExpression;
2885 bool ObjCCollection;
2886 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2887};
2888
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002889/// \brief Perform code-completion in an expression context when we know what
2890/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002891///
2892/// \param IntegralConstantExpression Only permit integral constant
2893/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002894void Sema::CodeCompleteExpression(Scope *S,
2895 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002896 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002897 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00002898 if (Data.ObjCCollection)
2899 Results.setFilter(&ResultBuilder::IsObjCCollection);
2900 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002901 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002902 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002903 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2904 else
2905 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002906
2907 if (!Data.PreferredType.isNull())
2908 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2909
2910 // Ignore any declarations that we were told that we don't care about.
2911 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2912 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002913
2914 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002915 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2916 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002917
2918 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002919 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002920 Results.ExitScope();
2921
Douglas Gregor590c7d52010-07-08 20:55:51 +00002922 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002923 if (!Data.PreferredType.isNull())
2924 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2925 || Data.PreferredType->isMemberPointerType()
2926 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002927
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002928 if (S->getFnParent() &&
2929 !Data.ObjCCollection &&
2930 !Data.IntegralConstantExpression)
2931 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2932
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002933 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002934 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002935 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002936 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2937 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002938 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002939}
2940
Douglas Gregorac5fd842010-09-18 01:28:11 +00002941void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
2942 if (E.isInvalid())
2943 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
2944 else if (getLangOptions().ObjC1)
2945 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00002946}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002947
Douglas Gregor95ac6552009-11-18 01:29:26 +00002948static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002949 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002950 DeclContext *CurContext,
2951 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002952 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002953
2954 // Add properties in this container.
2955 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2956 PEnd = Container->prop_end();
2957 P != PEnd;
2958 ++P)
2959 Results.MaybeAddResult(Result(*P, 0), CurContext);
2960
2961 // Add properties in referenced protocols.
2962 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2963 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2964 PEnd = Protocol->protocol_end();
2965 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002966 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002967 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002968 if (AllowCategories) {
2969 // Look through categories.
2970 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2971 Category; Category = Category->getNextClassCategory())
2972 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2973 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002974
2975 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002976 for (ObjCInterfaceDecl::all_protocol_iterator
2977 I = IFace->all_referenced_protocol_begin(),
2978 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002979 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002980
2981 // Look in the superclass.
2982 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002983 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2984 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002985 } else if (const ObjCCategoryDecl *Category
2986 = dyn_cast<ObjCCategoryDecl>(Container)) {
2987 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002988 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
2989 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002990 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002991 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002992 }
2993}
2994
Douglas Gregor81b747b2009-09-17 21:32:03 +00002995void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2996 SourceLocation OpLoc,
2997 bool IsArrow) {
2998 if (!BaseE || !CodeCompleter)
2999 return;
3000
John McCall0a2c5e22010-08-25 06:19:51 +00003001 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003002
Douglas Gregor81b747b2009-09-17 21:32:03 +00003003 Expr *Base = static_cast<Expr *>(BaseE);
3004 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003005
3006 if (IsArrow) {
3007 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3008 BaseType = Ptr->getPointeeType();
3009 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003010 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003011 else
3012 return;
3013 }
3014
Douglas Gregor52779fb2010-09-23 23:01:17 +00003015 ResultBuilder Results(*this,
3016 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3017 BaseType),
3018 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003019 Results.EnterNewScope();
3020 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003021 // Indicate that we are performing a member access, and the cv-qualifiers
3022 // for the base object type.
3023 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3024
Douglas Gregor95ac6552009-11-18 01:29:26 +00003025 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003026 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003027 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003028 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3029 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003030
Douglas Gregor95ac6552009-11-18 01:29:26 +00003031 if (getLangOptions().CPlusPlus) {
3032 if (!Results.empty()) {
3033 // The "template" keyword can follow "->" or "." in the grammar.
3034 // However, we only want to suggest the template keyword if something
3035 // is dependent.
3036 bool IsDependent = BaseType->isDependentType();
3037 if (!IsDependent) {
3038 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3039 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3040 IsDependent = Ctx->isDependentContext();
3041 break;
3042 }
3043 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003044
Douglas Gregor95ac6552009-11-18 01:29:26 +00003045 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003046 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003047 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003048 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003049 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3050 // Objective-C property reference.
3051
3052 // Add property results based on our interface.
3053 const ObjCObjectPointerType *ObjCPtr
3054 = BaseType->getAsObjCInterfacePointerType();
3055 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00003056 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003057
3058 // Add properties from the protocols in a qualified interface.
3059 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3060 E = ObjCPtr->qual_end();
3061 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00003062 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003063 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003064 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003065 // Objective-C instance variable access.
3066 ObjCInterfaceDecl *Class = 0;
3067 if (const ObjCObjectPointerType *ObjCPtr
3068 = BaseType->getAs<ObjCObjectPointerType>())
3069 Class = ObjCPtr->getInterfaceDecl();
3070 else
John McCallc12c5bb2010-05-15 11:32:37 +00003071 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003072
3073 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003074 if (Class) {
3075 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3076 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003077 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3078 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003079 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003080 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003081
3082 // FIXME: How do we cope with isa?
3083
3084 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003085
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003086 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003087 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003088 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003089 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003090}
3091
Douglas Gregor374929f2009-09-18 15:37:17 +00003092void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3093 if (!CodeCompleter)
3094 return;
3095
John McCall0a2c5e22010-08-25 06:19:51 +00003096 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003097 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003098 enum CodeCompletionContext::Kind ContextKind
3099 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003100 switch ((DeclSpec::TST)TagSpec) {
3101 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003102 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003103 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003104 break;
3105
3106 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003107 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003108 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003109 break;
3110
3111 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003112 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003113 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003114 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003115 break;
3116
3117 default:
3118 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3119 return;
3120 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003121
Douglas Gregor52779fb2010-09-23 23:01:17 +00003122 ResultBuilder Results(*this, ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003123 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003124
3125 // First pass: look for tags.
3126 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003127 LookupVisibleDecls(S, LookupTagName, Consumer,
3128 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003129
Douglas Gregor8071e422010-08-15 06:18:01 +00003130 if (CodeCompleter->includeGlobals()) {
3131 // Second pass: look for nested name specifiers.
3132 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3133 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3134 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003135
Douglas Gregor52779fb2010-09-23 23:01:17 +00003136 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003137 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003138}
3139
Douglas Gregor1a480c42010-08-27 17:35:51 +00003140void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003141 ResultBuilder Results(*this, CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003142 Results.EnterNewScope();
3143 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3144 Results.AddResult("const");
3145 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3146 Results.AddResult("volatile");
3147 if (getLangOptions().C99 &&
3148 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3149 Results.AddResult("restrict");
3150 Results.ExitScope();
3151 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003152 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003153 Results.data(), Results.size());
3154}
3155
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003156void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003157 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003158 return;
3159
John McCall781472f2010-08-25 08:40:02 +00003160 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003161 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003162 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3163 Data.IntegralConstantExpression = true;
3164 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003165 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003166 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003167
3168 // Code-complete the cases of a switch statement over an enumeration type
3169 // by providing the list of
3170 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3171
3172 // Determine which enumerators we have already seen in the switch statement.
3173 // FIXME: Ideally, we would also be able to look *past* the code-completion
3174 // token, in case we are code-completing in the middle of the switch and not
3175 // at the end. However, we aren't able to do so at the moment.
3176 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003177 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003178 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3179 SC = SC->getNextSwitchCase()) {
3180 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3181 if (!Case)
3182 continue;
3183
3184 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3186 if (EnumConstantDecl *Enumerator
3187 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3188 // We look into the AST of the case statement to determine which
3189 // enumerator was named. Alternatively, we could compute the value of
3190 // the integral constant expression, then compare it against the
3191 // values of each enumerator. However, value-based approach would not
3192 // work as well with C++ templates where enumerators declared within a
3193 // template are type- and value-dependent.
3194 EnumeratorsSeen.insert(Enumerator);
3195
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003196 // If this is a qualified-id, keep track of the nested-name-specifier
3197 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003198 //
3199 // switch (TagD.getKind()) {
3200 // case TagDecl::TK_enum:
3201 // break;
3202 // case XXX
3203 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003204 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003205 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3206 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003207 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003208 }
3209 }
3210
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003211 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3212 // If there are no prior enumerators in C++, check whether we have to
3213 // qualify the names of the enumerators that we suggest, because they
3214 // may not be visible in this scope.
3215 Qualifier = getRequiredQualification(Context, CurContext,
3216 Enum->getDeclContext());
3217
3218 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3219 }
3220
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003221 // Add any enumerators that have not yet been mentioned.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003222 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003223 Results.EnterNewScope();
3224 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3225 EEnd = Enum->enumerator_end();
3226 E != EEnd; ++E) {
3227 if (EnumeratorsSeen.count(*E))
3228 continue;
3229
John McCall0a2c5e22010-08-25 06:19:51 +00003230 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00003231 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003232 }
3233 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003234
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003235 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003236 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003237 HandleCodeCompleteResults(this, CodeCompleter,
3238 CodeCompletionContext::CCC_Expression,
3239 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003240}
3241
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003242namespace {
3243 struct IsBetterOverloadCandidate {
3244 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003245 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003246
3247 public:
John McCall5769d612010-02-08 23:07:23 +00003248 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3249 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003250
3251 bool
3252 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003253 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003254 }
3255 };
3256}
3257
Douglas Gregord28dcd72010-05-30 06:10:08 +00003258static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3259 if (NumArgs && !Args)
3260 return true;
3261
3262 for (unsigned I = 0; I != NumArgs; ++I)
3263 if (!Args[I])
3264 return true;
3265
3266 return false;
3267}
3268
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003269void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3270 ExprTy **ArgsIn, unsigned NumArgs) {
3271 if (!CodeCompleter)
3272 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003273
3274 // When we're code-completing for a call, we fall back to ordinary
3275 // name code-completion whenever we can't produce specific
3276 // results. We may want to revisit this strategy in the future,
3277 // e.g., by merging the two kinds of results.
3278
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003279 Expr *Fn = (Expr *)FnIn;
3280 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003281
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003282 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003283 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003284 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003285 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003286 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003287 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003288
John McCall3b4294e2009-12-16 12:17:52 +00003289 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003290 SourceLocation Loc = Fn->getExprLoc();
3291 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003292
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003293 // FIXME: What if we're calling something that isn't a function declaration?
3294 // FIXME: What if we're calling a pseudo-destructor?
3295 // FIXME: What if we're calling a member function?
3296
Douglas Gregorc0265402010-01-21 15:46:19 +00003297 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3298 llvm::SmallVector<ResultCandidate, 8> Results;
3299
John McCall3b4294e2009-12-16 12:17:52 +00003300 Expr *NakedFn = Fn->IgnoreParenCasts();
3301 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3302 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3303 /*PartialOverloading=*/ true);
3304 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3305 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003306 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003307 if (!getLangOptions().CPlusPlus ||
3308 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003309 Results.push_back(ResultCandidate(FDecl));
3310 else
John McCall86820f52010-01-26 01:37:31 +00003311 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003312 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3313 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003314 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003315 }
John McCall3b4294e2009-12-16 12:17:52 +00003316 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003317
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003318 QualType ParamType;
3319
Douglas Gregorc0265402010-01-21 15:46:19 +00003320 if (!CandidateSet.empty()) {
3321 // Sort the overload candidate set by placing the best overloads first.
3322 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003323 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003324
Douglas Gregorc0265402010-01-21 15:46:19 +00003325 // Add the remaining viable overload candidates as code-completion reslults.
3326 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3327 CandEnd = CandidateSet.end();
3328 Cand != CandEnd; ++Cand) {
3329 if (Cand->Viable)
3330 Results.push_back(ResultCandidate(Cand->Function));
3331 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003332
3333 // From the viable candidates, try to determine the type of this parameter.
3334 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3335 if (const FunctionType *FType = Results[I].getFunctionType())
3336 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3337 if (NumArgs < Proto->getNumArgs()) {
3338 if (ParamType.isNull())
3339 ParamType = Proto->getArgType(NumArgs);
3340 else if (!Context.hasSameUnqualifiedType(
3341 ParamType.getNonReferenceType(),
3342 Proto->getArgType(NumArgs).getNonReferenceType())) {
3343 ParamType = QualType();
3344 break;
3345 }
3346 }
3347 }
3348 } else {
3349 // Try to determine the parameter type from the type of the expression
3350 // being called.
3351 QualType FunctionType = Fn->getType();
3352 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3353 FunctionType = Ptr->getPointeeType();
3354 else if (const BlockPointerType *BlockPtr
3355 = FunctionType->getAs<BlockPointerType>())
3356 FunctionType = BlockPtr->getPointeeType();
3357 else if (const MemberPointerType *MemPtr
3358 = FunctionType->getAs<MemberPointerType>())
3359 FunctionType = MemPtr->getPointeeType();
3360
3361 if (const FunctionProtoType *Proto
3362 = FunctionType->getAs<FunctionProtoType>()) {
3363 if (NumArgs < Proto->getNumArgs())
3364 ParamType = Proto->getArgType(NumArgs);
3365 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003366 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003367
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003368 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003369 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003370 else
3371 CodeCompleteExpression(S, ParamType);
3372
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003373 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003374 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3375 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003376}
3377
John McCalld226f652010-08-21 09:40:31 +00003378void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3379 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003380 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003381 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003382 return;
3383 }
3384
3385 CodeCompleteExpression(S, VD->getType());
3386}
3387
3388void Sema::CodeCompleteReturn(Scope *S) {
3389 QualType ResultType;
3390 if (isa<BlockDecl>(CurContext)) {
3391 if (BlockScopeInfo *BSI = getCurBlock())
3392 ResultType = BSI->ReturnType;
3393 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3394 ResultType = Function->getResultType();
3395 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3396 ResultType = Method->getResultType();
3397
3398 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003399 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003400 else
3401 CodeCompleteExpression(S, ResultType);
3402}
3403
3404void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3405 if (LHS)
3406 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3407 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003408 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003409}
3410
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003411void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003412 bool EnteringContext) {
3413 if (!SS.getScopeRep() || !CodeCompleter)
3414 return;
3415
Douglas Gregor86d9a522009-09-21 16:56:56 +00003416 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3417 if (!Ctx)
3418 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003419
3420 // Try to instantiate any non-dependent declaration contexts before
3421 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003422 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003423 return;
3424
Douglas Gregor52779fb2010-09-23 23:01:17 +00003425 ResultBuilder Results(*this, CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003426 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003427
Douglas Gregor86d9a522009-09-21 16:56:56 +00003428 // The "template" keyword can follow "::" in the grammar, but only
3429 // put it into the grammar if the nested-name-specifier is dependent.
3430 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3431 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003432 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003433
3434 // Add calls to overridden virtual functions, if there are any.
3435 //
3436 // FIXME: This isn't wonderful, because we don't know whether we're actually
3437 // in a context that permits expressions. This is a general issue with
3438 // qualified-id completions.
3439 if (!EnteringContext)
3440 MaybeAddOverrideCalls(*this, Ctx, Results);
3441 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003442
Douglas Gregorf6961522010-08-27 21:18:54 +00003443 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3444 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3445
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003446 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003447 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003448 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003449}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003450
3451void Sema::CodeCompleteUsing(Scope *S) {
3452 if (!CodeCompleter)
3453 return;
3454
Douglas Gregor52779fb2010-09-23 23:01:17 +00003455 ResultBuilder Results(*this,
3456 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3457 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003458 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003459
3460 // If we aren't in class scope, we could see the "namespace" keyword.
3461 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003462 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003463
3464 // After "using", we can see anything that would start a
3465 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003466 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003467 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3468 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003469 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003470
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003471 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003472 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003473 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003474}
3475
3476void Sema::CodeCompleteUsingDirective(Scope *S) {
3477 if (!CodeCompleter)
3478 return;
3479
Douglas Gregor86d9a522009-09-21 16:56:56 +00003480 // After "using namespace", we expect to see a namespace name or namespace
3481 // alias.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003482 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3483 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003484 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003485 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003486 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3487 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003488 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003489 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003490 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003491 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003492}
3493
3494void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3495 if (!CodeCompleter)
3496 return;
3497
Douglas Gregor86d9a522009-09-21 16:56:56 +00003498 DeclContext *Ctx = (DeclContext *)S->getEntity();
3499 if (!S->getParent())
3500 Ctx = Context.getTranslationUnitDecl();
3501
Douglas Gregor52779fb2010-09-23 23:01:17 +00003502 bool SuppressedGlobalResults
3503 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3504
3505 ResultBuilder Results(*this,
3506 SuppressedGlobalResults
3507 ? CodeCompletionContext::CCC_Namespace
3508 : CodeCompletionContext::CCC_Other,
3509 &ResultBuilder::IsNamespace);
3510
3511 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003512 // We only want to see those namespaces that have already been defined
3513 // within this scope, because its likely that the user is creating an
3514 // extended namespace declaration. Keep track of the most recent
3515 // definition of each namespace.
3516 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3517 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3518 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3519 NS != NSEnd; ++NS)
3520 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3521
3522 // Add the most recent definition (or extended definition) of each
3523 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003524 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003525 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3526 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3527 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003528 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003529 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003530 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003531 }
3532
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003533 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003534 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003535 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003536}
3537
3538void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3539 if (!CodeCompleter)
3540 return;
3541
Douglas Gregor86d9a522009-09-21 16:56:56 +00003542 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor52779fb2010-09-23 23:01:17 +00003543 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3544 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003545 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003546 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3547 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003548 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003549 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003550 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003551}
3552
Douglas Gregored8d3222009-09-18 20:05:18 +00003553void Sema::CodeCompleteOperatorName(Scope *S) {
3554 if (!CodeCompleter)
3555 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003556
John McCall0a2c5e22010-08-25 06:19:51 +00003557 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003558 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type,
3559 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003560 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003561
Douglas Gregor86d9a522009-09-21 16:56:56 +00003562 // Add the names of overloadable operators.
3563#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3564 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003565 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003566#include "clang/Basic/OperatorKinds.def"
3567
3568 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003569 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003570 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003571 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3572 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003573
3574 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003575 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003576 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003577
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003578 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003579 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003580 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003581}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003582
Douglas Gregor0133f522010-08-28 00:00:50 +00003583void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3584 CXXBaseOrMemberInitializer** Initializers,
3585 unsigned NumInitializers) {
3586 CXXConstructorDecl *Constructor
3587 = static_cast<CXXConstructorDecl *>(ConstructorD);
3588 if (!Constructor)
3589 return;
3590
Douglas Gregor52779fb2010-09-23 23:01:17 +00003591 ResultBuilder Results(*this,
3592 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003593 Results.EnterNewScope();
3594
3595 // Fill in any already-initialized fields or base classes.
3596 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3597 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3598 for (unsigned I = 0; I != NumInitializers; ++I) {
3599 if (Initializers[I]->isBaseInitializer())
3600 InitializedBases.insert(
3601 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3602 else
3603 InitializedFields.insert(cast<FieldDecl>(Initializers[I]->getMember()));
3604 }
3605
3606 // Add completions for base classes.
Douglas Gregor0c431c82010-08-29 19:27:27 +00003607 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003608 CXXRecordDecl *ClassDecl = Constructor->getParent();
3609 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3610 BaseEnd = ClassDecl->bases_end();
3611 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003612 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3613 SawLastInitializer
3614 = NumInitializers > 0 &&
3615 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3616 Context.hasSameUnqualifiedType(Base->getType(),
3617 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003618 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003619 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003620
3621 CodeCompletionString *Pattern = new CodeCompletionString;
3622 Pattern->AddTypedTextChunk(
3623 Base->getType().getAsString(Context.PrintingPolicy));
3624 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3625 Pattern->AddPlaceholderChunk("args");
3626 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003627 Results.AddResult(CodeCompletionResult(Pattern,
3628 SawLastInitializer? CCP_NextInitializer
3629 : CCP_MemberDeclaration));
3630 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003631 }
3632
3633 // Add completions for virtual base classes.
3634 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3635 BaseEnd = ClassDecl->vbases_end();
3636 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003637 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3638 SawLastInitializer
3639 = NumInitializers > 0 &&
3640 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3641 Context.hasSameUnqualifiedType(Base->getType(),
3642 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003643 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003644 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003645
3646 CodeCompletionString *Pattern = new CodeCompletionString;
3647 Pattern->AddTypedTextChunk(
3648 Base->getType().getAsString(Context.PrintingPolicy));
3649 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3650 Pattern->AddPlaceholderChunk("args");
3651 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003652 Results.AddResult(CodeCompletionResult(Pattern,
3653 SawLastInitializer? CCP_NextInitializer
3654 : CCP_MemberDeclaration));
3655 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003656 }
3657
3658 // Add completions for members.
3659 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3660 FieldEnd = ClassDecl->field_end();
3661 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003662 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3663 SawLastInitializer
3664 = NumInitializers > 0 &&
3665 Initializers[NumInitializers - 1]->isMemberInitializer() &&
3666 Initializers[NumInitializers - 1]->getMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003667 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003668 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003669
3670 if (!Field->getDeclName())
3671 continue;
3672
3673 CodeCompletionString *Pattern = new CodeCompletionString;
3674 Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3675 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3676 Pattern->AddPlaceholderChunk("args");
3677 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0c431c82010-08-29 19:27:27 +00003678 Results.AddResult(CodeCompletionResult(Pattern,
3679 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003680 : CCP_MemberDeclaration,
3681 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003682 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003683 }
3684 Results.ExitScope();
3685
Douglas Gregor52779fb2010-09-23 23:01:17 +00003686 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003687 Results.data(), Results.size());
3688}
3689
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003690// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3691// true or false.
3692#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003693static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003694 ResultBuilder &Results,
3695 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003696 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003697 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003698 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003699
3700 CodeCompletionString *Pattern = 0;
3701 if (LangOpts.ObjC2) {
3702 // @dynamic
3703 Pattern = new CodeCompletionString;
3704 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3705 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3706 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003707 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003708
3709 // @synthesize
3710 Pattern = new CodeCompletionString;
3711 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3712 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3713 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003714 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003715 }
3716}
3717
Douglas Gregorbca403c2010-01-13 23:51:12 +00003718static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003719 ResultBuilder &Results,
3720 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003721 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003722
3723 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003724 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003725
3726 if (LangOpts.ObjC2) {
3727 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003728 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003729
3730 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003731 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003732
3733 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003734 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003735 }
3736}
3737
Douglas Gregorbca403c2010-01-13 23:51:12 +00003738static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003739 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003740 CodeCompletionString *Pattern = 0;
3741
3742 // @class name ;
3743 Pattern = new CodeCompletionString;
3744 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3745 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003746 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003747 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003748
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003749 if (Results.includeCodePatterns()) {
3750 // @interface name
3751 // FIXME: Could introduce the whole pattern, including superclasses and
3752 // such.
3753 Pattern = new CodeCompletionString;
3754 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3755 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3756 Pattern->AddPlaceholderChunk("class");
3757 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003758
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003759 // @protocol name
3760 Pattern = new CodeCompletionString;
3761 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3762 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3763 Pattern->AddPlaceholderChunk("protocol");
3764 Results.AddResult(Result(Pattern));
3765
3766 // @implementation name
3767 Pattern = new CodeCompletionString;
3768 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3769 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3770 Pattern->AddPlaceholderChunk("class");
3771 Results.AddResult(Result(Pattern));
3772 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003773
3774 // @compatibility_alias name
3775 Pattern = new CodeCompletionString;
3776 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3777 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3778 Pattern->AddPlaceholderChunk("alias");
3779 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3780 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003781 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003782}
3783
John McCalld226f652010-08-21 09:40:31 +00003784void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003785 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003786 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003787 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003788 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003789 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003790 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003791 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003792 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003793 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003794 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003795 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003796 HandleCodeCompleteResults(this, CodeCompleter,
3797 CodeCompletionContext::CCC_Other,
3798 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003799}
3800
Douglas Gregorbca403c2010-01-13 23:51:12 +00003801static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003802 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003803 CodeCompletionString *Pattern = 0;
3804
3805 // @encode ( type-name )
3806 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003807 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003808 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3809 Pattern->AddPlaceholderChunk("type-name");
3810 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003811 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003812
3813 // @protocol ( protocol-name )
3814 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003815 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003816 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3817 Pattern->AddPlaceholderChunk("protocol-name");
3818 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003819 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003820
3821 // @selector ( selector )
3822 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003823 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003824 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3825 Pattern->AddPlaceholderChunk("selector");
3826 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003827 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003828}
3829
Douglas Gregorbca403c2010-01-13 23:51:12 +00003830static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003831 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003832 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003833
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003834 if (Results.includeCodePatterns()) {
3835 // @try { statements } @catch ( declaration ) { statements } @finally
3836 // { statements }
3837 Pattern = new CodeCompletionString;
3838 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3839 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3840 Pattern->AddPlaceholderChunk("statements");
3841 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3842 Pattern->AddTextChunk("@catch");
3843 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3844 Pattern->AddPlaceholderChunk("parameter");
3845 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3846 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3847 Pattern->AddPlaceholderChunk("statements");
3848 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3849 Pattern->AddTextChunk("@finally");
3850 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3851 Pattern->AddPlaceholderChunk("statements");
3852 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3853 Results.AddResult(Result(Pattern));
3854 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003855
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003856 // @throw
3857 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003858 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003859 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003860 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003861 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003862
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003863 if (Results.includeCodePatterns()) {
3864 // @synchronized ( expression ) { statements }
3865 Pattern = new CodeCompletionString;
3866 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3867 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3868 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3869 Pattern->AddPlaceholderChunk("expression");
3870 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3871 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3872 Pattern->AddPlaceholderChunk("statements");
3873 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3874 Results.AddResult(Result(Pattern));
3875 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003876}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003877
Douglas Gregorbca403c2010-01-13 23:51:12 +00003878static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003879 ResultBuilder &Results,
3880 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003881 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003882 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3883 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3884 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003885 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003886 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003887}
3888
3889void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003890 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003891 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003892 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003893 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003894 HandleCodeCompleteResults(this, CodeCompleter,
3895 CodeCompletionContext::CCC_Other,
3896 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003897}
3898
3899void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003900 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003901 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003902 AddObjCStatementResults(Results, false);
3903 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003904 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003905 HandleCodeCompleteResults(this, CodeCompleter,
3906 CodeCompletionContext::CCC_Other,
3907 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003908}
3909
3910void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00003911 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003912 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003913 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003914 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003915 HandleCodeCompleteResults(this, CodeCompleter,
3916 CodeCompletionContext::CCC_Other,
3917 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003918}
3919
Douglas Gregor988358f2009-11-19 00:14:45 +00003920/// \brief Determine whether the addition of the given flag to an Objective-C
3921/// property's attributes will cause a conflict.
3922static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3923 // Check if we've already added this flag.
3924 if (Attributes & NewFlag)
3925 return true;
3926
3927 Attributes |= NewFlag;
3928
3929 // Check for collisions with "readonly".
3930 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3931 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3932 ObjCDeclSpec::DQ_PR_assign |
3933 ObjCDeclSpec::DQ_PR_copy |
3934 ObjCDeclSpec::DQ_PR_retain)))
3935 return true;
3936
3937 // Check for more than one of { assign, copy, retain }.
3938 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3939 ObjCDeclSpec::DQ_PR_copy |
3940 ObjCDeclSpec::DQ_PR_retain);
3941 if (AssignCopyRetMask &&
3942 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3943 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3944 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3945 return true;
3946
3947 return false;
3948}
3949
Douglas Gregora93b1082009-11-18 23:08:07 +00003950void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003951 if (!CodeCompleter)
3952 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003953
Steve Naroffece8e712009-10-08 21:55:05 +00003954 unsigned Attributes = ODS.getPropertyAttributes();
3955
John McCall0a2c5e22010-08-25 06:19:51 +00003956 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00003957 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00003958 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003959 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003960 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003961 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003962 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003963 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003964 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003965 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003966 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003967 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003968 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003969 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003970 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003971 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003972 CodeCompletionString *Setter = new CodeCompletionString;
3973 Setter->AddTypedTextChunk("setter");
3974 Setter->AddTextChunk(" = ");
3975 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003976 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003977 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003978 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003979 CodeCompletionString *Getter = new CodeCompletionString;
3980 Getter->AddTypedTextChunk("getter");
3981 Getter->AddTextChunk(" = ");
3982 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003983 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003984 }
Steve Naroffece8e712009-10-08 21:55:05 +00003985 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003986 HandleCodeCompleteResults(this, CodeCompleter,
3987 CodeCompletionContext::CCC_Other,
3988 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003989}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003990
Douglas Gregor4ad96852009-11-19 07:41:15 +00003991/// \brief Descripts the kind of Objective-C method that we want to find
3992/// via code completion.
3993enum ObjCMethodKind {
3994 MK_Any, //< Any kind of method, provided it means other specified criteria.
3995 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3996 MK_OneArgSelector //< One-argument selector.
3997};
3998
Douglas Gregor458433d2010-08-26 15:07:07 +00003999static bool isAcceptableObjCSelector(Selector Sel,
4000 ObjCMethodKind WantKind,
4001 IdentifierInfo **SelIdents,
4002 unsigned NumSelIdents) {
4003 if (NumSelIdents > Sel.getNumArgs())
4004 return false;
4005
4006 switch (WantKind) {
4007 case MK_Any: break;
4008 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4009 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4010 }
4011
4012 for (unsigned I = 0; I != NumSelIdents; ++I)
4013 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4014 return false;
4015
4016 return true;
4017}
4018
Douglas Gregor4ad96852009-11-19 07:41:15 +00004019static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4020 ObjCMethodKind WantKind,
4021 IdentifierInfo **SelIdents,
4022 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004023 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4024 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004025}
Douglas Gregord36adf52010-09-16 16:06:31 +00004026
4027namespace {
4028 /// \brief A set of selectors, which is used to avoid introducing multiple
4029 /// completions with the same selector into the result set.
4030 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4031}
4032
Douglas Gregor36ecb042009-11-17 23:22:23 +00004033/// \brief Add all of the Objective-C methods in the given Objective-C
4034/// container to the set of results.
4035///
4036/// The container will be a class, protocol, category, or implementation of
4037/// any of the above. This mether will recurse to include methods from
4038/// the superclasses of classes along with their categories, protocols, and
4039/// implementations.
4040///
4041/// \param Container the container in which we'll look to find methods.
4042///
4043/// \param WantInstance whether to add instance methods (only); if false, this
4044/// routine will add factory methods (only).
4045///
4046/// \param CurContext the context in which we're performing the lookup that
4047/// finds methods.
4048///
4049/// \param Results the structure into which we'll add results.
4050static void AddObjCMethods(ObjCContainerDecl *Container,
4051 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004052 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004053 IdentifierInfo **SelIdents,
4054 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004055 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004056 VisitedSelectorSet &Selectors,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004057 ResultBuilder &Results,
4058 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004059 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004060 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4061 MEnd = Container->meth_end();
4062 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004063 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4064 // Check whether the selector identifiers we've been given are a
4065 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004066 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00004067 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004068
Douglas Gregord36adf52010-09-16 16:06:31 +00004069 if (!Selectors.insert((*M)->getSelector()))
4070 continue;
4071
Douglas Gregord3c68542009-11-19 01:08:35 +00004072 Result R = Result(*M, 0);
4073 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004074 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004075 if (!InOriginalClass)
4076 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004077 Results.MaybeAddResult(R, CurContext);
4078 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004079 }
4080
Douglas Gregore396c7b2010-09-16 15:34:59 +00004081 // Visit the protocols of protocols.
4082 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4083 const ObjCList<ObjCProtocolDecl> &Protocols
4084 = Protocol->getReferencedProtocols();
4085 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4086 E = Protocols.end();
4087 I != E; ++I)
4088 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004089 CurContext, Selectors, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004090 }
4091
Douglas Gregor36ecb042009-11-17 23:22:23 +00004092 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4093 if (!IFace)
4094 return;
4095
4096 // Add methods in protocols.
4097 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4098 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4099 E = Protocols.end();
4100 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004101 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004102 CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004103
4104 // Add methods in categories.
4105 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4106 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004107 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004108 NumSelIdents, CurContext, Selectors, Results,
4109 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004110
4111 // Add a categories protocol methods.
4112 const ObjCList<ObjCProtocolDecl> &Protocols
4113 = CatDecl->getReferencedProtocols();
4114 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4115 E = Protocols.end();
4116 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004117 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004118 NumSelIdents, CurContext, Selectors, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004119
4120 // Add methods in category implementations.
4121 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004122 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004123 NumSelIdents, CurContext, Selectors, Results,
4124 InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004125 }
4126
4127 // Add methods in superclass.
4128 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004129 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregord36adf52010-09-16 16:06:31 +00004130 SelIdents, NumSelIdents, CurContext, Selectors, Results,
4131 false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004132
4133 // Add methods in our implementation, if any.
4134 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004135 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004136 NumSelIdents, CurContext, Selectors, Results,
4137 InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004138}
4139
4140
John McCalld226f652010-08-21 09:40:31 +00004141void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
4142 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004143 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00004144 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004145
4146 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004147 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004148 if (!Class) {
4149 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004150 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004151 Class = Category->getClassInterface();
4152
4153 if (!Class)
4154 return;
4155 }
4156
4157 // Find all of the potential getters.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004158 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004159 Results.EnterNewScope();
4160
4161 // FIXME: We need to do this because Objective-C methods don't get
4162 // pushed into DeclContexts early enough. Argh!
4163 for (unsigned I = 0; I != NumMethods; ++I) {
4164 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00004165 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004166 if (Method->isInstanceMethod() &&
4167 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
4168 Result R = Result(Method, 0);
4169 R.AllParametersAreInformative = true;
4170 Results.MaybeAddResult(R, CurContext);
4171 }
4172 }
4173
Douglas Gregord36adf52010-09-16 16:06:31 +00004174 VisitedSelectorSet Selectors;
4175 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
4176 Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004177 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004178 HandleCodeCompleteResults(this, CodeCompleter,
4179 CodeCompletionContext::CCC_Other,
4180 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004181}
4182
John McCalld226f652010-08-21 09:40:31 +00004183void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
4184 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004185 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00004186 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004187
4188 // Try to find the interface where setters might live.
4189 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004190 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004191 if (!Class) {
4192 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004193 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004194 Class = Category->getClassInterface();
4195
4196 if (!Class)
4197 return;
4198 }
4199
4200 // Find all of the potential getters.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004201 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004202 Results.EnterNewScope();
4203
4204 // FIXME: We need to do this because Objective-C methods don't get
4205 // pushed into DeclContexts early enough. Argh!
4206 for (unsigned I = 0; I != NumMethods; ++I) {
4207 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00004208 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004209 if (Method->isInstanceMethod() &&
4210 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
4211 Result R = Result(Method, 0);
4212 R.AllParametersAreInformative = true;
4213 Results.MaybeAddResult(R, CurContext);
4214 }
4215 }
4216
Douglas Gregord36adf52010-09-16 16:06:31 +00004217 VisitedSelectorSet Selectors;
4218 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4219 Selectors, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004220
4221 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004222 HandleCodeCompleteResults(this, CodeCompleter,
4223 CodeCompletionContext::CCC_Other,
4224 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004225}
4226
Douglas Gregord32b0222010-08-24 01:06:58 +00004227void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00004228 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00004229 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004230 Results.EnterNewScope();
4231
4232 // Add context-sensitive, Objective-C parameter-passing keywords.
4233 bool AddedInOut = false;
4234 if ((DS.getObjCDeclQualifier() &
4235 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4236 Results.AddResult("in");
4237 Results.AddResult("inout");
4238 AddedInOut = true;
4239 }
4240 if ((DS.getObjCDeclQualifier() &
4241 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4242 Results.AddResult("out");
4243 if (!AddedInOut)
4244 Results.AddResult("inout");
4245 }
4246 if ((DS.getObjCDeclQualifier() &
4247 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4248 ObjCDeclSpec::DQ_Oneway)) == 0) {
4249 Results.AddResult("bycopy");
4250 Results.AddResult("byref");
4251 Results.AddResult("oneway");
4252 }
4253
4254 // Add various builtin type names and specifiers.
4255 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4256 Results.ExitScope();
4257
4258 // Add the various type names
4259 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4260 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4261 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4262 CodeCompleter->includeGlobals());
4263
4264 if (CodeCompleter->includeMacros())
4265 AddMacroResults(PP, Results);
4266
4267 HandleCodeCompleteResults(this, CodeCompleter,
4268 CodeCompletionContext::CCC_Type,
4269 Results.data(), Results.size());
4270}
4271
Douglas Gregor22f56992010-04-06 19:22:33 +00004272/// \brief When we have an expression with type "id", we may assume
4273/// that it has some more-specific class type based on knowledge of
4274/// common uses of Objective-C. This routine returns that class type,
4275/// or NULL if no better result could be determined.
4276static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004277 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004278 if (!Msg)
4279 return 0;
4280
4281 Selector Sel = Msg->getSelector();
4282 if (Sel.isNull())
4283 return 0;
4284
4285 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4286 if (!Id)
4287 return 0;
4288
4289 ObjCMethodDecl *Method = Msg->getMethodDecl();
4290 if (!Method)
4291 return 0;
4292
4293 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004294 ObjCInterfaceDecl *IFace = 0;
4295 switch (Msg->getReceiverKind()) {
4296 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004297 if (const ObjCObjectType *ObjType
4298 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4299 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004300 break;
4301
4302 case ObjCMessageExpr::Instance: {
4303 QualType T = Msg->getInstanceReceiver()->getType();
4304 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4305 IFace = Ptr->getInterfaceDecl();
4306 break;
4307 }
4308
4309 case ObjCMessageExpr::SuperInstance:
4310 case ObjCMessageExpr::SuperClass:
4311 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004312 }
4313
4314 if (!IFace)
4315 return 0;
4316
4317 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4318 if (Method->isInstanceMethod())
4319 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4320 .Case("retain", IFace)
4321 .Case("autorelease", IFace)
4322 .Case("copy", IFace)
4323 .Case("copyWithZone", IFace)
4324 .Case("mutableCopy", IFace)
4325 .Case("mutableCopyWithZone", IFace)
4326 .Case("awakeFromCoder", IFace)
4327 .Case("replacementObjectFromCoder", IFace)
4328 .Case("class", IFace)
4329 .Case("classForCoder", IFace)
4330 .Case("superclass", Super)
4331 .Default(0);
4332
4333 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4334 .Case("new", IFace)
4335 .Case("alloc", IFace)
4336 .Case("allocWithZone", IFace)
4337 .Case("class", IFace)
4338 .Case("superclass", Super)
4339 .Default(0);
4340}
4341
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004342// Add a special completion for a message send to "super", which fills in the
4343// most likely case of forwarding all of our arguments to the superclass
4344// function.
4345///
4346/// \param S The semantic analysis object.
4347///
4348/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4349/// the "super" keyword. Otherwise, we just need to provide the arguments.
4350///
4351/// \param SelIdents The identifiers in the selector that have already been
4352/// provided as arguments for a send to "super".
4353///
4354/// \param NumSelIdents The number of identifiers in \p SelIdents.
4355///
4356/// \param Results The set of results to augment.
4357///
4358/// \returns the Objective-C method declaration that would be invoked by
4359/// this "super" completion. If NULL, no completion was added.
4360static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4361 IdentifierInfo **SelIdents,
4362 unsigned NumSelIdents,
4363 ResultBuilder &Results) {
4364 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4365 if (!CurMethod)
4366 return 0;
4367
4368 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4369 if (!Class)
4370 return 0;
4371
4372 // Try to find a superclass method with the same selector.
4373 ObjCMethodDecl *SuperMethod = 0;
4374 while ((Class = Class->getSuperClass()) && !SuperMethod)
4375 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4376 CurMethod->isInstanceMethod());
4377
4378 if (!SuperMethod)
4379 return 0;
4380
4381 // Check whether the superclass method has the same signature.
4382 if (CurMethod->param_size() != SuperMethod->param_size() ||
4383 CurMethod->isVariadic() != SuperMethod->isVariadic())
4384 return 0;
4385
4386 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4387 CurPEnd = CurMethod->param_end(),
4388 SuperP = SuperMethod->param_begin();
4389 CurP != CurPEnd; ++CurP, ++SuperP) {
4390 // Make sure the parameter types are compatible.
4391 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4392 (*SuperP)->getType()))
4393 return 0;
4394
4395 // Make sure we have a parameter name to forward!
4396 if (!(*CurP)->getIdentifier())
4397 return 0;
4398 }
4399
4400 // We have a superclass method. Now, form the send-to-super completion.
4401 CodeCompletionString *Pattern = new CodeCompletionString;
4402
4403 // Give this completion a return type.
4404 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4405
4406 // If we need the "super" keyword, add it (plus some spacing).
4407 if (NeedSuperKeyword) {
4408 Pattern->AddTypedTextChunk("super");
4409 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4410 }
4411
4412 Selector Sel = CurMethod->getSelector();
4413 if (Sel.isUnarySelector()) {
4414 if (NeedSuperKeyword)
4415 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4416 else
4417 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4418 } else {
4419 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4420 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4421 if (I > NumSelIdents)
4422 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4423
4424 if (I < NumSelIdents)
4425 Pattern->AddInformativeChunk(
4426 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4427 else if (NeedSuperKeyword || I > NumSelIdents) {
4428 Pattern->AddTextChunk(
4429 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4430 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4431 } else {
4432 Pattern->AddTypedTextChunk(
4433 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4434 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4435 }
4436 }
4437 }
4438
4439 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4440 SuperMethod->isInstanceMethod()
4441 ? CXCursor_ObjCInstanceMethodDecl
4442 : CXCursor_ObjCClassMethodDecl));
4443 return SuperMethod;
4444}
4445
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004446void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004447 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00004448 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCMessageReceiver,
4449 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004450
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004451 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4452 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004453 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4454 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004455
4456 // If we are in an Objective-C method inside a class that has a superclass,
4457 // add "super" as an option.
4458 if (ObjCMethodDecl *Method = getCurMethodDecl())
4459 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004460 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004461 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004462
4463 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4464 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004465
4466 Results.ExitScope();
4467
4468 if (CodeCompleter->includeMacros())
4469 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004470 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004471 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004472
4473}
4474
Douglas Gregor2725ca82010-04-21 19:57:20 +00004475void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4476 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004477 unsigned NumSelIdents,
4478 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004479 ObjCInterfaceDecl *CDecl = 0;
4480 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4481 // Figure out which interface we're in.
4482 CDecl = CurMethod->getClassInterface();
4483 if (!CDecl)
4484 return;
4485
4486 // Find the superclass of this class.
4487 CDecl = CDecl->getSuperClass();
4488 if (!CDecl)
4489 return;
4490
4491 if (CurMethod->isInstanceMethod()) {
4492 // We are inside an instance method, which means that the message
4493 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004494 // current object.
4495 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004496 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004497 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004498 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004499 }
4500
4501 // Fall through to send to the superclass in CDecl.
4502 } else {
4503 // "super" may be the name of a type or variable. Figure out which
4504 // it is.
4505 IdentifierInfo *Super = &Context.Idents.get("super");
4506 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4507 LookupOrdinaryName);
4508 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4509 // "super" names an interface. Use it.
4510 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004511 if (const ObjCObjectType *Iface
4512 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4513 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004514 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4515 // "super" names an unresolved type; we can't be more specific.
4516 } else {
4517 // Assume that "super" names some kind of value and parse that way.
4518 CXXScopeSpec SS;
4519 UnqualifiedId id;
4520 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004521 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004522 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004523 SelIdents, NumSelIdents,
4524 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004525 }
4526
4527 // Fall through
4528 }
4529
John McCallb3d87482010-08-24 05:47:05 +00004530 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004531 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004532 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004533 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004534 NumSelIdents, AtArgumentExpression,
4535 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004536}
4537
Douglas Gregorb9d77572010-09-21 00:03:25 +00004538/// \brief Given a set of code-completion results for the argument of a message
4539/// send, determine the preferred type (if any) for that argument expression.
4540static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4541 unsigned NumSelIdents) {
4542 typedef CodeCompletionResult Result;
4543 ASTContext &Context = Results.getSema().Context;
4544
4545 QualType PreferredType;
4546 unsigned BestPriority = CCP_Unlikely * 2;
4547 Result *ResultsData = Results.data();
4548 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4549 Result &R = ResultsData[I];
4550 if (R.Kind == Result::RK_Declaration &&
4551 isa<ObjCMethodDecl>(R.Declaration)) {
4552 if (R.Priority <= BestPriority) {
4553 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4554 if (NumSelIdents <= Method->param_size()) {
4555 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4556 ->getType();
4557 if (R.Priority < BestPriority || PreferredType.isNull()) {
4558 BestPriority = R.Priority;
4559 PreferredType = MyPreferredType;
4560 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4561 MyPreferredType)) {
4562 PreferredType = QualType();
4563 }
4564 }
4565 }
4566 }
4567 }
4568
4569 return PreferredType;
4570}
4571
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004572static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4573 ParsedType Receiver,
4574 IdentifierInfo **SelIdents,
4575 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004576 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004577 bool IsSuper,
4578 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004579 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004580 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004581
Douglas Gregor24a069f2009-11-17 17:59:40 +00004582 // If the given name refers to an interface type, retrieve the
4583 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004584 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004585 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004586 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004587 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4588 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004589 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004590
Douglas Gregor36ecb042009-11-17 23:22:23 +00004591 // Add all of the factory methods in this Objective-C class, its protocols,
4592 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004593 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004594
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004595 // If this is a send-to-super, try to add the special "super" send
4596 // completion.
4597 if (IsSuper) {
4598 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004599 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4600 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004601 Results.Ignore(SuperMethod);
4602 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004603
Douglas Gregor265f7492010-08-27 15:29:55 +00004604 // If we're inside an Objective-C method definition, prefer its selector to
4605 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004606 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004607 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004608
Douglas Gregord36adf52010-09-16 16:06:31 +00004609 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004610 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004611 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004612 SemaRef.CurContext, Selectors, Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004613 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004614 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004615
Douglas Gregor719770d2010-04-06 17:30:22 +00004616 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004617 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004618 if (SemaRef.ExternalSource) {
4619 for (uint32_t I = 0,
4620 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004621 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004622 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4623 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004624 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004625
4626 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004627 }
4628 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004629
4630 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4631 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004632 M != MEnd; ++M) {
4633 for (ObjCMethodList *MethList = &M->second.second;
4634 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004635 MethList = MethList->Next) {
4636 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4637 NumSelIdents))
4638 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004639
Douglas Gregor13438f92010-04-06 16:40:00 +00004640 Result R(MethList->Method, 0);
4641 R.StartParameter = NumSelIdents;
4642 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004643 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004644 }
4645 }
4646 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004647
4648 Results.ExitScope();
4649}
Douglas Gregor13438f92010-04-06 16:40:00 +00004650
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004651void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4652 IdentifierInfo **SelIdents,
4653 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004654 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004655 bool IsSuper) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004656 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004657 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4658 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004659
4660 // If we're actually at the argument expression (rather than prior to the
4661 // selector), we're actually performing code completion for an expression.
4662 // Determine whether we have a single, best method. If so, we can
4663 // code-complete the expression using the corresponding parameter type as
4664 // our preferred type, improving completion results.
4665 if (AtArgumentExpression) {
4666 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4667 NumSelIdents);
4668 if (PreferredType.isNull())
4669 CodeCompleteOrdinaryName(S, PCC_Expression);
4670 else
4671 CodeCompleteExpression(S, PreferredType);
4672 return;
4673 }
4674
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004675 HandleCodeCompleteResults(this, CodeCompleter,
4676 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004677 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004678}
4679
Douglas Gregord3c68542009-11-19 01:08:35 +00004680void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4681 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004682 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004683 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004684 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004685 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004686
4687 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004688
Douglas Gregor36ecb042009-11-17 23:22:23 +00004689 // If necessary, apply function/array conversion to the receiver.
4690 // C99 6.7.5.3p[7,8].
Douglas Gregor78edf512010-09-15 16:23:04 +00004691 if (RecExpr)
4692 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004693 QualType ReceiverType = RecExpr? RecExpr->getType()
4694 : Super? Context.getObjCObjectPointerType(
4695 Context.getObjCInterfaceType(Super))
4696 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004697
Douglas Gregor36ecb042009-11-17 23:22:23 +00004698 // Build the set of methods we can see.
Douglas Gregor52779fb2010-09-23 23:01:17 +00004699 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004700 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004701
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004702 // If this is a send-to-super, try to add the special "super" send
4703 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004704 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004705 if (ObjCMethodDecl *SuperMethod
4706 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4707 Results))
4708 Results.Ignore(SuperMethod);
4709 }
4710
Douglas Gregor265f7492010-08-27 15:29:55 +00004711 // If we're inside an Objective-C method definition, prefer its selector to
4712 // others.
4713 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4714 Results.setPreferredSelector(CurMethod->getSelector());
4715
Douglas Gregor22f56992010-04-06 19:22:33 +00004716 // If we're messaging an expression with type "id" or "Class", check
4717 // whether we know something special about the receiver that allows
4718 // us to assume a more-specific receiver type.
4719 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4720 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4721 ReceiverType = Context.getObjCObjectPointerType(
4722 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00004723
Douglas Gregord36adf52010-09-16 16:06:31 +00004724 // Keep track of the selectors we've already added.
4725 VisitedSelectorSet Selectors;
4726
Douglas Gregorf74a4192009-11-18 00:06:18 +00004727 // Handle messages to Class. This really isn't a message to an instance
4728 // method, so we treat it the same way we would treat a message send to a
4729 // class method.
4730 if (ReceiverType->isObjCClassType() ||
4731 ReceiverType->isObjCQualifiedClassType()) {
4732 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4733 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004734 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004735 CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004736 }
4737 }
4738 // Handle messages to a qualified ID ("id<foo>").
4739 else if (const ObjCObjectPointerType *QualID
4740 = ReceiverType->getAsObjCQualifiedIdType()) {
4741 // Search protocols for instance methods.
4742 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4743 E = QualID->qual_end();
4744 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004745 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004746 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004747 }
4748 // Handle messages to a pointer to interface type.
4749 else if (const ObjCObjectPointerType *IFacePtr
4750 = ReceiverType->getAsObjCInterfacePointerType()) {
4751 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004752 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregord36adf52010-09-16 16:06:31 +00004753 NumSelIdents, CurContext, Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004754
4755 // Search protocols for instance methods.
4756 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4757 E = IFacePtr->qual_end();
4758 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004759 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004760 Selectors, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004761 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004762 // Handle messages to "id".
4763 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004764 // We're messaging "id", so provide all instance methods we know
4765 // about as code-completion results.
4766
4767 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004768 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004769 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004770 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4771 I != N; ++I) {
4772 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004773 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004774 continue;
4775
Sebastian Redldb9d2142010-08-02 23:18:59 +00004776 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004777 }
4778 }
4779
Sebastian Redldb9d2142010-08-02 23:18:59 +00004780 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4781 MEnd = MethodPool.end();
4782 M != MEnd; ++M) {
4783 for (ObjCMethodList *MethList = &M->second.first;
4784 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004785 MethList = MethList->Next) {
4786 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4787 NumSelIdents))
4788 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00004789
4790 if (!Selectors.insert(MethList->Method->getSelector()))
4791 continue;
4792
Douglas Gregor13438f92010-04-06 16:40:00 +00004793 Result R(MethList->Method, 0);
4794 R.StartParameter = NumSelIdents;
4795 R.AllParametersAreInformative = false;
4796 Results.MaybeAddResult(R, CurContext);
4797 }
4798 }
4799 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00004800 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00004801
4802
4803 // If we're actually at the argument expression (rather than prior to the
4804 // selector), we're actually performing code completion for an expression.
4805 // Determine whether we have a single, best method. If so, we can
4806 // code-complete the expression using the corresponding parameter type as
4807 // our preferred type, improving completion results.
4808 if (AtArgumentExpression) {
4809 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4810 NumSelIdents);
4811 if (PreferredType.isNull())
4812 CodeCompleteOrdinaryName(S, PCC_Expression);
4813 else
4814 CodeCompleteExpression(S, PreferredType);
4815 return;
4816 }
4817
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004818 HandleCodeCompleteResults(this, CodeCompleter,
4819 CodeCompletionContext::CCC_Other,
4820 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004821}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004822
Douglas Gregorfb629412010-08-23 21:17:50 +00004823void Sema::CodeCompleteObjCForCollection(Scope *S,
4824 DeclGroupPtrTy IterationVar) {
4825 CodeCompleteExpressionData Data;
4826 Data.ObjCCollection = true;
4827
4828 if (IterationVar.getAsOpaquePtr()) {
4829 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4830 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4831 if (*I)
4832 Data.IgnoreDecls.push_back(*I);
4833 }
4834 }
4835
4836 CodeCompleteExpression(S, Data);
4837}
4838
Douglas Gregor458433d2010-08-26 15:07:07 +00004839void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4840 unsigned NumSelIdents) {
4841 // If we have an external source, load the entire class method
4842 // pool from the AST file.
4843 if (ExternalSource) {
4844 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4845 I != N; ++I) {
4846 Selector Sel = ExternalSource->GetExternalSelector(I);
4847 if (Sel.isNull() || MethodPool.count(Sel))
4848 continue;
4849
4850 ReadMethodPool(Sel);
4851 }
4852 }
4853
Douglas Gregor52779fb2010-09-23 23:01:17 +00004854 ResultBuilder Results(*this, CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00004855 Results.EnterNewScope();
4856 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4857 MEnd = MethodPool.end();
4858 M != MEnd; ++M) {
4859
4860 Selector Sel = M->first;
4861 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4862 continue;
4863
4864 CodeCompletionString *Pattern = new CodeCompletionString;
4865 if (Sel.isUnarySelector()) {
4866 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4867 Results.AddResult(Pattern);
4868 continue;
4869 }
4870
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004871 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004872 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004873 if (I == NumSelIdents) {
4874 if (!Accumulator.empty()) {
4875 Pattern->AddInformativeChunk(Accumulator);
4876 Accumulator.clear();
4877 }
4878 }
4879
4880 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4881 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004882 }
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004883 Pattern->AddTypedTextChunk(Accumulator);
Douglas Gregor458433d2010-08-26 15:07:07 +00004884 Results.AddResult(Pattern);
4885 }
4886 Results.ExitScope();
4887
4888 HandleCodeCompleteResults(this, CodeCompleter,
4889 CodeCompletionContext::CCC_SelectorName,
4890 Results.data(), Results.size());
4891}
4892
Douglas Gregor55385fe2009-11-18 04:19:12 +00004893/// \brief Add all of the protocol declarations that we find in the given
4894/// (translation unit) context.
4895static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004896 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004897 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004898 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004899
4900 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4901 DEnd = Ctx->decls_end();
4902 D != DEnd; ++D) {
4903 // Record any protocols we find.
4904 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004905 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004906 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004907
4908 // Record any forward-declared protocols we find.
4909 if (ObjCForwardProtocolDecl *Forward
4910 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4911 for (ObjCForwardProtocolDecl::protocol_iterator
4912 P = Forward->protocol_begin(),
4913 PEnd = Forward->protocol_end();
4914 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004915 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004916 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004917 }
4918 }
4919}
4920
4921void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4922 unsigned NumProtocols) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004923 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004924 Results.EnterNewScope();
4925
4926 // Tell the result set to ignore all of the protocols we have
4927 // already seen.
4928 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004929 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4930 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004931 Results.Ignore(Protocol);
4932
4933 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004934 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4935 Results);
4936
4937 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004938 HandleCodeCompleteResults(this, CodeCompleter,
4939 CodeCompletionContext::CCC_ObjCProtocolName,
4940 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004941}
4942
4943void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004944 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00004945 Results.EnterNewScope();
4946
4947 // Add all protocols.
4948 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4949 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004950
4951 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004952 HandleCodeCompleteResults(this, CodeCompleter,
4953 CodeCompletionContext::CCC_ObjCProtocolName,
4954 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004955}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004956
4957/// \brief Add all of the Objective-C interface declarations that we find in
4958/// the given (translation unit) context.
4959static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4960 bool OnlyForwardDeclarations,
4961 bool OnlyUnimplemented,
4962 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004963 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004964
4965 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4966 DEnd = Ctx->decls_end();
4967 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004968 // Record any interfaces we find.
4969 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4970 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4971 (!OnlyUnimplemented || !Class->getImplementation()))
4972 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004973
4974 // Record any forward-declared interfaces we find.
4975 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4976 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004977 C != CEnd; ++C)
4978 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4979 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4980 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004981 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004982 }
4983 }
4984}
4985
4986void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00004987 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004988 Results.EnterNewScope();
4989
4990 // Add all classes.
4991 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4992 false, Results);
4993
4994 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00004995 // FIXME: Add a special context for this, use cached global completion
4996 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004997 HandleCodeCompleteResults(this, CodeCompleter,
4998 CodeCompletionContext::CCC_Other,
4999 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005000}
5001
Douglas Gregorc83c6872010-04-15 22:33:43 +00005002void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5003 SourceLocation ClassNameLoc) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005004 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005005 Results.EnterNewScope();
5006
5007 // Make sure that we ignore the class we're currently defining.
5008 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005009 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005010 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005011 Results.Ignore(CurClass);
5012
5013 // Add all classes.
5014 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5015 false, Results);
5016
5017 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005018 // FIXME: Add a special context for this, use cached global completion
5019 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005020 HandleCodeCompleteResults(this, CodeCompleter,
5021 CodeCompletionContext::CCC_Other,
5022 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005023}
5024
5025void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005026 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005027 Results.EnterNewScope();
5028
5029 // Add all unimplemented classes.
5030 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5031 true, Results);
5032
5033 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005034 // FIXME: Add a special context for this, use cached global completion
5035 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005036 HandleCodeCompleteResults(this, CodeCompleter,
5037 CodeCompletionContext::CCC_Other,
5038 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005039}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005040
5041void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005042 IdentifierInfo *ClassName,
5043 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005044 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005045
Douglas Gregor52779fb2010-09-23 23:01:17 +00005046 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005047
5048 // Ignore any categories we find that have already been implemented by this
5049 // interface.
5050 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5051 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005052 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005053 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5054 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5055 Category = Category->getNextClassCategory())
5056 CategoryNames.insert(Category->getIdentifier());
5057
5058 // Add all of the categories we know about.
5059 Results.EnterNewScope();
5060 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5061 for (DeclContext::decl_iterator D = TU->decls_begin(),
5062 DEnd = TU->decls_end();
5063 D != DEnd; ++D)
5064 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5065 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005066 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005067 Results.ExitScope();
5068
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005069 HandleCodeCompleteResults(this, CodeCompleter,
5070 CodeCompletionContext::CCC_Other,
5071 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005072}
5073
5074void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005075 IdentifierInfo *ClassName,
5076 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005077 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005078
5079 // Find the corresponding interface. If we couldn't find the interface, the
5080 // program itself is ill-formed. However, we'll try to be helpful still by
5081 // providing the list of all of the categories we know about.
5082 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005083 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005084 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5085 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005086 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005087
Douglas Gregor52779fb2010-09-23 23:01:17 +00005088 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005089
5090 // Add all of the categories that have have corresponding interface
5091 // declarations in this class and any of its superclasses, except for
5092 // already-implemented categories in the class itself.
5093 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5094 Results.EnterNewScope();
5095 bool IgnoreImplemented = true;
5096 while (Class) {
5097 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5098 Category = Category->getNextClassCategory())
5099 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5100 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005101 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005102
5103 Class = Class->getSuperClass();
5104 IgnoreImplemented = false;
5105 }
5106 Results.ExitScope();
5107
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005108 HandleCodeCompleteResults(this, CodeCompleter,
5109 CodeCompletionContext::CCC_Other,
5110 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005111}
Douglas Gregor322328b2009-11-18 22:32:06 +00005112
John McCalld226f652010-08-21 09:40:31 +00005113void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005114 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005115 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005116
5117 // Figure out where this @synthesize lives.
5118 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005119 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005120 if (!Container ||
5121 (!isa<ObjCImplementationDecl>(Container) &&
5122 !isa<ObjCCategoryImplDecl>(Container)))
5123 return;
5124
5125 // Ignore any properties that have already been implemented.
5126 for (DeclContext::decl_iterator D = Container->decls_begin(),
5127 DEnd = Container->decls_end();
5128 D != DEnd; ++D)
5129 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5130 Results.Ignore(PropertyImpl->getPropertyDecl());
5131
5132 // Add any properties that we find.
5133 Results.EnterNewScope();
5134 if (ObjCImplementationDecl *ClassImpl
5135 = dyn_cast<ObjCImplementationDecl>(Container))
5136 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
5137 Results);
5138 else
5139 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
5140 false, CurContext, Results);
5141 Results.ExitScope();
5142
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005143 HandleCodeCompleteResults(this, CodeCompleter,
5144 CodeCompletionContext::CCC_Other,
5145 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005146}
5147
5148void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5149 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005150 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005151 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005152 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005153
5154 // Figure out where this @synthesize lives.
5155 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005156 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005157 if (!Container ||
5158 (!isa<ObjCImplementationDecl>(Container) &&
5159 !isa<ObjCCategoryImplDecl>(Container)))
5160 return;
5161
5162 // Figure out which interface we're looking into.
5163 ObjCInterfaceDecl *Class = 0;
5164 if (ObjCImplementationDecl *ClassImpl
5165 = dyn_cast<ObjCImplementationDecl>(Container))
5166 Class = ClassImpl->getClassInterface();
5167 else
5168 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5169 ->getClassInterface();
5170
5171 // Add all of the instance variables in this class and its superclasses.
5172 Results.EnterNewScope();
5173 for(; Class; Class = Class->getSuperClass()) {
5174 // FIXME: We could screen the type of each ivar for compatibility with
5175 // the property, but is that being too paternal?
5176 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
5177 IVarEnd = Class->ivar_end();
5178 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00005179 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00005180 }
5181 Results.ExitScope();
5182
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005183 HandleCodeCompleteResults(this, CodeCompleter,
5184 CodeCompletionContext::CCC_Other,
5185 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005186}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005187
Douglas Gregor408be5a2010-08-25 01:08:01 +00005188// Mapping from selectors to the methods that implement that selector, along
5189// with the "in original class" flag.
5190typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5191 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005192
5193/// \brief Find all of the methods that reside in the given container
5194/// (and its superclasses, protocols, etc.) that meet the given
5195/// criteria. Insert those methods into the map of known methods,
5196/// indexed by selector so they can be easily found.
5197static void FindImplementableMethods(ASTContext &Context,
5198 ObjCContainerDecl *Container,
5199 bool WantInstanceMethods,
5200 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005201 KnownMethodsMap &KnownMethods,
5202 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005203 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5204 // Recurse into protocols.
5205 const ObjCList<ObjCProtocolDecl> &Protocols
5206 = IFace->getReferencedProtocols();
5207 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005208 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005209 I != E; ++I)
5210 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005211 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005212
Douglas Gregorea766182010-10-18 18:21:28 +00005213 // Add methods from any class extensions and categories.
5214 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5215 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005216 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5217 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005218 KnownMethods, false);
5219
5220 // Visit the superclass.
5221 if (IFace->getSuperClass())
5222 FindImplementableMethods(Context, IFace->getSuperClass(),
5223 WantInstanceMethods, ReturnType,
5224 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005225 }
5226
5227 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5228 // Recurse into protocols.
5229 const ObjCList<ObjCProtocolDecl> &Protocols
5230 = Category->getReferencedProtocols();
5231 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005232 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005233 I != E; ++I)
5234 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005235 KnownMethods, InOriginalClass);
5236
5237 // If this category is the original class, jump to the interface.
5238 if (InOriginalClass && Category->getClassInterface())
5239 FindImplementableMethods(Context, Category->getClassInterface(),
5240 WantInstanceMethods, ReturnType, KnownMethods,
5241 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005242 }
5243
5244 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5245 // Recurse into protocols.
5246 const ObjCList<ObjCProtocolDecl> &Protocols
5247 = Protocol->getReferencedProtocols();
5248 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5249 E = Protocols.end();
5250 I != E; ++I)
5251 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005252 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005253 }
5254
5255 // Add methods in this container. This operation occurs last because
5256 // we want the methods from this container to override any methods
5257 // we've previously seen with the same selector.
5258 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5259 MEnd = Container->meth_end();
5260 M != MEnd; ++M) {
5261 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5262 if (!ReturnType.isNull() &&
5263 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5264 continue;
5265
Douglas Gregor408be5a2010-08-25 01:08:01 +00005266 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005267 }
5268 }
5269}
5270
5271void Sema::CodeCompleteObjCMethodDecl(Scope *S,
5272 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00005273 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00005274 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005275 // Determine the return type of the method we're declaring, if
5276 // provided.
5277 QualType ReturnType = GetTypeFromParser(ReturnTy);
5278
Douglas Gregorea766182010-10-18 18:21:28 +00005279 // Determine where we should start searching for methods.
5280 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005281 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00005282 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005283 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
5284 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005285 IsInImplementation = true;
5286 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00005287 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005288 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005289 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00005290 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00005291 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005292 }
5293
5294 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00005295 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00005296 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005297 }
5298
Douglas Gregorea766182010-10-18 18:21:28 +00005299 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005300 HandleCodeCompleteResults(this, CodeCompleter,
5301 CodeCompletionContext::CCC_Other,
5302 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005303 return;
5304 }
5305
5306 // Find all of the methods that we could declare/implement here.
5307 KnownMethodsMap KnownMethods;
5308 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00005309 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005310
Douglas Gregore8f5a172010-04-07 00:21:17 +00005311 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00005312 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005313 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005314 Results.EnterNewScope();
5315 PrintingPolicy Policy(Context.PrintingPolicy);
5316 Policy.AnonymousTagLocations = false;
5317 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
5318 MEnd = KnownMethods.end();
5319 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00005320 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005321 CodeCompletionString *Pattern = new CodeCompletionString;
5322
5323 // If the result type was not already provided, add it to the
5324 // pattern as (type).
5325 if (ReturnType.isNull()) {
5326 std::string TypeStr;
5327 Method->getResultType().getAsStringInternal(TypeStr, Policy);
5328 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5329 Pattern->AddTextChunk(TypeStr);
5330 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5331 }
5332
5333 Selector Sel = Method->getSelector();
5334
5335 // Add the first part of the selector to the pattern.
5336 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
5337
5338 // Add parameters to the pattern.
5339 unsigned I = 0;
5340 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5341 PEnd = Method->param_end();
5342 P != PEnd; (void)++P, ++I) {
5343 // Add the part of the selector name.
5344 if (I == 0)
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00005345 Pattern->AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00005346 else if (I < Sel.getNumArgs()) {
5347 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00005348 Pattern->AddTypedTextChunk((Sel.getIdentifierInfoForSlot(I)->getName()
5349 + ":").str());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005350 } else
5351 break;
5352
5353 // Add the parameter type.
5354 std::string TypeStr;
5355 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
5356 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5357 Pattern->AddTextChunk(TypeStr);
5358 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5359
5360 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregore17794f2010-08-31 05:13:43 +00005361 Pattern->AddTextChunk(Id->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005362 }
5363
5364 if (Method->isVariadic()) {
5365 if (Method->param_size() > 0)
5366 Pattern->AddChunk(CodeCompletionString::CK_Comma);
5367 Pattern->AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00005368 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005369
Douglas Gregor447107d2010-05-28 00:57:46 +00005370 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005371 // We will be defining the method here, so add a compound statement.
5372 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5373 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
5374 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5375 if (!Method->getResultType()->isVoidType()) {
5376 // If the result type is not void, add a return clause.
5377 Pattern->AddTextChunk("return");
5378 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5379 Pattern->AddPlaceholderChunk("expression");
5380 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
5381 } else
5382 Pattern->AddPlaceholderChunk("statements");
5383
5384 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5385 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
5386 }
5387
Douglas Gregor408be5a2010-08-25 01:08:01 +00005388 unsigned Priority = CCP_CodePattern;
5389 if (!M->second.second)
5390 Priority += CCD_InBaseClass;
5391
5392 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00005393 Method->isInstanceMethod()
5394 ? CXCursor_ObjCInstanceMethodDecl
5395 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005396 }
5397
5398 Results.ExitScope();
5399
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005400 HandleCodeCompleteResults(this, CodeCompleter,
5401 CodeCompletionContext::CCC_Other,
5402 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005403}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005404
5405void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5406 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005407 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00005408 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005409 IdentifierInfo **SelIdents,
5410 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005411 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005412 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005413 if (ExternalSource) {
5414 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5415 I != N; ++I) {
5416 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005417 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005418 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00005419
5420 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005421 }
5422 }
5423
5424 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00005425 typedef CodeCompletionResult Result;
Douglas Gregor52779fb2010-09-23 23:01:17 +00005426 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005427
5428 if (ReturnTy)
5429 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00005430
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005431 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005432 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5433 MEnd = MethodPool.end();
5434 M != MEnd; ++M) {
5435 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5436 &M->second.second;
5437 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005438 MethList = MethList->Next) {
5439 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5440 NumSelIdents))
5441 continue;
5442
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005443 if (AtParameterName) {
5444 // Suggest parameter names we've seen before.
5445 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5446 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5447 if (Param->getIdentifier()) {
5448 CodeCompletionString *Pattern = new CodeCompletionString;
5449 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5450 Results.AddResult(Pattern);
5451 }
5452 }
5453
5454 continue;
5455 }
5456
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005457 Result R(MethList->Method, 0);
5458 R.StartParameter = NumSelIdents;
5459 R.AllParametersAreInformative = false;
5460 R.DeclaringEntity = true;
5461 Results.MaybeAddResult(R, CurContext);
5462 }
5463 }
5464
5465 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005466 HandleCodeCompleteResults(this, CodeCompleter,
5467 CodeCompletionContext::CCC_Other,
5468 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005469}
Douglas Gregor87c08a52010-08-13 22:48:40 +00005470
Douglas Gregorf29c5232010-08-24 22:20:20 +00005471void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005472 ResultBuilder Results(*this,
5473 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005474 Results.EnterNewScope();
5475
5476 // #if <condition>
5477 CodeCompletionString *Pattern = new CodeCompletionString;
5478 Pattern->AddTypedTextChunk("if");
5479 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5480 Pattern->AddPlaceholderChunk("condition");
5481 Results.AddResult(Pattern);
5482
5483 // #ifdef <macro>
5484 Pattern = new CodeCompletionString;
5485 Pattern->AddTypedTextChunk("ifdef");
5486 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5487 Pattern->AddPlaceholderChunk("macro");
5488 Results.AddResult(Pattern);
5489
5490 // #ifndef <macro>
5491 Pattern = new CodeCompletionString;
5492 Pattern->AddTypedTextChunk("ifndef");
5493 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5494 Pattern->AddPlaceholderChunk("macro");
5495 Results.AddResult(Pattern);
5496
5497 if (InConditional) {
5498 // #elif <condition>
5499 Pattern = new CodeCompletionString;
5500 Pattern->AddTypedTextChunk("elif");
5501 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5502 Pattern->AddPlaceholderChunk("condition");
5503 Results.AddResult(Pattern);
5504
5505 // #else
5506 Pattern = new CodeCompletionString;
5507 Pattern->AddTypedTextChunk("else");
5508 Results.AddResult(Pattern);
5509
5510 // #endif
5511 Pattern = new CodeCompletionString;
5512 Pattern->AddTypedTextChunk("endif");
5513 Results.AddResult(Pattern);
5514 }
5515
5516 // #include "header"
5517 Pattern = new CodeCompletionString;
5518 Pattern->AddTypedTextChunk("include");
5519 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5520 Pattern->AddTextChunk("\"");
5521 Pattern->AddPlaceholderChunk("header");
5522 Pattern->AddTextChunk("\"");
5523 Results.AddResult(Pattern);
5524
5525 // #include <header>
5526 Pattern = new CodeCompletionString;
5527 Pattern->AddTypedTextChunk("include");
5528 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5529 Pattern->AddTextChunk("<");
5530 Pattern->AddPlaceholderChunk("header");
5531 Pattern->AddTextChunk(">");
5532 Results.AddResult(Pattern);
5533
5534 // #define <macro>
5535 Pattern = new CodeCompletionString;
5536 Pattern->AddTypedTextChunk("define");
5537 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5538 Pattern->AddPlaceholderChunk("macro");
5539 Results.AddResult(Pattern);
5540
5541 // #define <macro>(<args>)
5542 Pattern = new CodeCompletionString;
5543 Pattern->AddTypedTextChunk("define");
5544 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5545 Pattern->AddPlaceholderChunk("macro");
5546 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5547 Pattern->AddPlaceholderChunk("args");
5548 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5549 Results.AddResult(Pattern);
5550
5551 // #undef <macro>
5552 Pattern = new CodeCompletionString;
5553 Pattern->AddTypedTextChunk("undef");
5554 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5555 Pattern->AddPlaceholderChunk("macro");
5556 Results.AddResult(Pattern);
5557
5558 // #line <number>
5559 Pattern = new CodeCompletionString;
5560 Pattern->AddTypedTextChunk("line");
5561 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5562 Pattern->AddPlaceholderChunk("number");
5563 Results.AddResult(Pattern);
5564
5565 // #line <number> "filename"
5566 Pattern = new CodeCompletionString;
5567 Pattern->AddTypedTextChunk("line");
5568 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5569 Pattern->AddPlaceholderChunk("number");
5570 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5571 Pattern->AddTextChunk("\"");
5572 Pattern->AddPlaceholderChunk("filename");
5573 Pattern->AddTextChunk("\"");
5574 Results.AddResult(Pattern);
5575
5576 // #error <message>
5577 Pattern = new CodeCompletionString;
5578 Pattern->AddTypedTextChunk("error");
5579 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5580 Pattern->AddPlaceholderChunk("message");
5581 Results.AddResult(Pattern);
5582
5583 // #pragma <arguments>
5584 Pattern = new CodeCompletionString;
5585 Pattern->AddTypedTextChunk("pragma");
5586 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5587 Pattern->AddPlaceholderChunk("arguments");
5588 Results.AddResult(Pattern);
5589
5590 if (getLangOptions().ObjC1) {
5591 // #import "header"
5592 Pattern = new CodeCompletionString;
5593 Pattern->AddTypedTextChunk("import");
5594 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5595 Pattern->AddTextChunk("\"");
5596 Pattern->AddPlaceholderChunk("header");
5597 Pattern->AddTextChunk("\"");
5598 Results.AddResult(Pattern);
5599
5600 // #import <header>
5601 Pattern = new CodeCompletionString;
5602 Pattern->AddTypedTextChunk("import");
5603 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5604 Pattern->AddTextChunk("<");
5605 Pattern->AddPlaceholderChunk("header");
5606 Pattern->AddTextChunk(">");
5607 Results.AddResult(Pattern);
5608 }
5609
5610 // #include_next "header"
5611 Pattern = new CodeCompletionString;
5612 Pattern->AddTypedTextChunk("include_next");
5613 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5614 Pattern->AddTextChunk("\"");
5615 Pattern->AddPlaceholderChunk("header");
5616 Pattern->AddTextChunk("\"");
5617 Results.AddResult(Pattern);
5618
5619 // #include_next <header>
5620 Pattern = new CodeCompletionString;
5621 Pattern->AddTypedTextChunk("include_next");
5622 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5623 Pattern->AddTextChunk("<");
5624 Pattern->AddPlaceholderChunk("header");
5625 Pattern->AddTextChunk(">");
5626 Results.AddResult(Pattern);
5627
5628 // #warning <message>
5629 Pattern = new CodeCompletionString;
5630 Pattern->AddTypedTextChunk("warning");
5631 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5632 Pattern->AddPlaceholderChunk("message");
5633 Results.AddResult(Pattern);
5634
5635 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5636 // completions for them. And __include_macros is a Clang-internal extension
5637 // that we don't want to encourage anyone to use.
5638
5639 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5640 Results.ExitScope();
5641
Douglas Gregorf44e8542010-08-24 19:08:16 +00005642 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005643 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005644 Results.data(), Results.size());
5645}
5646
5647void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005648 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005649 S->getFnParent()? Sema::PCC_RecoveryInFunction
5650 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005651}
5652
Douglas Gregorf29c5232010-08-24 22:20:20 +00005653void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005654 ResultBuilder Results(*this,
5655 IsDefinition? CodeCompletionContext::CCC_MacroName
5656 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005657 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5658 // Add just the names of macros, not their arguments.
5659 Results.EnterNewScope();
5660 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5661 MEnd = PP.macro_end();
5662 M != MEnd; ++M) {
5663 CodeCompletionString *Pattern = new CodeCompletionString;
5664 Pattern->AddTypedTextChunk(M->first->getName());
5665 Results.AddResult(Pattern);
5666 }
5667 Results.ExitScope();
5668 } else if (IsDefinition) {
5669 // FIXME: Can we detect when the user just wrote an include guard above?
5670 }
5671
Douglas Gregor52779fb2010-09-23 23:01:17 +00005672 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005673 Results.data(), Results.size());
5674}
5675
Douglas Gregorf29c5232010-08-24 22:20:20 +00005676void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005677 ResultBuilder Results(*this,
5678 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005679
5680 if (!CodeCompleter || CodeCompleter->includeMacros())
5681 AddMacroResults(PP, Results);
5682
5683 // defined (<macro>)
5684 Results.EnterNewScope();
5685 CodeCompletionString *Pattern = new CodeCompletionString;
5686 Pattern->AddTypedTextChunk("defined");
5687 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5688 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5689 Pattern->AddPlaceholderChunk("macro");
5690 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5691 Results.AddResult(Pattern);
5692 Results.ExitScope();
5693
5694 HandleCodeCompleteResults(this, CodeCompleter,
5695 CodeCompletionContext::CCC_PreprocessorExpression,
5696 Results.data(), Results.size());
5697}
5698
5699void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5700 IdentifierInfo *Macro,
5701 MacroInfo *MacroInfo,
5702 unsigned Argument) {
5703 // FIXME: In the future, we could provide "overload" results, much like we
5704 // do for function calls.
5705
5706 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005707 S->getFnParent()? Sema::PCC_RecoveryInFunction
5708 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005709}
5710
Douglas Gregor55817af2010-08-25 17:04:25 +00005711void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005712 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005713 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005714 0, 0);
5715}
5716
Douglas Gregor87c08a52010-08-13 22:48:40 +00005717void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00005718 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00005719 ResultBuilder Builder(*this, CodeCompletionContext::CCC_Recovery);
Douglas Gregor87c08a52010-08-13 22:48:40 +00005720
Douglas Gregor8071e422010-08-15 06:18:01 +00005721 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5722 CodeCompletionDeclConsumer Consumer(Builder,
5723 Context.getTranslationUnitDecl());
5724 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5725 Consumer);
5726 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005727
5728 if (!CodeCompleter || CodeCompleter->includeMacros())
5729 AddMacroResults(PP, Builder);
5730
5731 Results.clear();
5732 Results.insert(Results.end(),
5733 Builder.data(), Builder.data() + Builder.size());
5734}