blob: 2877d52b084ea1c40f595a2894073b1c9acf21d3 [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//===----------------------------------------------------------------------===//
13#include "Sema.h"
Douglas Gregor1ca6ae82010-01-14 01:09:38 +000014#include "Lookup.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000015#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000016#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000023#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000024#include <list>
25#include <map>
26#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000027
28using namespace clang;
29
Douglas Gregor86d9a522009-09-21 16:56:56 +000030namespace {
31 /// \brief A container of code-completion results.
32 class ResultBuilder {
33 public:
34 /// \brief The type of a name-lookup filter, which can be provided to the
35 /// name-lookup routines to specify which declarations should be included in
36 /// the result set (when it returns true) and which declarations should be
37 /// filtered out (returns false).
38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
39
40 typedef CodeCompleteConsumer::Result Result;
41
42 private:
43 /// \brief The actual results we have found.
44 std::vector<Result> Results;
45
46 /// \brief A record of all of the declarations we have found and placed
47 /// into the result set, used to ensure that no declaration ever gets into
48 /// the result set twice.
49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
50
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000051 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
52
53 /// \brief An entry in the shadow map, which is optimized to store
54 /// a single (declaration, index) mapping (the common case) but
55 /// can also store a list of (declaration, index) mappings.
56 class ShadowMapEntry {
57 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
58
59 /// \brief Contains either the solitary NamedDecl * or a vector
60 /// of (declaration, index) pairs.
61 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
62
63 /// \brief When the entry contains a single declaration, this is
64 /// the index associated with that entry.
65 unsigned SingleDeclIndex;
66
67 public:
68 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
69
70 void Add(NamedDecl *ND, unsigned Index) {
71 if (DeclOrVector.isNull()) {
72 // 0 - > 1 elements: just set the single element information.
73 DeclOrVector = ND;
74 SingleDeclIndex = Index;
75 return;
76 }
77
78 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
79 // 1 -> 2 elements: create the vector of results and push in the
80 // existing declaration.
81 DeclIndexPairVector *Vec = new DeclIndexPairVector;
82 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
83 DeclOrVector = Vec;
84 }
85
86 // Add the new element to the end of the vector.
87 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
88 DeclIndexPair(ND, Index));
89 }
90
91 void Destroy() {
92 if (DeclIndexPairVector *Vec
93 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
94 delete Vec;
95 DeclOrVector = ((NamedDecl *)0);
96 }
97 }
98
99 // Iteration.
100 class iterator;
101 iterator begin() const;
102 iterator end() const;
103 };
104
Douglas Gregor86d9a522009-09-21 16:56:56 +0000105 /// \brief A mapping from declaration names to the declarations that have
106 /// this name within a particular scope and their index within the list of
107 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000108 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000109
110 /// \brief The semantic analysis object for which results are being
111 /// produced.
112 Sema &SemaRef;
113
114 /// \brief If non-NULL, a filter function used to remove any code-completion
115 /// results that are not desirable.
116 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000117
118 /// \brief Whether we should allow declarations as
119 /// nested-name-specifiers that would otherwise be filtered out.
120 bool AllowNestedNameSpecifiers;
121
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000122 /// \brief If set, the type that we would prefer our resulting value
123 /// declarations to have.
124 ///
125 /// Closely matching the preferred type gives a boost to a result's
126 /// priority.
127 CanQualType PreferredType;
128
Douglas Gregor86d9a522009-09-21 16:56:56 +0000129 /// \brief A list of shadow maps, which is used to model name hiding at
130 /// different levels of, e.g., the inheritance hierarchy.
131 std::list<ShadowMap> ShadowMaps;
132
133 public:
134 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor45bcd432010-01-14 03:21:49 +0000135 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000136
Douglas Gregord8e8a582010-05-25 21:41:55 +0000137 /// \brief Whether we should include code patterns in the completion
138 /// results.
139 bool includeCodePatterns() const {
140 return SemaRef.CodeCompleter &&
141 SemaRef.CodeCompleter->includeCodePatterns();
142 }
143
Douglas Gregor86d9a522009-09-21 16:56:56 +0000144 /// \brief Set the filter used for code-completion results.
145 void setFilter(LookupFilter Filter) {
146 this->Filter = Filter;
147 }
148
149 typedef std::vector<Result>::iterator iterator;
150 iterator begin() { return Results.begin(); }
151 iterator end() { return Results.end(); }
152
153 Result *data() { return Results.empty()? 0 : &Results.front(); }
154 unsigned size() const { return Results.size(); }
155 bool empty() const { return Results.empty(); }
156
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000157 /// \brief Specify the preferred type.
158 void setPreferredType(QualType T) {
159 PreferredType = SemaRef.Context.getCanonicalType(T);
160 }
161
Douglas Gregor45bcd432010-01-14 03:21:49 +0000162 /// \brief Specify whether nested-name-specifiers are allowed.
163 void allowNestedNameSpecifiers(bool Allow = true) {
164 AllowNestedNameSpecifiers = Allow;
165 }
166
Douglas Gregore495b7f2010-01-14 00:20:49 +0000167 /// \brief Determine whether the given declaration is at all interesting
168 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000169 ///
170 /// \param ND the declaration that we are inspecting.
171 ///
172 /// \param AsNestedNameSpecifier will be set true if this declaration is
173 /// only interesting when it is a nested-name-specifier.
174 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000175
176 /// \brief Check whether the result is hidden by the Hiding declaration.
177 ///
178 /// \returns true if the result is hidden and cannot be found, false if
179 /// the hidden result could still be found. When false, \p R may be
180 /// modified to describe how the result can be found (e.g., via extra
181 /// qualification).
182 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
183 NamedDecl *Hiding);
184
Douglas Gregor86d9a522009-09-21 16:56:56 +0000185 /// \brief Add a new result to this result set (if it isn't already in one
186 /// of the shadow maps), or replace an existing result (for, e.g., a
187 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000188 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000189 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000190 ///
191 /// \param R the context in which this result will be named.
192 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000193
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000194 /// \brief Add a new result to this result set, where we already know
195 /// the hiding declation (if any).
196 ///
197 /// \param R the result to add (if it is unique).
198 ///
199 /// \param CurContext the context in which this result will be named.
200 ///
201 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000202 ///
203 /// \param InBaseClass whether the result was found in a base
204 /// class of the searched context.
205 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
206 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000207
Douglas Gregora4477812010-01-14 16:01:26 +0000208 /// \brief Add a new non-declaration result to this result set.
209 void AddResult(Result R);
210
Douglas Gregor86d9a522009-09-21 16:56:56 +0000211 /// \brief Enter into a new scope.
212 void EnterNewScope();
213
214 /// \brief Exit from the current scope.
215 void ExitScope();
216
Douglas Gregor55385fe2009-11-18 04:19:12 +0000217 /// \brief Ignore this declaration, if it is seen again.
218 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
219
Douglas Gregor86d9a522009-09-21 16:56:56 +0000220 /// \name Name lookup predicates
221 ///
222 /// These predicates can be passed to the name lookup functions to filter the
223 /// results of name lookup. All of the predicates have the same type, so that
224 ///
225 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000226 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000227 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000228 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000229 bool IsNestedNameSpecifier(NamedDecl *ND) const;
230 bool IsEnum(NamedDecl *ND) const;
231 bool IsClassOrStruct(NamedDecl *ND) const;
232 bool IsUnion(NamedDecl *ND) const;
233 bool IsNamespace(NamedDecl *ND) const;
234 bool IsNamespaceOrAlias(NamedDecl *ND) const;
235 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000236 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000237 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000238 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000239 //@}
240 };
241}
242
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000243class ResultBuilder::ShadowMapEntry::iterator {
244 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
245 unsigned SingleDeclIndex;
246
247public:
248 typedef DeclIndexPair value_type;
249 typedef value_type reference;
250 typedef std::ptrdiff_t difference_type;
251 typedef std::input_iterator_tag iterator_category;
252
253 class pointer {
254 DeclIndexPair Value;
255
256 public:
257 pointer(const DeclIndexPair &Value) : Value(Value) { }
258
259 const DeclIndexPair *operator->() const {
260 return &Value;
261 }
262 };
263
264 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
265
266 iterator(NamedDecl *SingleDecl, unsigned Index)
267 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
268
269 iterator(const DeclIndexPair *Iterator)
270 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
271
272 iterator &operator++() {
273 if (DeclOrIterator.is<NamedDecl *>()) {
274 DeclOrIterator = (NamedDecl *)0;
275 SingleDeclIndex = 0;
276 return *this;
277 }
278
279 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
280 ++I;
281 DeclOrIterator = I;
282 return *this;
283 }
284
285 iterator operator++(int) {
286 iterator tmp(*this);
287 ++(*this);
288 return tmp;
289 }
290
291 reference operator*() const {
292 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
293 return reference(ND, SingleDeclIndex);
294
Douglas Gregord490f952009-12-06 21:27:58 +0000295 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000296 }
297
298 pointer operator->() const {
299 return pointer(**this);
300 }
301
302 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000303 return X.DeclOrIterator.getOpaqueValue()
304 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000305 X.SingleDeclIndex == Y.SingleDeclIndex;
306 }
307
308 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000309 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000310 }
311};
312
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000313ResultBuilder::ShadowMapEntry::iterator
314ResultBuilder::ShadowMapEntry::begin() const {
315 if (DeclOrVector.isNull())
316 return iterator();
317
318 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
319 return iterator(ND, SingleDeclIndex);
320
321 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
322}
323
324ResultBuilder::ShadowMapEntry::iterator
325ResultBuilder::ShadowMapEntry::end() const {
326 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
327 return iterator();
328
329 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
330}
331
Douglas Gregor456c4a12009-09-21 20:12:40 +0000332/// \brief Compute the qualification required to get from the current context
333/// (\p CurContext) to the target context (\p TargetContext).
334///
335/// \param Context the AST context in which the qualification will be used.
336///
337/// \param CurContext the context where an entity is being named, which is
338/// typically based on the current scope.
339///
340/// \param TargetContext the context in which the named entity actually
341/// resides.
342///
343/// \returns a nested name specifier that refers into the target context, or
344/// NULL if no qualification is needed.
345static NestedNameSpecifier *
346getRequiredQualification(ASTContext &Context,
347 DeclContext *CurContext,
348 DeclContext *TargetContext) {
349 llvm::SmallVector<DeclContext *, 4> TargetParents;
350
351 for (DeclContext *CommonAncestor = TargetContext;
352 CommonAncestor && !CommonAncestor->Encloses(CurContext);
353 CommonAncestor = CommonAncestor->getLookupParent()) {
354 if (CommonAncestor->isTransparentContext() ||
355 CommonAncestor->isFunctionOrMethod())
356 continue;
357
358 TargetParents.push_back(CommonAncestor);
359 }
360
361 NestedNameSpecifier *Result = 0;
362 while (!TargetParents.empty()) {
363 DeclContext *Parent = TargetParents.back();
364 TargetParents.pop_back();
365
366 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
367 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
368 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
369 Result = NestedNameSpecifier::Create(Context, Result,
370 false,
371 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000372 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000373 return Result;
374}
375
Douglas Gregor45bcd432010-01-14 03:21:49 +0000376bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
377 bool &AsNestedNameSpecifier) const {
378 AsNestedNameSpecifier = false;
379
Douglas Gregore495b7f2010-01-14 00:20:49 +0000380 ND = ND->getUnderlyingDecl();
381 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000382
383 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000384 if (!ND->getDeclName())
385 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000386
387 // Friend declarations and declarations introduced due to friends are never
388 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000389 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000390 return false;
391
Douglas Gregor76282942009-12-11 17:31:05 +0000392 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000393 if (isa<ClassTemplateSpecializationDecl>(ND) ||
394 isa<ClassTemplatePartialSpecializationDecl>(ND))
395 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000396
Douglas Gregor76282942009-12-11 17:31:05 +0000397 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000398 if (isa<UsingDecl>(ND))
399 return false;
400
401 // Some declarations have reserved names that we don't want to ever show.
402 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000403 // __va_list_tag is a freak of nature. Find it and skip it.
404 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000405 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000406
Douglas Gregorf52cede2009-10-09 22:16:47 +0000407 // Filter out names reserved for the implementation (C99 7.1.3,
408 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000409 //
410 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000411 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000412 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000413 if (Name[0] == '_' &&
414 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000415 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000416 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000417 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000418
Douglas Gregor86d9a522009-09-21 16:56:56 +0000419 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000420 if (isa<CXXConstructorDecl>(ND))
421 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000422
423 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000424 if (Filter && !(this->*Filter)(ND)) {
425 // Check whether it is interesting as a nested-name-specifier.
426 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
427 IsNestedNameSpecifier(ND) &&
428 (Filter != &ResultBuilder::IsMember ||
429 (isa<CXXRecordDecl>(ND) &&
430 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
431 AsNestedNameSpecifier = true;
432 return true;
433 }
434
Douglas Gregore495b7f2010-01-14 00:20:49 +0000435 return false;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000436 }
John McCall0d6b1642010-04-23 18:46:30 +0000437
438 if (Filter == &ResultBuilder::IsNestedNameSpecifier)
439 AsNestedNameSpecifier = true;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000440
Douglas Gregore495b7f2010-01-14 00:20:49 +0000441 // ... then it must be interesting!
442 return true;
443}
444
Douglas Gregor6660d842010-01-14 00:41:07 +0000445bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
446 NamedDecl *Hiding) {
447 // In C, there is no way to refer to a hidden name.
448 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
449 // name if we introduce the tag type.
450 if (!SemaRef.getLangOptions().CPlusPlus)
451 return true;
452
453 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
454
455 // There is no way to qualify a name declared in a function or method.
456 if (HiddenCtx->isFunctionOrMethod())
457 return true;
458
459 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
460 return true;
461
462 // We can refer to the result with the appropriate qualification. Do it.
463 R.Hidden = true;
464 R.QualifierIsInformative = false;
465
466 if (!R.Qualifier)
467 R.Qualifier = getRequiredQualification(SemaRef.Context,
468 CurContext,
469 R.Declaration->getDeclContext());
470 return false;
471}
472
Douglas Gregore495b7f2010-01-14 00:20:49 +0000473void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
474 assert(!ShadowMaps.empty() && "Must enter into a results scope");
475
476 if (R.Kind != Result::RK_Declaration) {
477 // For non-declaration results, just add the result.
478 Results.push_back(R);
479 return;
480 }
481
482 // Look through using declarations.
483 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
484 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
485 return;
486 }
487
488 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
489 unsigned IDNS = CanonDecl->getIdentifierNamespace();
490
Douglas Gregor45bcd432010-01-14 03:21:49 +0000491 bool AsNestedNameSpecifier = false;
492 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000493 return;
494
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000496 ShadowMapEntry::iterator I, IEnd;
497 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
498 if (NamePos != SMap.end()) {
499 I = NamePos->second.begin();
500 IEnd = NamePos->second.end();
501 }
502
503 for (; I != IEnd; ++I) {
504 NamedDecl *ND = I->first;
505 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000506 if (ND->getCanonicalDecl() == CanonDecl) {
507 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000508 Results[Index].Declaration = R.Declaration;
509
Douglas Gregor86d9a522009-09-21 16:56:56 +0000510 // We're done.
511 return;
512 }
513 }
514
515 // This is a new declaration in this scope. However, check whether this
516 // declaration name is hidden by a similarly-named declaration in an outer
517 // scope.
518 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
519 --SMEnd;
520 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000521 ShadowMapEntry::iterator I, IEnd;
522 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
523 if (NamePos != SM->end()) {
524 I = NamePos->second.begin();
525 IEnd = NamePos->second.end();
526 }
527 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000528 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000529 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000530 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
531 Decl::IDNS_ObjCProtocol)))
532 continue;
533
534 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000535 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000536 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000537 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000538 continue;
539
540 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000541 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000542 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000543
544 break;
545 }
546 }
547
548 // Make sure that any given declaration only shows up in the result set once.
549 if (!AllDeclsFound.insert(CanonDecl))
550 return;
551
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000552 // If the filter is for nested-name-specifiers, then this result starts a
553 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000554 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000555 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000556 R.Priority = CCP_NestedNameSpecifier;
557 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000558
Douglas Gregor0563c262009-09-22 23:15:58 +0000559 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000560 if (R.QualifierIsInformative && !R.Qualifier &&
561 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000562 DeclContext *Ctx = R.Declaration->getDeclContext();
563 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
564 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
565 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
566 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
567 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
568 else
569 R.QualifierIsInformative = false;
570 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000571
Douglas Gregor86d9a522009-09-21 16:56:56 +0000572 // Insert this result into the set of results and into the current shadow
573 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000574 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000575 Results.push_back(R);
576}
577
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000578enum SimplifiedTypeClass {
579 STC_Arithmetic,
580 STC_Array,
581 STC_Block,
582 STC_Function,
583 STC_ObjectiveC,
584 STC_Other,
585 STC_Pointer,
586 STC_Record,
587 STC_Void
588};
589
590/// \brief A simplified classification of types used to determine whether two
591/// types are "similar enough" when adjusting priorities.
592static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
593 switch (T->getTypeClass()) {
594 case Type::Builtin:
595 switch (cast<BuiltinType>(T)->getKind()) {
596 case BuiltinType::Void:
597 return STC_Void;
598
599 case BuiltinType::NullPtr:
600 return STC_Pointer;
601
602 case BuiltinType::Overload:
603 case BuiltinType::Dependent:
604 case BuiltinType::UndeducedAuto:
605 return STC_Other;
606
607 case BuiltinType::ObjCId:
608 case BuiltinType::ObjCClass:
609 case BuiltinType::ObjCSel:
610 return STC_ObjectiveC;
611
612 default:
613 return STC_Arithmetic;
614 }
615 return STC_Other;
616
617 case Type::Complex:
618 return STC_Arithmetic;
619
620 case Type::Pointer:
621 return STC_Pointer;
622
623 case Type::BlockPointer:
624 return STC_Block;
625
626 case Type::LValueReference:
627 case Type::RValueReference:
628 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
629
630 case Type::ConstantArray:
631 case Type::IncompleteArray:
632 case Type::VariableArray:
633 case Type::DependentSizedArray:
634 return STC_Array;
635
636 case Type::DependentSizedExtVector:
637 case Type::Vector:
638 case Type::ExtVector:
639 return STC_Arithmetic;
640
641 case Type::FunctionProto:
642 case Type::FunctionNoProto:
643 return STC_Function;
644
645 case Type::Record:
646 return STC_Record;
647
648 case Type::Enum:
649 return STC_Arithmetic;
650
651 case Type::ObjCObject:
652 case Type::ObjCInterface:
653 case Type::ObjCObjectPointer:
654 return STC_ObjectiveC;
655
656 default:
657 return STC_Other;
658 }
659}
660
661/// \brief Get the type that a given expression will have if this declaration
662/// is used as an expression in its "typical" code-completion form.
663static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
664 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
665
666 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
667 return C.getTypeDeclType(Type);
668 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
669 return C.getObjCInterfaceType(Iface);
670
671 QualType T;
672 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
673 T = Function->getResultType();
674 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
675 T = Method->getResultType();
676 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
677 T = FunTmpl->getTemplatedDecl()->getResultType();
678 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
679 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
680 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
681 T = Property->getType();
682 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
683 T = Value->getType();
684 else
685 return QualType();
686
687 return T.getNonReferenceType();
688}
689
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000690void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000691 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000692 if (R.Kind != Result::RK_Declaration) {
693 // For non-declaration results, just add the result.
694 Results.push_back(R);
695 return;
696 }
697
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000698 // Look through using declarations.
699 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
700 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
701 return;
702 }
703
Douglas Gregor45bcd432010-01-14 03:21:49 +0000704 bool AsNestedNameSpecifier = false;
705 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000706 return;
707
708 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
709 return;
710
711 // Make sure that any given declaration only shows up in the result set once.
712 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
713 return;
714
715 // If the filter is for nested-name-specifiers, then this result starts a
716 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000717 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000718 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000719 R.Priority = CCP_NestedNameSpecifier;
720 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000721 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
722 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
723 ->getLookupContext()))
724 R.QualifierIsInformative = true;
725
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000726 // If this result is supposed to have an informative qualifier, add one.
727 if (R.QualifierIsInformative && !R.Qualifier &&
728 !R.StartsNestedNameSpecifier) {
729 DeclContext *Ctx = R.Declaration->getDeclContext();
730 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
731 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
732 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
733 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000734 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000735 else
736 R.QualifierIsInformative = false;
737 }
738
Douglas Gregor12e13132010-05-26 22:00:08 +0000739 // Adjust the priority if this result comes from a base class.
740 if (InBaseClass)
741 R.Priority += CCD_InBaseClass;
742
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000743 if (!PreferredType.isNull()) {
744 if (ValueDecl *Value = dyn_cast<ValueDecl>(R.Declaration)) {
745 CanQualType T = SemaRef.Context.getCanonicalType(
746 getDeclUsageType(SemaRef.Context, Value));
747 // Check for exactly-matching types (modulo qualifiers).
748 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, T))
749 R.Priority /= CCF_ExactTypeMatch;
750 // Check for nearly-matching types, based on classification of each.
751 else if ((getSimplifiedTypeClass(PreferredType)
752 == getSimplifiedTypeClass(T)) &&
753 !(PreferredType->isEnumeralType() && T->isEnumeralType()))
754 R.Priority /= CCF_SimilarTypeMatch;
755 }
756 }
757
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000758 // Insert this result into the set of results.
759 Results.push_back(R);
760}
761
Douglas Gregora4477812010-01-14 16:01:26 +0000762void ResultBuilder::AddResult(Result R) {
763 assert(R.Kind != Result::RK_Declaration &&
764 "Declaration results need more context");
765 Results.push_back(R);
766}
767
Douglas Gregor86d9a522009-09-21 16:56:56 +0000768/// \brief Enter into a new scope.
769void ResultBuilder::EnterNewScope() {
770 ShadowMaps.push_back(ShadowMap());
771}
772
773/// \brief Exit from the current scope.
774void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000775 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
776 EEnd = ShadowMaps.back().end();
777 E != EEnd;
778 ++E)
779 E->second.Destroy();
780
Douglas Gregor86d9a522009-09-21 16:56:56 +0000781 ShadowMaps.pop_back();
782}
783
Douglas Gregor791215b2009-09-21 20:51:25 +0000784/// \brief Determines whether this given declaration will be found by
785/// ordinary name lookup.
786bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000787 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
788
Douglas Gregor791215b2009-09-21 20:51:25 +0000789 unsigned IDNS = Decl::IDNS_Ordinary;
790 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000791 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000792 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
793 return true;
794
Douglas Gregor791215b2009-09-21 20:51:25 +0000795 return ND->getIdentifierNamespace() & IDNS;
796}
797
Douglas Gregor01dfea02010-01-10 23:08:15 +0000798/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000799/// ordinary name lookup but is not a type name.
800bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
801 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
802 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
803 return false;
804
805 unsigned IDNS = Decl::IDNS_Ordinary;
806 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000807 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000808 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
809 return true;
810
811 return ND->getIdentifierNamespace() & IDNS;
812}
813
814/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000815/// ordinary name lookup.
816bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000817 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
818
Douglas Gregor01dfea02010-01-10 23:08:15 +0000819 unsigned IDNS = Decl::IDNS_Ordinary;
820 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000821 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000822
823 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000824 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
825 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000826}
827
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828/// \brief Determines whether the given declaration is suitable as the
829/// start of a C++ nested-name-specifier, e.g., a class or namespace.
830bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
831 // Allow us to find class templates, too.
832 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
833 ND = ClassTemplate->getTemplatedDecl();
834
835 return SemaRef.isAcceptableNestedNameSpecifier(ND);
836}
837
838/// \brief Determines whether the given declaration is an enumeration.
839bool ResultBuilder::IsEnum(NamedDecl *ND) const {
840 return isa<EnumDecl>(ND);
841}
842
843/// \brief Determines whether the given declaration is a class or struct.
844bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
845 // Allow us to find class templates, too.
846 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
847 ND = ClassTemplate->getTemplatedDecl();
848
849 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000850 return RD->getTagKind() == TTK_Class ||
851 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000852
853 return false;
854}
855
856/// \brief Determines whether the given declaration is a union.
857bool ResultBuilder::IsUnion(NamedDecl *ND) const {
858 // Allow us to find class templates, too.
859 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
860 ND = ClassTemplate->getTemplatedDecl();
861
862 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000863 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000864
865 return false;
866}
867
868/// \brief Determines whether the given declaration is a namespace.
869bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
870 return isa<NamespaceDecl>(ND);
871}
872
873/// \brief Determines whether the given declaration is a namespace or
874/// namespace alias.
875bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
876 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
877}
878
Douglas Gregor76282942009-12-11 17:31:05 +0000879/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000880bool ResultBuilder::IsType(NamedDecl *ND) const {
881 return isa<TypeDecl>(ND);
882}
883
Douglas Gregor76282942009-12-11 17:31:05 +0000884/// \brief Determines which members of a class should be visible via
885/// "." or "->". Only value declarations, nested name specifiers, and
886/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000887bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000888 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
889 ND = Using->getTargetDecl();
890
Douglas Gregorce821962009-12-11 18:14:22 +0000891 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
892 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000893}
894
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000895static bool isObjCReceiverType(ASTContext &C, QualType T) {
896 T = C.getCanonicalType(T);
897 switch (T->getTypeClass()) {
898 case Type::ObjCObject:
899 case Type::ObjCInterface:
900 case Type::ObjCObjectPointer:
901 return true;
902
903 case Type::Builtin:
904 switch (cast<BuiltinType>(T)->getKind()) {
905 case BuiltinType::ObjCId:
906 case BuiltinType::ObjCClass:
907 case BuiltinType::ObjCSel:
908 return true;
909
910 default:
911 break;
912 }
913 return false;
914
915 default:
916 break;
917 }
918
919 if (!C.getLangOptions().CPlusPlus)
920 return false;
921
922 // FIXME: We could perform more analysis here to determine whether a
923 // particular class type has any conversions to Objective-C types. For now,
924 // just accept all class types.
925 return T->isDependentType() || T->isRecordType();
926}
927
928bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
929 QualType T = getDeclUsageType(SemaRef.Context, ND);
930 if (T.isNull())
931 return false;
932
933 T = SemaRef.Context.getBaseElementType(T);
934 return isObjCReceiverType(SemaRef.Context, T);
935}
936
937
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000938/// \rief Determines whether the given declaration is an Objective-C
939/// instance variable.
940bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
941 return isa<ObjCIvarDecl>(ND);
942}
943
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000944namespace {
945 /// \brief Visible declaration consumer that adds a code-completion result
946 /// for each visible declaration.
947 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
948 ResultBuilder &Results;
949 DeclContext *CurContext;
950
951 public:
952 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
953 : Results(Results), CurContext(CurContext) { }
954
Douglas Gregor0cc84042010-01-14 15:47:35 +0000955 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
956 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000957 }
958 };
959}
960
Douglas Gregor86d9a522009-09-21 16:56:56 +0000961/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +0000962static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000963 ResultBuilder &Results) {
964 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor12e13132010-05-26 22:00:08 +0000965 Results.AddResult(Result("short", CCP_Type));
966 Results.AddResult(Result("long", CCP_Type));
967 Results.AddResult(Result("signed", CCP_Type));
968 Results.AddResult(Result("unsigned", CCP_Type));
969 Results.AddResult(Result("void", CCP_Type));
970 Results.AddResult(Result("char", CCP_Type));
971 Results.AddResult(Result("int", CCP_Type));
972 Results.AddResult(Result("float", CCP_Type));
973 Results.AddResult(Result("double", CCP_Type));
974 Results.AddResult(Result("enum", CCP_Type));
975 Results.AddResult(Result("struct", CCP_Type));
976 Results.AddResult(Result("union", CCP_Type));
977 Results.AddResult(Result("const", CCP_Type));
978 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000979
Douglas Gregor86d9a522009-09-21 16:56:56 +0000980 if (LangOpts.C99) {
981 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +0000982 Results.AddResult(Result("_Complex", CCP_Type));
983 Results.AddResult(Result("_Imaginary", CCP_Type));
984 Results.AddResult(Result("_Bool", CCP_Type));
985 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000986 }
987
988 if (LangOpts.CPlusPlus) {
989 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +0000990 Results.AddResult(Result("bool", CCP_Type));
991 Results.AddResult(Result("class", CCP_Type));
992 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000993
Douglas Gregorc8bddde2010-05-28 00:22:41 +0000994 // typename qualified-id
995 CodeCompletionString *Pattern = new CodeCompletionString;
996 Pattern->AddTypedTextChunk("typename");
997 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
998 Pattern->AddPlaceholderChunk("qualifier");
999 Pattern->AddTextChunk("::");
1000 Pattern->AddPlaceholderChunk("name");
1001 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001002
Douglas Gregor86d9a522009-09-21 16:56:56 +00001003 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001004 Results.AddResult(Result("auto", CCP_Type));
1005 Results.AddResult(Result("char16_t", CCP_Type));
1006 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001007
1008 CodeCompletionString *Pattern = new CodeCompletionString;
1009 Pattern->AddTypedTextChunk("decltype");
1010 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1011 Pattern->AddPlaceholderChunk("expression");
1012 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1013 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001014 }
1015 }
1016
1017 // GNU extensions
1018 if (LangOpts.GNUMode) {
1019 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001020 // Results.AddResult(Result("_Decimal32"));
1021 // Results.AddResult(Result("_Decimal64"));
1022 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001023
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001024 CodeCompletionString *Pattern = new CodeCompletionString;
1025 Pattern->AddTypedTextChunk("typeof");
1026 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1027 Pattern->AddPlaceholderChunk("expression");
1028 Results.AddResult(Result(Pattern));
1029
1030 Pattern = new CodeCompletionString;
1031 Pattern->AddTypedTextChunk("typeof");
1032 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1033 Pattern->AddPlaceholderChunk("type");
1034 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1035 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001036 }
1037}
1038
Douglas Gregor01dfea02010-01-10 23:08:15 +00001039static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
1040 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001041 ResultBuilder &Results) {
1042 typedef CodeCompleteConsumer::Result Result;
1043 // Note: we don't suggest either "auto" or "register", because both
1044 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1045 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001046 Results.AddResult(Result("extern"));
1047 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001048}
1049
1050static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
1051 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001052 ResultBuilder &Results) {
1053 typedef CodeCompleteConsumer::Result Result;
1054 switch (CCC) {
1055 case Action::CCC_Class:
1056 case Action::CCC_MemberTemplate:
1057 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001058 Results.AddResult(Result("explicit"));
1059 Results.AddResult(Result("friend"));
1060 Results.AddResult(Result("mutable"));
1061 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001062 }
1063 // Fall through
1064
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001065 case Action::CCC_ObjCInterface:
1066 case Action::CCC_ObjCImplementation:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001067 case Action::CCC_Namespace:
1068 case Action::CCC_Template:
1069 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001070 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001071 break;
1072
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001073 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001074 case Action::CCC_Expression:
1075 case Action::CCC_Statement:
1076 case Action::CCC_ForInit:
1077 case Action::CCC_Condition:
Douglas Gregordc845342010-05-25 05:58:43 +00001078 case Action::CCC_RecoveryInFunction:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001079 break;
1080 }
1081}
1082
Douglas Gregorbca403c2010-01-13 23:51:12 +00001083static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1084static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1085static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001086 ResultBuilder &Results,
1087 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001088static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001089 ResultBuilder &Results,
1090 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001091static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001092 ResultBuilder &Results,
1093 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001094static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001095
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001096static void AddTypedefResult(ResultBuilder &Results) {
1097 CodeCompletionString *Pattern = new CodeCompletionString;
1098 Pattern->AddTypedTextChunk("typedef");
1099 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1100 Pattern->AddPlaceholderChunk("type");
1101 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1102 Pattern->AddPlaceholderChunk("name");
1103 Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1104}
1105
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001106static bool WantTypesInContext(Action::CodeCompletionContext CCC,
1107 const LangOptions &LangOpts) {
1108 if (LangOpts.CPlusPlus)
1109 return true;
1110
1111 switch (CCC) {
1112 case Action::CCC_Namespace:
1113 case Action::CCC_Class:
1114 case Action::CCC_ObjCInstanceVariableList:
1115 case Action::CCC_Template:
1116 case Action::CCC_MemberTemplate:
1117 case Action::CCC_Statement:
1118 case Action::CCC_RecoveryInFunction:
1119 return true;
1120
1121 case Action::CCC_ObjCInterface:
1122 case Action::CCC_ObjCImplementation:
1123 case Action::CCC_Expression:
1124 case Action::CCC_Condition:
1125 return false;
1126
1127 case Action::CCC_ForInit:
1128 return LangOpts.ObjC1 || LangOpts.C99;
1129 }
1130
1131 return false;
1132}
1133
Douglas Gregor01dfea02010-01-10 23:08:15 +00001134/// \brief Add language constructs that show up for "ordinary" names.
1135static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
1136 Scope *S,
1137 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001138 ResultBuilder &Results) {
1139 typedef CodeCompleteConsumer::Result Result;
1140 switch (CCC) {
1141 case Action::CCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001142 if (SemaRef.getLangOptions().CPlusPlus) {
1143 CodeCompletionString *Pattern = 0;
1144
1145 if (Results.includeCodePatterns()) {
1146 // namespace <identifier> { declarations }
1147 CodeCompletionString *Pattern = new CodeCompletionString;
1148 Pattern->AddTypedTextChunk("namespace");
1149 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1150 Pattern->AddPlaceholderChunk("identifier");
1151 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1152 Pattern->AddPlaceholderChunk("declarations");
1153 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1154 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1155 Results.AddResult(Result(Pattern));
1156 }
1157
Douglas Gregor01dfea02010-01-10 23:08:15 +00001158 // namespace identifier = identifier ;
1159 Pattern = new CodeCompletionString;
1160 Pattern->AddTypedTextChunk("namespace");
1161 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001162 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001163 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001164 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001165 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001166
1167 // Using directives
1168 Pattern = new CodeCompletionString;
1169 Pattern->AddTypedTextChunk("using");
1170 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1171 Pattern->AddTextChunk("namespace");
1172 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1173 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001174 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001175
1176 // asm(string-literal)
1177 Pattern = new CodeCompletionString;
1178 Pattern->AddTypedTextChunk("asm");
1179 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1180 Pattern->AddPlaceholderChunk("string-literal");
1181 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001182 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001183
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001184 if (Results.includeCodePatterns()) {
1185 // Explicit template instantiation
1186 Pattern = new CodeCompletionString;
1187 Pattern->AddTypedTextChunk("template");
1188 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1189 Pattern->AddPlaceholderChunk("declaration");
1190 Results.AddResult(Result(Pattern));
1191 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001192 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001193
1194 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001195 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001196
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001197 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001198 // Fall through
1199
1200 case Action::CCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001201 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001202 // Using declaration
1203 CodeCompletionString *Pattern = new CodeCompletionString;
1204 Pattern->AddTypedTextChunk("using");
1205 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001206 Pattern->AddPlaceholderChunk("qualifier");
1207 Pattern->AddTextChunk("::");
1208 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001209 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001210
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001211 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001212 if (SemaRef.CurContext->isDependentContext()) {
1213 Pattern = new CodeCompletionString;
1214 Pattern->AddTypedTextChunk("using");
1215 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1216 Pattern->AddTextChunk("typename");
1217 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001218 Pattern->AddPlaceholderChunk("qualifier");
1219 Pattern->AddTextChunk("::");
1220 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001221 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001222 }
1223
1224 if (CCC == Action::CCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001225 AddTypedefResult(Results);
1226
Douglas Gregor01dfea02010-01-10 23:08:15 +00001227 // public:
1228 Pattern = new CodeCompletionString;
1229 Pattern->AddTypedTextChunk("public");
1230 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001231 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001232
1233 // protected:
1234 Pattern = new CodeCompletionString;
1235 Pattern->AddTypedTextChunk("protected");
1236 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001237 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001238
1239 // private:
1240 Pattern = new CodeCompletionString;
1241 Pattern->AddTypedTextChunk("private");
1242 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001243 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001244 }
1245 }
1246 // Fall through
1247
1248 case Action::CCC_Template:
1249 case Action::CCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001250 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001251 // template < parameters >
1252 CodeCompletionString *Pattern = new CodeCompletionString;
1253 Pattern->AddTypedTextChunk("template");
1254 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1255 Pattern->AddPlaceholderChunk("parameters");
1256 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001257 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001258 }
1259
Douglas Gregorbca403c2010-01-13 23:51:12 +00001260 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1261 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001262 break;
1263
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001264 case Action::CCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001265 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1266 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1267 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001268 break;
1269
1270 case Action::CCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001271 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1272 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1273 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001274 break;
1275
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001276 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001277 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001278 break;
1279
Douglas Gregordc845342010-05-25 05:58:43 +00001280 case Action::CCC_RecoveryInFunction:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 case Action::CCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001282 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283
1284 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001285 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286 Pattern = new CodeCompletionString;
1287 Pattern->AddTypedTextChunk("try");
1288 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1289 Pattern->AddPlaceholderChunk("statements");
1290 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1291 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1292 Pattern->AddTextChunk("catch");
1293 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1294 Pattern->AddPlaceholderChunk("declaration");
1295 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1296 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1297 Pattern->AddPlaceholderChunk("statements");
1298 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1299 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001300 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001301 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001302 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001303 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001304
Douglas Gregord8e8a582010-05-25 21:41:55 +00001305 if (Results.includeCodePatterns()) {
1306 // if (condition) { statements }
1307 Pattern = new CodeCompletionString;
1308 Pattern->AddTypedTextChunk("if");
1309 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1310 if (SemaRef.getLangOptions().CPlusPlus)
1311 Pattern->AddPlaceholderChunk("condition");
1312 else
1313 Pattern->AddPlaceholderChunk("expression");
1314 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1315 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1316 Pattern->AddPlaceholderChunk("statements");
1317 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1318 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1319 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320
Douglas Gregord8e8a582010-05-25 21:41:55 +00001321 // switch (condition) { }
1322 Pattern = new CodeCompletionString;
1323 Pattern->AddTypedTextChunk("switch");
1324 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1325 if (SemaRef.getLangOptions().CPlusPlus)
1326 Pattern->AddPlaceholderChunk("condition");
1327 else
1328 Pattern->AddPlaceholderChunk("expression");
1329 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1330 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1331 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1332 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1333 Results.AddResult(Result(Pattern));
1334 }
1335
Douglas Gregor01dfea02010-01-10 23:08:15 +00001336 // Switch-specific statements.
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337 if (!SemaRef.getSwitchStack().empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001338 // case expression:
1339 Pattern = new CodeCompletionString;
1340 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001341 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001342 Pattern->AddPlaceholderChunk("expression");
1343 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001344 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001345
1346 // default:
1347 Pattern = new CodeCompletionString;
1348 Pattern->AddTypedTextChunk("default");
1349 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001350 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001351 }
1352
Douglas Gregord8e8a582010-05-25 21:41:55 +00001353 if (Results.includeCodePatterns()) {
1354 /// while (condition) { statements }
1355 Pattern = new CodeCompletionString;
1356 Pattern->AddTypedTextChunk("while");
1357 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1358 if (SemaRef.getLangOptions().CPlusPlus)
1359 Pattern->AddPlaceholderChunk("condition");
1360 else
1361 Pattern->AddPlaceholderChunk("expression");
1362 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1363 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1364 Pattern->AddPlaceholderChunk("statements");
1365 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1366 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1367 Results.AddResult(Result(Pattern));
1368
1369 // do { statements } while ( expression );
1370 Pattern = new CodeCompletionString;
1371 Pattern->AddTypedTextChunk("do");
1372 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1373 Pattern->AddPlaceholderChunk("statements");
1374 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1375 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1376 Pattern->AddTextChunk("while");
1377 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001378 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001379 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1380 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381
Douglas Gregord8e8a582010-05-25 21:41:55 +00001382 // for ( for-init-statement ; condition ; expression ) { statements }
1383 Pattern = new CodeCompletionString;
1384 Pattern->AddTypedTextChunk("for");
1385 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1386 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1387 Pattern->AddPlaceholderChunk("init-statement");
1388 else
1389 Pattern->AddPlaceholderChunk("init-expression");
1390 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1391 Pattern->AddPlaceholderChunk("condition");
1392 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1393 Pattern->AddPlaceholderChunk("inc-expression");
1394 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1395 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1396 Pattern->AddPlaceholderChunk("statements");
1397 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1398 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1399 Results.AddResult(Result(Pattern));
1400 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001401
1402 if (S->getContinueParent()) {
1403 // continue ;
1404 Pattern = new CodeCompletionString;
1405 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001406 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001407 }
1408
1409 if (S->getBreakParent()) {
1410 // break ;
1411 Pattern = new CodeCompletionString;
1412 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001413 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001414 }
1415
1416 // "return expression ;" or "return ;", depending on whether we
1417 // know the function is void or not.
1418 bool isVoid = false;
1419 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1420 isVoid = Function->getResultType()->isVoidType();
1421 else if (ObjCMethodDecl *Method
1422 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1423 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001424 else if (SemaRef.getCurBlock() &&
1425 !SemaRef.getCurBlock()->ReturnType.isNull())
1426 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001427 Pattern = new CodeCompletionString;
1428 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001429 if (!isVoid) {
1430 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001431 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001432 }
Douglas Gregora4477812010-01-14 16:01:26 +00001433 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001434
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 // goto identifier ;
1436 Pattern = new CodeCompletionString;
1437 Pattern->AddTypedTextChunk("goto");
1438 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1439 Pattern->AddPlaceholderChunk("label");
1440 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001442 // Using directives
1443 Pattern = new CodeCompletionString;
1444 Pattern->AddTypedTextChunk("using");
1445 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1446 Pattern->AddTextChunk("namespace");
1447 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1448 Pattern->AddPlaceholderChunk("identifier");
1449 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001450 }
1451
1452 // Fall through (for statement expressions).
1453 case Action::CCC_ForInit:
1454 case Action::CCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001455 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001456 // Fall through: conditions and statements can have expressions.
1457
1458 case Action::CCC_Expression: {
1459 CodeCompletionString *Pattern = 0;
1460 if (SemaRef.getLangOptions().CPlusPlus) {
1461 // 'this', if we're in a non-static member function.
1462 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1463 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001464 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001465
1466 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001467 Results.AddResult(Result("true"));
1468 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001469
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001470 // dynamic_cast < type-id > ( expression )
1471 Pattern = new CodeCompletionString;
1472 Pattern->AddTypedTextChunk("dynamic_cast");
1473 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1474 Pattern->AddPlaceholderChunk("type");
1475 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1476 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1477 Pattern->AddPlaceholderChunk("expression");
1478 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1479 Results.AddResult(Result(Pattern));
1480
1481 // static_cast < type-id > ( expression )
1482 Pattern = new CodeCompletionString;
1483 Pattern->AddTypedTextChunk("static_cast");
1484 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1485 Pattern->AddPlaceholderChunk("type");
1486 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1487 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1488 Pattern->AddPlaceholderChunk("expression");
1489 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1490 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001491
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001492 // reinterpret_cast < type-id > ( expression )
1493 Pattern = new CodeCompletionString;
1494 Pattern->AddTypedTextChunk("reinterpret_cast");
1495 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1496 Pattern->AddPlaceholderChunk("type");
1497 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1498 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1499 Pattern->AddPlaceholderChunk("expression");
1500 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1501 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001502
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001503 // const_cast < type-id > ( expression )
1504 Pattern = new CodeCompletionString;
1505 Pattern->AddTypedTextChunk("const_cast");
1506 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1507 Pattern->AddPlaceholderChunk("type");
1508 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1509 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1510 Pattern->AddPlaceholderChunk("expression");
1511 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1512 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001513
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001514 // typeid ( expression-or-type )
1515 Pattern = new CodeCompletionString;
1516 Pattern->AddTypedTextChunk("typeid");
1517 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1518 Pattern->AddPlaceholderChunk("expression-or-type");
1519 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1520 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001521
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001522 // new T ( ... )
1523 Pattern = new CodeCompletionString;
1524 Pattern->AddTypedTextChunk("new");
1525 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1526 Pattern->AddPlaceholderChunk("type");
1527 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1528 Pattern->AddPlaceholderChunk("expressions");
1529 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1530 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001531
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001532 // new T [ ] ( ... )
1533 Pattern = new CodeCompletionString;
1534 Pattern->AddTypedTextChunk("new");
1535 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1536 Pattern->AddPlaceholderChunk("type");
1537 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1538 Pattern->AddPlaceholderChunk("size");
1539 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1540 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1541 Pattern->AddPlaceholderChunk("expressions");
1542 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1543 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001544
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001545 // delete expression
1546 Pattern = new CodeCompletionString;
1547 Pattern->AddTypedTextChunk("delete");
1548 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1549 Pattern->AddPlaceholderChunk("expression");
1550 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001551
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001552 // delete [] expression
1553 Pattern = new CodeCompletionString;
1554 Pattern->AddTypedTextChunk("delete");
1555 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1556 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1557 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1558 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1559 Pattern->AddPlaceholderChunk("expression");
1560 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001562 // throw expression
1563 Pattern = new CodeCompletionString;
1564 Pattern->AddTypedTextChunk("throw");
1565 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566 Pattern->AddPlaceholderChunk("expression");
1567 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001568
1569 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001570 }
1571
1572 if (SemaRef.getLangOptions().ObjC1) {
1573 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001574 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1575 // The interface can be NULL.
1576 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1577 if (ID->getSuperClass())
1578 Results.AddResult(Result("super"));
1579 }
1580
Douglas Gregorbca403c2010-01-13 23:51:12 +00001581 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001582 }
1583
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001584 // sizeof expression
1585 Pattern = new CodeCompletionString;
1586 Pattern->AddTypedTextChunk("sizeof");
1587 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1588 Pattern->AddPlaceholderChunk("expression-or-type");
1589 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1590 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001591 break;
1592 }
1593 }
1594
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001595 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1596 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001597
1598 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregora4477812010-01-14 16:01:26 +00001599 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001600}
1601
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001602/// \brief If the given declaration has an associated type, add it as a result
1603/// type chunk.
1604static void AddResultTypeChunk(ASTContext &Context,
1605 NamedDecl *ND,
1606 CodeCompletionString *Result) {
1607 if (!ND)
1608 return;
1609
1610 // Determine the type of the declaration (if it has a type).
1611 QualType T;
1612 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1613 T = Function->getResultType();
1614 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1615 T = Method->getResultType();
1616 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1617 T = FunTmpl->getTemplatedDecl()->getResultType();
1618 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1619 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1620 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1621 /* Do nothing: ignore unresolved using declarations*/
1622 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1623 T = Value->getType();
1624 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1625 T = Property->getType();
1626
1627 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1628 return;
1629
Douglas Gregor84139d62010-04-05 21:25:31 +00001630 PrintingPolicy Policy(Context.PrintingPolicy);
1631 Policy.AnonymousTagLocations = false;
1632
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001633 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001634 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001635 Result->AddResultTypeChunk(TypeStr);
1636}
1637
Douglas Gregor86d9a522009-09-21 16:56:56 +00001638/// \brief Add function parameter chunks to the given code completion string.
1639static void AddFunctionParameterChunks(ASTContext &Context,
1640 FunctionDecl *Function,
1641 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001642 typedef CodeCompletionString::Chunk Chunk;
1643
Douglas Gregor86d9a522009-09-21 16:56:56 +00001644 CodeCompletionString *CCStr = Result;
1645
1646 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1647 ParmVarDecl *Param = Function->getParamDecl(P);
1648
1649 if (Param->hasDefaultArg()) {
1650 // When we see an optional default argument, put that argument and
1651 // the remaining default arguments into a new, optional string.
1652 CodeCompletionString *Opt = new CodeCompletionString;
1653 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1654 CCStr = Opt;
1655 }
1656
1657 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001658 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001659
1660 // Format the placeholder string.
1661 std::string PlaceholderStr;
1662 if (Param->getIdentifier())
1663 PlaceholderStr = Param->getIdentifier()->getName();
1664
1665 Param->getType().getAsStringInternal(PlaceholderStr,
1666 Context.PrintingPolicy);
1667
1668 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001669 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001670 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001671
1672 if (const FunctionProtoType *Proto
1673 = Function->getType()->getAs<FunctionProtoType>())
1674 if (Proto->isVariadic())
1675 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001676}
1677
1678/// \brief Add template parameter chunks to the given code completion string.
1679static void AddTemplateParameterChunks(ASTContext &Context,
1680 TemplateDecl *Template,
1681 CodeCompletionString *Result,
1682 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001683 typedef CodeCompletionString::Chunk Chunk;
1684
Douglas Gregor86d9a522009-09-21 16:56:56 +00001685 CodeCompletionString *CCStr = Result;
1686 bool FirstParameter = true;
1687
1688 TemplateParameterList *Params = Template->getTemplateParameters();
1689 TemplateParameterList::iterator PEnd = Params->end();
1690 if (MaxParameters)
1691 PEnd = Params->begin() + MaxParameters;
1692 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1693 bool HasDefaultArg = false;
1694 std::string PlaceholderStr;
1695 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1696 if (TTP->wasDeclaredWithTypename())
1697 PlaceholderStr = "typename";
1698 else
1699 PlaceholderStr = "class";
1700
1701 if (TTP->getIdentifier()) {
1702 PlaceholderStr += ' ';
1703 PlaceholderStr += TTP->getIdentifier()->getName();
1704 }
1705
1706 HasDefaultArg = TTP->hasDefaultArgument();
1707 } else if (NonTypeTemplateParmDecl *NTTP
1708 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1709 if (NTTP->getIdentifier())
1710 PlaceholderStr = NTTP->getIdentifier()->getName();
1711 NTTP->getType().getAsStringInternal(PlaceholderStr,
1712 Context.PrintingPolicy);
1713 HasDefaultArg = NTTP->hasDefaultArgument();
1714 } else {
1715 assert(isa<TemplateTemplateParmDecl>(*P));
1716 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1717
1718 // Since putting the template argument list into the placeholder would
1719 // be very, very long, we just use an abbreviation.
1720 PlaceholderStr = "template<...> class";
1721 if (TTP->getIdentifier()) {
1722 PlaceholderStr += ' ';
1723 PlaceholderStr += TTP->getIdentifier()->getName();
1724 }
1725
1726 HasDefaultArg = TTP->hasDefaultArgument();
1727 }
1728
1729 if (HasDefaultArg) {
1730 // When we see an optional default argument, put that argument and
1731 // the remaining default arguments into a new, optional string.
1732 CodeCompletionString *Opt = new CodeCompletionString;
1733 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1734 CCStr = Opt;
1735 }
1736
1737 if (FirstParameter)
1738 FirstParameter = false;
1739 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001740 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001741
1742 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001743 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001744 }
1745}
1746
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001747/// \brief Add a qualifier to the given code-completion string, if the
1748/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001749static void
1750AddQualifierToCompletionString(CodeCompletionString *Result,
1751 NestedNameSpecifier *Qualifier,
1752 bool QualifierIsInformative,
1753 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001754 if (!Qualifier)
1755 return;
1756
1757 std::string PrintedNNS;
1758 {
1759 llvm::raw_string_ostream OS(PrintedNNS);
1760 Qualifier->print(OS, Context.PrintingPolicy);
1761 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001762 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001763 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001764 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001765 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001766}
1767
Douglas Gregora61a8792009-12-11 18:44:16 +00001768static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1769 FunctionDecl *Function) {
1770 const FunctionProtoType *Proto
1771 = Function->getType()->getAs<FunctionProtoType>();
1772 if (!Proto || !Proto->getTypeQuals())
1773 return;
1774
1775 std::string QualsStr;
1776 if (Proto->getTypeQuals() & Qualifiers::Const)
1777 QualsStr += " const";
1778 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1779 QualsStr += " volatile";
1780 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1781 QualsStr += " restrict";
1782 Result->AddInformativeChunk(QualsStr);
1783}
1784
Douglas Gregor86d9a522009-09-21 16:56:56 +00001785/// \brief If possible, create a new code completion string for the given
1786/// result.
1787///
1788/// \returns Either a new, heap-allocated code completion string describing
1789/// how to use this result, or NULL to indicate that the string or name of the
1790/// result is all that is needed.
1791CodeCompletionString *
1792CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001793 typedef CodeCompletionString::Chunk Chunk;
1794
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001795 if (Kind == RK_Pattern)
1796 return Pattern->Clone();
1797
1798 CodeCompletionString *Result = new CodeCompletionString;
1799
1800 if (Kind == RK_Keyword) {
1801 Result->AddTypedTextChunk(Keyword);
1802 return Result;
1803 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001804
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001805 if (Kind == RK_Macro) {
1806 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001807 assert(MI && "Not a macro?");
1808
1809 Result->AddTypedTextChunk(Macro->getName());
1810
1811 if (!MI->isFunctionLike())
1812 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001813
1814 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001815 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001816 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1817 A != AEnd; ++A) {
1818 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001819 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001820
1821 if (!MI->isVariadic() || A != AEnd - 1) {
1822 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001823 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001824 continue;
1825 }
1826
1827 // Variadic argument; cope with the different between GNU and C99
1828 // variadic macros, providing a single placeholder for the rest of the
1829 // arguments.
1830 if ((*A)->isStr("__VA_ARGS__"))
1831 Result->AddPlaceholderChunk("...");
1832 else {
1833 std::string Arg = (*A)->getName();
1834 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001835 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001836 }
1837 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001838 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001839 return Result;
1840 }
1841
Douglas Gregord8e8a582010-05-25 21:41:55 +00001842 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001843 NamedDecl *ND = Declaration;
1844
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001845 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00001846 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001847 Result->AddTextChunk("::");
1848 return Result;
1849 }
1850
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001851 AddResultTypeChunk(S.Context, ND, Result);
1852
Douglas Gregor86d9a522009-09-21 16:56:56 +00001853 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001854 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1855 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001856 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001857 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001858 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001859 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001860 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001861 return Result;
1862 }
1863
1864 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001865 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1866 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001867 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00001868 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001869
1870 // Figure out which template parameters are deduced (or have default
1871 // arguments).
1872 llvm::SmallVector<bool, 16> Deduced;
1873 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1874 unsigned LastDeducibleArgument;
1875 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1876 --LastDeducibleArgument) {
1877 if (!Deduced[LastDeducibleArgument - 1]) {
1878 // C++0x: Figure out if the template argument has a default. If so,
1879 // the user doesn't need to type this argument.
1880 // FIXME: We need to abstract template parameters better!
1881 bool HasDefaultArg = false;
1882 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1883 LastDeducibleArgument - 1);
1884 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1885 HasDefaultArg = TTP->hasDefaultArgument();
1886 else if (NonTypeTemplateParmDecl *NTTP
1887 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1888 HasDefaultArg = NTTP->hasDefaultArgument();
1889 else {
1890 assert(isa<TemplateTemplateParmDecl>(Param));
1891 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001892 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001893 }
1894
1895 if (!HasDefaultArg)
1896 break;
1897 }
1898 }
1899
1900 if (LastDeducibleArgument) {
1901 // Some of the function template arguments cannot be deduced from a
1902 // function call, so we introduce an explicit template argument list
1903 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001904 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001905 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1906 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001907 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001908 }
1909
1910 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001911 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001912 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001913 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001914 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001915 return Result;
1916 }
1917
1918 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001919 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1920 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001921 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001922 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001923 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001924 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001925 return Result;
1926 }
1927
Douglas Gregor9630eb62009-11-17 16:44:22 +00001928 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00001929 Selector Sel = Method->getSelector();
1930 if (Sel.isUnarySelector()) {
1931 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1932 return Result;
1933 }
1934
Douglas Gregord3c68542009-11-19 01:08:35 +00001935 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1936 SelName += ':';
1937 if (StartParameter == 0)
1938 Result->AddTypedTextChunk(SelName);
1939 else {
1940 Result->AddInformativeChunk(SelName);
1941
1942 // If there is only one parameter, and we're past it, add an empty
1943 // typed-text chunk since there is nothing to type.
1944 if (Method->param_size() == 1)
1945 Result->AddTypedTextChunk("");
1946 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00001947 unsigned Idx = 0;
1948 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1949 PEnd = Method->param_end();
1950 P != PEnd; (void)++P, ++Idx) {
1951 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001952 std::string Keyword;
1953 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00001954 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001955 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1956 Keyword += II->getName().str();
1957 Keyword += ":";
Douglas Gregor4ad96852009-11-19 07:41:15 +00001958 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001959 Result->AddInformativeChunk(Keyword);
1960 } else if (Idx == StartParameter)
1961 Result->AddTypedTextChunk(Keyword);
1962 else
1963 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001964 }
Douglas Gregord3c68542009-11-19 01:08:35 +00001965
1966 // If we're before the starting parameter, skip the placeholder.
1967 if (Idx < StartParameter)
1968 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00001969
1970 std::string Arg;
1971 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1972 Arg = "(" + Arg + ")";
1973 if (IdentifierInfo *II = (*P)->getIdentifier())
1974 Arg += II->getName().str();
Douglas Gregor4ad96852009-11-19 07:41:15 +00001975 if (AllParametersAreInformative)
1976 Result->AddInformativeChunk(Arg);
1977 else
1978 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001979 }
1980
Douglas Gregor2a17af02009-12-23 00:21:46 +00001981 if (Method->isVariadic()) {
1982 if (AllParametersAreInformative)
1983 Result->AddInformativeChunk(", ...");
1984 else
1985 Result->AddPlaceholderChunk(", ...");
1986 }
1987
Douglas Gregor9630eb62009-11-17 16:44:22 +00001988 return Result;
1989 }
1990
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001991 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00001992 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1993 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001994
1995 Result->AddTypedTextChunk(ND->getNameAsString());
1996 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001997}
1998
Douglas Gregor86d802e2009-09-23 00:34:09 +00001999CodeCompletionString *
2000CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2001 unsigned CurrentArg,
2002 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002003 typedef CodeCompletionString::Chunk Chunk;
2004
Douglas Gregor86d802e2009-09-23 00:34:09 +00002005 CodeCompletionString *Result = new CodeCompletionString;
2006 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002007 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002008 const FunctionProtoType *Proto
2009 = dyn_cast<FunctionProtoType>(getFunctionType());
2010 if (!FDecl && !Proto) {
2011 // Function without a prototype. Just give the return type and a
2012 // highlighted ellipsis.
2013 const FunctionType *FT = getFunctionType();
2014 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002015 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002016 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2017 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2018 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002019 return Result;
2020 }
2021
2022 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002023 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002024 else
2025 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002026 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002027
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002028 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002029 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2030 for (unsigned I = 0; I != NumParams; ++I) {
2031 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002032 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002033
2034 std::string ArgString;
2035 QualType ArgType;
2036
2037 if (FDecl) {
2038 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2039 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2040 } else {
2041 ArgType = Proto->getArgType(I);
2042 }
2043
2044 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2045
2046 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002047 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002048 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002049 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002050 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002051 }
2052
2053 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002054 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002055 if (CurrentArg < NumParams)
2056 Result->AddTextChunk("...");
2057 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002058 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002059 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002060 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002061
2062 return Result;
2063}
2064
Douglas Gregor86d9a522009-09-21 16:56:56 +00002065namespace {
2066 struct SortCodeCompleteResult {
2067 typedef CodeCompleteConsumer::Result Result;
2068
Douglas Gregor6a684032009-09-28 03:51:44 +00002069 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002070 Selector XSel = X.getObjCSelector();
2071 Selector YSel = Y.getObjCSelector();
2072 if (!XSel.isNull() && !YSel.isNull()) {
2073 // We are comparing two selectors.
2074 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2075 if (N == 0)
2076 ++N;
2077 for (unsigned I = 0; I != N; ++I) {
2078 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2079 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2080 if (!XId || !YId)
2081 return XId && !YId;
2082
2083 switch (XId->getName().compare_lower(YId->getName())) {
2084 case -1: return true;
2085 case 1: return false;
2086 default: break;
2087 }
2088 }
2089
2090 return XSel.getNumArgs() < YSel.getNumArgs();
2091 }
2092
2093 // For non-selectors, order by kind.
2094 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00002095 return X.getNameKind() < Y.getNameKind();
2096
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002097 // Order identifiers by comparison of their lowercased names.
2098 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2099 return XId->getName().compare_lower(
2100 Y.getAsIdentifierInfo()->getName()) < 0;
2101
2102 // Order overloaded operators by the order in which they appear
2103 // in our list of operators.
2104 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2105 return XOp < Y.getCXXOverloadedOperator();
2106
2107 // Order C++0x user-defined literal operators lexically by their
2108 // lowercased suffixes.
2109 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2110 return XLit->getName().compare_lower(
2111 Y.getCXXLiteralIdentifier()->getName()) < 0;
2112
2113 // The only stable ordering we have is to turn the name into a
2114 // string and then compare the lower-case strings. This is
2115 // inefficient, but thankfully does not happen too often.
Benjamin Kramer0e7049f2009-12-05 10:22:15 +00002116 return llvm::StringRef(X.getAsString()).compare_lower(
2117 Y.getAsString()) < 0;
Douglas Gregor6a684032009-09-28 03:51:44 +00002118 }
2119
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002120 /// \brief Retrieve the name that should be used to order a result.
2121 ///
2122 /// If the name needs to be constructed as a string, that string will be
2123 /// saved into Saved and the returned StringRef will refer to it.
2124 static llvm::StringRef getOrderedName(const Result &R,
2125 std::string &Saved) {
2126 switch (R.Kind) {
2127 case Result::RK_Keyword:
2128 return R.Keyword;
2129
2130 case Result::RK_Pattern:
2131 return R.Pattern->getTypedText();
2132
2133 case Result::RK_Macro:
2134 return R.Macro->getName();
2135
2136 case Result::RK_Declaration:
2137 // Handle declarations below.
2138 break;
Douglas Gregor54f01612009-11-19 00:01:57 +00002139 }
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002140
2141 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor54f01612009-11-19 00:01:57 +00002142
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002143 // If the name is a simple identifier (by far the common case), or a
2144 // zero-argument selector, just return a reference to that identifier.
2145 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2146 return Id->getName();
2147 if (Name.isObjCZeroArgSelector())
2148 if (IdentifierInfo *Id
2149 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2150 return Id->getName();
2151
2152 Saved = Name.getAsString();
2153 return Saved;
2154 }
2155
2156 bool operator()(const Result &X, const Result &Y) const {
2157 std::string XSaved, YSaved;
2158 llvm::StringRef XStr = getOrderedName(X, XSaved);
2159 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2160 int cmp = XStr.compare_lower(YStr);
2161 if (cmp)
2162 return cmp < 0;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002163
2164 // Non-hidden names precede hidden names.
2165 if (X.Hidden != Y.Hidden)
2166 return !X.Hidden;
2167
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002168 // Non-nested-name-specifiers precede nested-name-specifiers.
2169 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2170 return !X.StartsNestedNameSpecifier;
2171
Douglas Gregor86d9a522009-09-21 16:56:56 +00002172 return false;
2173 }
2174 };
2175}
2176
Douglas Gregorbca403c2010-01-13 23:51:12 +00002177static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002178 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002179 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2180 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002181 M != MEnd; ++M)
Douglas Gregora4477812010-01-14 16:01:26 +00002182 Results.AddResult(M->first);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002183 Results.ExitScope();
2184}
2185
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002186static void HandleCodeCompleteResults(Sema *S,
2187 CodeCompleteConsumer *CodeCompleter,
2188 CodeCompleteConsumer::Result *Results,
2189 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002190 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2191
2192 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002193 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002194
2195 for (unsigned I = 0; I != NumResults; ++I)
2196 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002197}
2198
Douglas Gregor01dfea02010-01-10 23:08:15 +00002199void Sema::CodeCompleteOrdinaryName(Scope *S,
2200 CodeCompletionContext CompletionContext) {
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002201 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002202 ResultBuilder Results(*this);
2203
2204 // Determine how to filter results, e.g., so that the names of
2205 // values (functions, enumerators, function templates, etc.) are
2206 // only allowed where we can have an expression.
2207 switch (CompletionContext) {
2208 case CCC_Namespace:
2209 case CCC_Class:
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002210 case CCC_ObjCInterface:
2211 case CCC_ObjCImplementation:
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002212 case CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002213 case CCC_Template:
2214 case CCC_MemberTemplate:
2215 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2216 break;
2217
2218 case CCC_Expression:
2219 case CCC_Statement:
2220 case CCC_ForInit:
2221 case CCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002222 if (WantTypesInContext(CompletionContext, getLangOptions()))
2223 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2224 else
2225 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002226 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002227
2228 case CCC_RecoveryInFunction:
2229 // Unfiltered
2230 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002231 }
2232
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002233 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2234 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002235
2236 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002237 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002238 Results.ExitScope();
2239
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002240 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002241 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002242 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002243}
2244
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002245/// \brief Perform code-completion in an expression context when we know what
2246/// type we're looking for.
2247void Sema::CodeCompleteExpression(Scope *S, QualType T) {
2248 typedef CodeCompleteConsumer::Result Result;
2249 ResultBuilder Results(*this);
2250
2251 if (WantTypesInContext(CCC_Expression, getLangOptions()))
2252 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2253 else
2254 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2255 Results.setPreferredType(T.getNonReferenceType());
2256
2257 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2258 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2259
2260 Results.EnterNewScope();
2261 AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
2262 Results.ExitScope();
2263
2264 if (CodeCompleter->includeMacros())
2265 AddMacroResults(PP, Results);
2266 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2267}
2268
2269
Douglas Gregor95ac6552009-11-18 01:29:26 +00002270static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002271 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002272 DeclContext *CurContext,
2273 ResultBuilder &Results) {
2274 typedef CodeCompleteConsumer::Result Result;
2275
2276 // Add properties in this container.
2277 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2278 PEnd = Container->prop_end();
2279 P != PEnd;
2280 ++P)
2281 Results.MaybeAddResult(Result(*P, 0), CurContext);
2282
2283 // Add properties in referenced protocols.
2284 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2285 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2286 PEnd = Protocol->protocol_end();
2287 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002288 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002289 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002290 if (AllowCategories) {
2291 // Look through categories.
2292 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2293 Category; Category = Category->getNextClassCategory())
2294 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2295 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002296
2297 // Look through protocols.
2298 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2299 E = IFace->protocol_end();
2300 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002301 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002302
2303 // Look in the superclass.
2304 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002305 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2306 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002307 } else if (const ObjCCategoryDecl *Category
2308 = dyn_cast<ObjCCategoryDecl>(Container)) {
2309 // Look through protocols.
2310 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2311 PEnd = Category->protocol_end();
2312 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002313 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002314 }
2315}
2316
Douglas Gregor81b747b2009-09-17 21:32:03 +00002317void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2318 SourceLocation OpLoc,
2319 bool IsArrow) {
2320 if (!BaseE || !CodeCompleter)
2321 return;
2322
Douglas Gregor86d9a522009-09-21 16:56:56 +00002323 typedef CodeCompleteConsumer::Result Result;
2324
Douglas Gregor81b747b2009-09-17 21:32:03 +00002325 Expr *Base = static_cast<Expr *>(BaseE);
2326 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002327
2328 if (IsArrow) {
2329 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2330 BaseType = Ptr->getPointeeType();
2331 else if (BaseType->isObjCObjectPointerType())
2332 /*Do nothing*/ ;
2333 else
2334 return;
2335 }
2336
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002337 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002338 Results.EnterNewScope();
2339 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2340 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002341 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002342 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2343 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002344
Douglas Gregor95ac6552009-11-18 01:29:26 +00002345 if (getLangOptions().CPlusPlus) {
2346 if (!Results.empty()) {
2347 // The "template" keyword can follow "->" or "." in the grammar.
2348 // However, we only want to suggest the template keyword if something
2349 // is dependent.
2350 bool IsDependent = BaseType->isDependentType();
2351 if (!IsDependent) {
2352 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2353 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2354 IsDependent = Ctx->isDependentContext();
2355 break;
2356 }
2357 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002358
Douglas Gregor95ac6552009-11-18 01:29:26 +00002359 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002360 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002361 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002362 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002363 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2364 // Objective-C property reference.
2365
2366 // Add property results based on our interface.
2367 const ObjCObjectPointerType *ObjCPtr
2368 = BaseType->getAsObjCInterfacePointerType();
2369 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002370 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002371
2372 // Add properties from the protocols in a qualified interface.
2373 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2374 E = ObjCPtr->qual_end();
2375 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002376 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002377 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002378 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002379 // Objective-C instance variable access.
2380 ObjCInterfaceDecl *Class = 0;
2381 if (const ObjCObjectPointerType *ObjCPtr
2382 = BaseType->getAs<ObjCObjectPointerType>())
2383 Class = ObjCPtr->getInterfaceDecl();
2384 else
John McCallc12c5bb2010-05-15 11:32:37 +00002385 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002386
2387 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002388 if (Class) {
2389 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2390 Results.setFilter(&ResultBuilder::IsObjCIvar);
2391 LookupVisibleDecls(Class, LookupMemberName, Consumer);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002392 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002393 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002394
2395 // FIXME: How do we cope with isa?
2396
2397 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002398
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002399 // Hand off the results found for code completion.
2400 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002401}
2402
Douglas Gregor374929f2009-09-18 15:37:17 +00002403void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2404 if (!CodeCompleter)
2405 return;
2406
Douglas Gregor86d9a522009-09-21 16:56:56 +00002407 typedef CodeCompleteConsumer::Result Result;
2408 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00002409 switch ((DeclSpec::TST)TagSpec) {
2410 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002411 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00002412 break;
2413
2414 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002415 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00002416 break;
2417
2418 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002419 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002420 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00002421 break;
2422
2423 default:
2424 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2425 return;
2426 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002427
John McCall0d6b1642010-04-23 18:46:30 +00002428 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002429 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002430
2431 // First pass: look for tags.
2432 Results.setFilter(Filter);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002433 LookupVisibleDecls(S, LookupTagName, Consumer);
John McCall0d6b1642010-04-23 18:46:30 +00002434
2435 // Second pass: look for nested name specifiers.
2436 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2437 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002438
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002439 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002440}
2441
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002442void Sema::CodeCompleteCase(Scope *S) {
2443 if (getSwitchStack().empty() || !CodeCompleter)
2444 return;
2445
2446 SwitchStmt *Switch = getSwitchStack().back();
2447 if (!Switch->getCond()->getType()->isEnumeralType())
2448 return;
2449
2450 // Code-complete the cases of a switch statement over an enumeration type
2451 // by providing the list of
2452 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2453
2454 // Determine which enumerators we have already seen in the switch statement.
2455 // FIXME: Ideally, we would also be able to look *past* the code-completion
2456 // token, in case we are code-completing in the middle of the switch and not
2457 // at the end. However, we aren't able to do so at the moment.
2458 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002459 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002460 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2461 SC = SC->getNextSwitchCase()) {
2462 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2463 if (!Case)
2464 continue;
2465
2466 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2467 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2468 if (EnumConstantDecl *Enumerator
2469 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2470 // We look into the AST of the case statement to determine which
2471 // enumerator was named. Alternatively, we could compute the value of
2472 // the integral constant expression, then compare it against the
2473 // values of each enumerator. However, value-based approach would not
2474 // work as well with C++ templates where enumerators declared within a
2475 // template are type- and value-dependent.
2476 EnumeratorsSeen.insert(Enumerator);
2477
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002478 // If this is a qualified-id, keep track of the nested-name-specifier
2479 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002480 //
2481 // switch (TagD.getKind()) {
2482 // case TagDecl::TK_enum:
2483 // break;
2484 // case XXX
2485 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002486 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002487 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2488 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002489 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002490 }
2491 }
2492
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002493 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2494 // If there are no prior enumerators in C++, check whether we have to
2495 // qualify the names of the enumerators that we suggest, because they
2496 // may not be visible in this scope.
2497 Qualifier = getRequiredQualification(Context, CurContext,
2498 Enum->getDeclContext());
2499
2500 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2501 }
2502
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002503 // Add any enumerators that have not yet been mentioned.
2504 ResultBuilder Results(*this);
2505 Results.EnterNewScope();
2506 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2507 EEnd = Enum->enumerator_end();
2508 E != EEnd; ++E) {
2509 if (EnumeratorsSeen.count(*E))
2510 continue;
2511
Douglas Gregor608300b2010-01-14 16:14:35 +00002512 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2513 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002514 }
2515 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002516
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002517 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002518 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002519 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002520}
2521
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002522namespace {
2523 struct IsBetterOverloadCandidate {
2524 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002525 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002526
2527 public:
John McCall5769d612010-02-08 23:07:23 +00002528 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2529 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002530
2531 bool
2532 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall5769d612010-02-08 23:07:23 +00002533 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002534 }
2535 };
2536}
2537
Douglas Gregord28dcd72010-05-30 06:10:08 +00002538static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2539 if (NumArgs && !Args)
2540 return true;
2541
2542 for (unsigned I = 0; I != NumArgs; ++I)
2543 if (!Args[I])
2544 return true;
2545
2546 return false;
2547}
2548
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002549void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2550 ExprTy **ArgsIn, unsigned NumArgs) {
2551 if (!CodeCompleter)
2552 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002553
2554 // When we're code-completing for a call, we fall back to ordinary
2555 // name code-completion whenever we can't produce specific
2556 // results. We may want to revisit this strategy in the future,
2557 // e.g., by merging the two kinds of results.
2558
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002559 Expr *Fn = (Expr *)FnIn;
2560 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002561
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002562 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002563 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002564 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00002565 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002566 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002567 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002568
John McCall3b4294e2009-12-16 12:17:52 +00002569 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002570 SourceLocation Loc = Fn->getExprLoc();
2571 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002572
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002573 // FIXME: What if we're calling something that isn't a function declaration?
2574 // FIXME: What if we're calling a pseudo-destructor?
2575 // FIXME: What if we're calling a member function?
2576
Douglas Gregorc0265402010-01-21 15:46:19 +00002577 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2578 llvm::SmallVector<ResultCandidate, 8> Results;
2579
John McCall3b4294e2009-12-16 12:17:52 +00002580 Expr *NakedFn = Fn->IgnoreParenCasts();
2581 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2582 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2583 /*PartialOverloading=*/ true);
2584 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2585 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002586 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00002587 if (!getLangOptions().CPlusPlus ||
2588 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00002589 Results.push_back(ResultCandidate(FDecl));
2590 else
John McCall86820f52010-01-26 01:37:31 +00002591 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00002592 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2593 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00002594 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00002595 }
John McCall3b4294e2009-12-16 12:17:52 +00002596 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002597
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002598 QualType ParamType;
2599
Douglas Gregorc0265402010-01-21 15:46:19 +00002600 if (!CandidateSet.empty()) {
2601 // Sort the overload candidate set by placing the best overloads first.
2602 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00002603 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002604
Douglas Gregorc0265402010-01-21 15:46:19 +00002605 // Add the remaining viable overload candidates as code-completion reslults.
2606 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2607 CandEnd = CandidateSet.end();
2608 Cand != CandEnd; ++Cand) {
2609 if (Cand->Viable)
2610 Results.push_back(ResultCandidate(Cand->Function));
2611 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002612
2613 // From the viable candidates, try to determine the type of this parameter.
2614 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2615 if (const FunctionType *FType = Results[I].getFunctionType())
2616 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2617 if (NumArgs < Proto->getNumArgs()) {
2618 if (ParamType.isNull())
2619 ParamType = Proto->getArgType(NumArgs);
2620 else if (!Context.hasSameUnqualifiedType(
2621 ParamType.getNonReferenceType(),
2622 Proto->getArgType(NumArgs).getNonReferenceType())) {
2623 ParamType = QualType();
2624 break;
2625 }
2626 }
2627 }
2628 } else {
2629 // Try to determine the parameter type from the type of the expression
2630 // being called.
2631 QualType FunctionType = Fn->getType();
2632 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2633 FunctionType = Ptr->getPointeeType();
2634 else if (const BlockPointerType *BlockPtr
2635 = FunctionType->getAs<BlockPointerType>())
2636 FunctionType = BlockPtr->getPointeeType();
2637 else if (const MemberPointerType *MemPtr
2638 = FunctionType->getAs<MemberPointerType>())
2639 FunctionType = MemPtr->getPointeeType();
2640
2641 if (const FunctionProtoType *Proto
2642 = FunctionType->getAs<FunctionProtoType>()) {
2643 if (NumArgs < Proto->getNumArgs())
2644 ParamType = Proto->getArgType(NumArgs);
2645 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002646 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002647
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002648 if (ParamType.isNull())
2649 CodeCompleteOrdinaryName(S, CCC_Expression);
2650 else
2651 CodeCompleteExpression(S, ParamType);
2652
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00002653 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00002654 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2655 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002656}
2657
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002658void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2659 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2660 if (!VD) {
2661 CodeCompleteOrdinaryName(S, CCC_Expression);
2662 return;
2663 }
2664
2665 CodeCompleteExpression(S, VD->getType());
2666}
2667
2668void Sema::CodeCompleteReturn(Scope *S) {
2669 QualType ResultType;
2670 if (isa<BlockDecl>(CurContext)) {
2671 if (BlockScopeInfo *BSI = getCurBlock())
2672 ResultType = BSI->ReturnType;
2673 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2674 ResultType = Function->getResultType();
2675 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2676 ResultType = Method->getResultType();
2677
2678 if (ResultType.isNull())
2679 CodeCompleteOrdinaryName(S, CCC_Expression);
2680 else
2681 CodeCompleteExpression(S, ResultType);
2682}
2683
2684void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2685 if (LHS)
2686 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2687 else
2688 CodeCompleteOrdinaryName(S, CCC_Expression);
2689}
2690
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002691void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002692 bool EnteringContext) {
2693 if (!SS.getScopeRep() || !CodeCompleter)
2694 return;
2695
Douglas Gregor86d9a522009-09-21 16:56:56 +00002696 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2697 if (!Ctx)
2698 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002699
2700 // Try to instantiate any non-dependent declaration contexts before
2701 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00002702 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002703 return;
2704
Douglas Gregor86d9a522009-09-21 16:56:56 +00002705 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00002706 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2707 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002708
2709 // The "template" keyword can follow "::" in the grammar, but only
2710 // put it into the grammar if the nested-name-specifier is dependent.
2711 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2712 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00002713 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002714
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002715 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002716}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002717
2718void Sema::CodeCompleteUsing(Scope *S) {
2719 if (!CodeCompleter)
2720 return;
2721
Douglas Gregor86d9a522009-09-21 16:56:56 +00002722 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002723 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002724
2725 // If we aren't in class scope, we could see the "namespace" keyword.
2726 if (!S->isClassScope())
Douglas Gregora4477812010-01-14 16:01:26 +00002727 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002728
2729 // After "using", we can see anything that would start a
2730 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002731 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2732 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002733 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002734
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002735 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002736}
2737
2738void Sema::CodeCompleteUsingDirective(Scope *S) {
2739 if (!CodeCompleter)
2740 return;
2741
Douglas Gregor86d9a522009-09-21 16:56:56 +00002742 // After "using namespace", we expect to see a namespace name or namespace
2743 // alias.
2744 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002745 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002746 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2747 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002748 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002749 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002750}
2751
2752void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2753 if (!CodeCompleter)
2754 return;
2755
Douglas Gregor86d9a522009-09-21 16:56:56 +00002756 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2757 DeclContext *Ctx = (DeclContext *)S->getEntity();
2758 if (!S->getParent())
2759 Ctx = Context.getTranslationUnitDecl();
2760
2761 if (Ctx && Ctx->isFileContext()) {
2762 // We only want to see those namespaces that have already been defined
2763 // within this scope, because its likely that the user is creating an
2764 // extended namespace declaration. Keep track of the most recent
2765 // definition of each namespace.
2766 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2767 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2768 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2769 NS != NSEnd; ++NS)
2770 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2771
2772 // Add the most recent definition (or extended definition) of each
2773 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002774 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002775 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2776 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2777 NS != NSEnd; ++NS)
Douglas Gregor608300b2010-01-14 16:14:35 +00002778 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2779 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002780 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002781 }
2782
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002783 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002784}
2785
2786void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2787 if (!CodeCompleter)
2788 return;
2789
Douglas Gregor86d9a522009-09-21 16:56:56 +00002790 // After "namespace", we expect to see a namespace or alias.
2791 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002792 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2793 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002794 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002795}
2796
Douglas Gregored8d3222009-09-18 20:05:18 +00002797void Sema::CodeCompleteOperatorName(Scope *S) {
2798 if (!CodeCompleter)
2799 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002800
2801 typedef CodeCompleteConsumer::Result Result;
2802 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002803 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00002804
Douglas Gregor86d9a522009-09-21 16:56:56 +00002805 // Add the names of overloadable operators.
2806#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2807 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00002808 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002809#include "clang/Basic/OperatorKinds.def"
2810
2811 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00002812 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002813 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2814 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002815
2816 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00002817 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002818 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002819
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002820 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00002821}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002822
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002823// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2824// true or false.
2825#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00002826static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002827 ResultBuilder &Results,
2828 bool NeedAt) {
2829 typedef CodeCompleteConsumer::Result Result;
2830 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002831 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002832
2833 CodeCompletionString *Pattern = 0;
2834 if (LangOpts.ObjC2) {
2835 // @dynamic
2836 Pattern = new CodeCompletionString;
2837 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2838 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2839 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002840 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002841
2842 // @synthesize
2843 Pattern = new CodeCompletionString;
2844 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2845 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2846 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002847 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002848 }
2849}
2850
Douglas Gregorbca403c2010-01-13 23:51:12 +00002851static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002852 ResultBuilder &Results,
2853 bool NeedAt) {
2854 typedef CodeCompleteConsumer::Result Result;
2855
2856 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002857 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002858
2859 if (LangOpts.ObjC2) {
2860 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00002861 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002862
2863 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00002864 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002865
2866 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00002867 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002868 }
2869}
2870
Douglas Gregorbca403c2010-01-13 23:51:12 +00002871static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002872 typedef CodeCompleteConsumer::Result Result;
2873 CodeCompletionString *Pattern = 0;
2874
2875 // @class name ;
2876 Pattern = new CodeCompletionString;
2877 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2878 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002879 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00002880 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002881
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002882 if (Results.includeCodePatterns()) {
2883 // @interface name
2884 // FIXME: Could introduce the whole pattern, including superclasses and
2885 // such.
2886 Pattern = new CodeCompletionString;
2887 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2888 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2889 Pattern->AddPlaceholderChunk("class");
2890 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002891
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002892 // @protocol name
2893 Pattern = new CodeCompletionString;
2894 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2895 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2896 Pattern->AddPlaceholderChunk("protocol");
2897 Results.AddResult(Result(Pattern));
2898
2899 // @implementation name
2900 Pattern = new CodeCompletionString;
2901 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2902 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2903 Pattern->AddPlaceholderChunk("class");
2904 Results.AddResult(Result(Pattern));
2905 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002906
2907 // @compatibility_alias name
2908 Pattern = new CodeCompletionString;
2909 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2910 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2911 Pattern->AddPlaceholderChunk("alias");
2912 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2913 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00002914 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002915}
2916
Douglas Gregorc464ae82009-12-07 09:27:33 +00002917void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2918 bool InInterface) {
2919 typedef CodeCompleteConsumer::Result Result;
2920 ResultBuilder Results(*this);
2921 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002922 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002923 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002924 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002925 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002926 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00002927 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002928 Results.ExitScope();
2929 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2930}
2931
Douglas Gregorbca403c2010-01-13 23:51:12 +00002932static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002933 typedef CodeCompleteConsumer::Result Result;
2934 CodeCompletionString *Pattern = 0;
2935
2936 // @encode ( type-name )
2937 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002938 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002939 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2940 Pattern->AddPlaceholderChunk("type-name");
2941 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002942 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002943
2944 // @protocol ( protocol-name )
2945 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002946 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002947 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2948 Pattern->AddPlaceholderChunk("protocol-name");
2949 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002950 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002951
2952 // @selector ( selector )
2953 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002954 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002955 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2956 Pattern->AddPlaceholderChunk("selector");
2957 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002958 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002959}
2960
Douglas Gregorbca403c2010-01-13 23:51:12 +00002961static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002962 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002963 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002964
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002965 if (Results.includeCodePatterns()) {
2966 // @try { statements } @catch ( declaration ) { statements } @finally
2967 // { statements }
2968 Pattern = new CodeCompletionString;
2969 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2970 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2971 Pattern->AddPlaceholderChunk("statements");
2972 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2973 Pattern->AddTextChunk("@catch");
2974 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2975 Pattern->AddPlaceholderChunk("parameter");
2976 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2977 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2978 Pattern->AddPlaceholderChunk("statements");
2979 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2980 Pattern->AddTextChunk("@finally");
2981 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2982 Pattern->AddPlaceholderChunk("statements");
2983 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2984 Results.AddResult(Result(Pattern));
2985 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002986
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002987 // @throw
2988 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002989 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00002990 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002991 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00002992 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002993
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002994 if (Results.includeCodePatterns()) {
2995 // @synchronized ( expression ) { statements }
2996 Pattern = new CodeCompletionString;
2997 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
2998 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2999 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3000 Pattern->AddPlaceholderChunk("expression");
3001 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3002 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3003 Pattern->AddPlaceholderChunk("statements");
3004 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3005 Results.AddResult(Result(Pattern));
3006 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003007}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003008
Douglas Gregorbca403c2010-01-13 23:51:12 +00003009static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003010 ResultBuilder &Results,
3011 bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003012 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003013 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3014 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3015 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003016 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003017 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003018}
3019
3020void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3021 ResultBuilder Results(*this);
3022 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003023 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003024 Results.ExitScope();
3025 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3026}
3027
3028void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003029 ResultBuilder Results(*this);
3030 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003031 AddObjCStatementResults(Results, false);
3032 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003033 Results.ExitScope();
3034 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3035}
3036
3037void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3038 ResultBuilder Results(*this);
3039 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003040 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003041 Results.ExitScope();
3042 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3043}
3044
Douglas Gregor988358f2009-11-19 00:14:45 +00003045/// \brief Determine whether the addition of the given flag to an Objective-C
3046/// property's attributes will cause a conflict.
3047static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3048 // Check if we've already added this flag.
3049 if (Attributes & NewFlag)
3050 return true;
3051
3052 Attributes |= NewFlag;
3053
3054 // Check for collisions with "readonly".
3055 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3056 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3057 ObjCDeclSpec::DQ_PR_assign |
3058 ObjCDeclSpec::DQ_PR_copy |
3059 ObjCDeclSpec::DQ_PR_retain)))
3060 return true;
3061
3062 // Check for more than one of { assign, copy, retain }.
3063 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3064 ObjCDeclSpec::DQ_PR_copy |
3065 ObjCDeclSpec::DQ_PR_retain);
3066 if (AssignCopyRetMask &&
3067 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3068 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3069 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3070 return true;
3071
3072 return false;
3073}
3074
Douglas Gregora93b1082009-11-18 23:08:07 +00003075void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003076 if (!CodeCompleter)
3077 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003078
Steve Naroffece8e712009-10-08 21:55:05 +00003079 unsigned Attributes = ODS.getPropertyAttributes();
3080
3081 typedef CodeCompleteConsumer::Result Result;
3082 ResultBuilder Results(*this);
3083 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003084 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregora4477812010-01-14 16:01:26 +00003085 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003086 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregora4477812010-01-14 16:01:26 +00003087 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003088 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregora4477812010-01-14 16:01:26 +00003089 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003090 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregora4477812010-01-14 16:01:26 +00003091 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003092 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregora4477812010-01-14 16:01:26 +00003093 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003094 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregora4477812010-01-14 16:01:26 +00003095 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003096 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003097 CodeCompletionString *Setter = new CodeCompletionString;
3098 Setter->AddTypedTextChunk("setter");
3099 Setter->AddTextChunk(" = ");
3100 Setter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003101 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003102 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003103 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003104 CodeCompletionString *Getter = new CodeCompletionString;
3105 Getter->AddTypedTextChunk("getter");
3106 Getter->AddTextChunk(" = ");
3107 Getter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003108 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003109 }
Steve Naroffece8e712009-10-08 21:55:05 +00003110 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003111 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003112}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003113
Douglas Gregor4ad96852009-11-19 07:41:15 +00003114/// \brief Descripts the kind of Objective-C method that we want to find
3115/// via code completion.
3116enum ObjCMethodKind {
3117 MK_Any, //< Any kind of method, provided it means other specified criteria.
3118 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3119 MK_OneArgSelector //< One-argument selector.
3120};
3121
3122static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3123 ObjCMethodKind WantKind,
3124 IdentifierInfo **SelIdents,
3125 unsigned NumSelIdents) {
3126 Selector Sel = Method->getSelector();
3127 if (NumSelIdents > Sel.getNumArgs())
3128 return false;
3129
3130 switch (WantKind) {
3131 case MK_Any: break;
3132 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3133 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3134 }
3135
3136 for (unsigned I = 0; I != NumSelIdents; ++I)
3137 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3138 return false;
3139
3140 return true;
3141}
3142
Douglas Gregor36ecb042009-11-17 23:22:23 +00003143/// \brief Add all of the Objective-C methods in the given Objective-C
3144/// container to the set of results.
3145///
3146/// The container will be a class, protocol, category, or implementation of
3147/// any of the above. This mether will recurse to include methods from
3148/// the superclasses of classes along with their categories, protocols, and
3149/// implementations.
3150///
3151/// \param Container the container in which we'll look to find methods.
3152///
3153/// \param WantInstance whether to add instance methods (only); if false, this
3154/// routine will add factory methods (only).
3155///
3156/// \param CurContext the context in which we're performing the lookup that
3157/// finds methods.
3158///
3159/// \param Results the structure into which we'll add results.
3160static void AddObjCMethods(ObjCContainerDecl *Container,
3161 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003162 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003163 IdentifierInfo **SelIdents,
3164 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003165 DeclContext *CurContext,
3166 ResultBuilder &Results) {
3167 typedef CodeCompleteConsumer::Result Result;
3168 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3169 MEnd = Container->meth_end();
3170 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003171 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3172 // Check whether the selector identifiers we've been given are a
3173 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003174 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003175 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003176
Douglas Gregord3c68542009-11-19 01:08:35 +00003177 Result R = Result(*M, 0);
3178 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003179 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00003180 Results.MaybeAddResult(R, CurContext);
3181 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003182 }
3183
3184 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3185 if (!IFace)
3186 return;
3187
3188 // Add methods in protocols.
3189 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3190 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3191 E = Protocols.end();
3192 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003193 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00003194 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003195
3196 // Add methods in categories.
3197 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3198 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003199 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3200 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003201
3202 // Add a categories protocol methods.
3203 const ObjCList<ObjCProtocolDecl> &Protocols
3204 = CatDecl->getReferencedProtocols();
3205 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3206 E = Protocols.end();
3207 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003208 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3209 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003210
3211 // Add methods in category implementations.
3212 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003213 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3214 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003215 }
3216
3217 // Add methods in superclass.
3218 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003219 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3220 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003221
3222 // Add methods in our implementation, if any.
3223 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003224 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3225 NumSelIdents, CurContext, Results);
3226}
3227
3228
3229void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3230 DeclPtrTy *Methods,
3231 unsigned NumMethods) {
3232 typedef CodeCompleteConsumer::Result Result;
3233
3234 // Try to find the interface where getters might live.
3235 ObjCInterfaceDecl *Class
3236 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3237 if (!Class) {
3238 if (ObjCCategoryDecl *Category
3239 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3240 Class = Category->getClassInterface();
3241
3242 if (!Class)
3243 return;
3244 }
3245
3246 // Find all of the potential getters.
3247 ResultBuilder Results(*this);
3248 Results.EnterNewScope();
3249
3250 // FIXME: We need to do this because Objective-C methods don't get
3251 // pushed into DeclContexts early enough. Argh!
3252 for (unsigned I = 0; I != NumMethods; ++I) {
3253 if (ObjCMethodDecl *Method
3254 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3255 if (Method->isInstanceMethod() &&
3256 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3257 Result R = Result(Method, 0);
3258 R.AllParametersAreInformative = true;
3259 Results.MaybeAddResult(R, CurContext);
3260 }
3261 }
3262
3263 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3264 Results.ExitScope();
3265 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3266}
3267
3268void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3269 DeclPtrTy *Methods,
3270 unsigned NumMethods) {
3271 typedef CodeCompleteConsumer::Result Result;
3272
3273 // Try to find the interface where setters might live.
3274 ObjCInterfaceDecl *Class
3275 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3276 if (!Class) {
3277 if (ObjCCategoryDecl *Category
3278 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3279 Class = Category->getClassInterface();
3280
3281 if (!Class)
3282 return;
3283 }
3284
3285 // Find all of the potential getters.
3286 ResultBuilder Results(*this);
3287 Results.EnterNewScope();
3288
3289 // FIXME: We need to do this because Objective-C methods don't get
3290 // pushed into DeclContexts early enough. Argh!
3291 for (unsigned I = 0; I != NumMethods; ++I) {
3292 if (ObjCMethodDecl *Method
3293 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3294 if (Method->isInstanceMethod() &&
3295 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3296 Result R = Result(Method, 0);
3297 R.AllParametersAreInformative = true;
3298 Results.MaybeAddResult(R, CurContext);
3299 }
3300 }
3301
3302 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3303
3304 Results.ExitScope();
3305 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003306}
3307
Douglas Gregor22f56992010-04-06 19:22:33 +00003308/// \brief When we have an expression with type "id", we may assume
3309/// that it has some more-specific class type based on knowledge of
3310/// common uses of Objective-C. This routine returns that class type,
3311/// or NULL if no better result could be determined.
3312static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3313 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3314 if (!Msg)
3315 return 0;
3316
3317 Selector Sel = Msg->getSelector();
3318 if (Sel.isNull())
3319 return 0;
3320
3321 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3322 if (!Id)
3323 return 0;
3324
3325 ObjCMethodDecl *Method = Msg->getMethodDecl();
3326 if (!Method)
3327 return 0;
3328
3329 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003330 ObjCInterfaceDecl *IFace = 0;
3331 switch (Msg->getReceiverKind()) {
3332 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003333 if (const ObjCObjectType *ObjType
3334 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3335 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003336 break;
3337
3338 case ObjCMessageExpr::Instance: {
3339 QualType T = Msg->getInstanceReceiver()->getType();
3340 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3341 IFace = Ptr->getInterfaceDecl();
3342 break;
3343 }
3344
3345 case ObjCMessageExpr::SuperInstance:
3346 case ObjCMessageExpr::SuperClass:
3347 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003348 }
3349
3350 if (!IFace)
3351 return 0;
3352
3353 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3354 if (Method->isInstanceMethod())
3355 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3356 .Case("retain", IFace)
3357 .Case("autorelease", IFace)
3358 .Case("copy", IFace)
3359 .Case("copyWithZone", IFace)
3360 .Case("mutableCopy", IFace)
3361 .Case("mutableCopyWithZone", IFace)
3362 .Case("awakeFromCoder", IFace)
3363 .Case("replacementObjectFromCoder", IFace)
3364 .Case("class", IFace)
3365 .Case("classForCoder", IFace)
3366 .Case("superclass", Super)
3367 .Default(0);
3368
3369 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3370 .Case("new", IFace)
3371 .Case("alloc", IFace)
3372 .Case("allocWithZone", IFace)
3373 .Case("class", IFace)
3374 .Case("superclass", Super)
3375 .Default(0);
3376}
3377
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003378void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3379 typedef CodeCompleteConsumer::Result Result;
3380 ResultBuilder Results(*this);
3381
3382 // Find anything that looks like it could be a message receiver.
3383 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3384 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3385 Results.EnterNewScope();
3386 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
3387
3388 // If we are in an Objective-C method inside a class that has a superclass,
3389 // add "super" as an option.
3390 if (ObjCMethodDecl *Method = getCurMethodDecl())
3391 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3392 if (Iface->getSuperClass())
3393 Results.AddResult(Result("super"));
3394
3395 Results.ExitScope();
3396
3397 if (CodeCompleter->includeMacros())
3398 AddMacroResults(PP, Results);
3399 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3400
3401}
3402
Douglas Gregor2725ca82010-04-21 19:57:20 +00003403void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3404 IdentifierInfo **SelIdents,
3405 unsigned NumSelIdents) {
3406 ObjCInterfaceDecl *CDecl = 0;
3407 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3408 // Figure out which interface we're in.
3409 CDecl = CurMethod->getClassInterface();
3410 if (!CDecl)
3411 return;
3412
3413 // Find the superclass of this class.
3414 CDecl = CDecl->getSuperClass();
3415 if (!CDecl)
3416 return;
3417
3418 if (CurMethod->isInstanceMethod()) {
3419 // We are inside an instance method, which means that the message
3420 // send [super ...] is actually calling an instance method on the
3421 // current object. Build the super expression and handle this like
3422 // an instance method.
3423 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3424 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3425 OwningExprResult Super
3426 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3427 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3428 SelIdents, NumSelIdents);
3429 }
3430
3431 // Fall through to send to the superclass in CDecl.
3432 } else {
3433 // "super" may be the name of a type or variable. Figure out which
3434 // it is.
3435 IdentifierInfo *Super = &Context.Idents.get("super");
3436 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3437 LookupOrdinaryName);
3438 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3439 // "super" names an interface. Use it.
3440 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00003441 if (const ObjCObjectType *Iface
3442 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3443 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00003444 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3445 // "super" names an unresolved type; we can't be more specific.
3446 } else {
3447 // Assume that "super" names some kind of value and parse that way.
3448 CXXScopeSpec SS;
3449 UnqualifiedId id;
3450 id.setIdentifier(Super, SuperLoc);
3451 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3452 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3453 SelIdents, NumSelIdents);
3454 }
3455
3456 // Fall through
3457 }
3458
3459 TypeTy *Receiver = 0;
3460 if (CDecl)
3461 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3462 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3463 NumSelIdents);
3464}
3465
3466void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00003467 IdentifierInfo **SelIdents,
3468 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003469 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00003470 ObjCInterfaceDecl *CDecl = 0;
3471
Douglas Gregor24a069f2009-11-17 17:59:40 +00003472 // If the given name refers to an interface type, retrieve the
3473 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00003474 if (Receiver) {
3475 QualType T = GetTypeFromParser(Receiver, 0);
3476 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00003477 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3478 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00003479 }
3480
Douglas Gregor36ecb042009-11-17 23:22:23 +00003481 // Add all of the factory methods in this Objective-C class, its protocols,
3482 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00003483 ResultBuilder Results(*this);
3484 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00003485
3486 if (CDecl)
3487 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3488 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003489 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00003490 // We're messaging "id" as a type; provide all class/factory methods.
3491
Douglas Gregor719770d2010-04-06 17:30:22 +00003492 // If we have an external source, load the entire class method
3493 // pool from the PCH file.
3494 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003495 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3496 I != N; ++I) {
3497 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregor719770d2010-04-06 17:30:22 +00003498 if (Sel.isNull() || FactoryMethodPool.count(Sel) ||
3499 InstanceMethodPool.count(Sel))
3500 continue;
3501
3502 ReadMethodPool(Sel, /*isInstance=*/false);
3503 }
3504 }
3505
Douglas Gregor13438f92010-04-06 16:40:00 +00003506 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3507 M = FactoryMethodPool.begin(),
3508 MEnd = FactoryMethodPool.end();
3509 M != MEnd;
3510 ++M) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003511 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003512 MethList = MethList->Next) {
3513 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3514 NumSelIdents))
3515 continue;
3516
3517 Result R(MethList->Method, 0);
3518 R.StartParameter = NumSelIdents;
3519 R.AllParametersAreInformative = false;
3520 Results.MaybeAddResult(R, CurContext);
3521 }
3522 }
3523 }
3524
Steve Naroffc4df6d22009-11-07 02:08:14 +00003525 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003526 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003527}
3528
Douglas Gregord3c68542009-11-19 01:08:35 +00003529void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3530 IdentifierInfo **SelIdents,
3531 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003532 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00003533
3534 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00003535
Douglas Gregor36ecb042009-11-17 23:22:23 +00003536 // If necessary, apply function/array conversion to the receiver.
3537 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00003538 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003539 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00003540
Douglas Gregor36ecb042009-11-17 23:22:23 +00003541 // Build the set of methods we can see.
3542 ResultBuilder Results(*this);
3543 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00003544
3545 // If we're messaging an expression with type "id" or "Class", check
3546 // whether we know something special about the receiver that allows
3547 // us to assume a more-specific receiver type.
3548 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3549 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3550 ReceiverType = Context.getObjCObjectPointerType(
3551 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00003552
Douglas Gregorf74a4192009-11-18 00:06:18 +00003553 // Handle messages to Class. This really isn't a message to an instance
3554 // method, so we treat it the same way we would treat a message send to a
3555 // class method.
3556 if (ReceiverType->isObjCClassType() ||
3557 ReceiverType->isObjCQualifiedClassType()) {
3558 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3559 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003560 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3561 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003562 }
3563 }
3564 // Handle messages to a qualified ID ("id<foo>").
3565 else if (const ObjCObjectPointerType *QualID
3566 = ReceiverType->getAsObjCQualifiedIdType()) {
3567 // Search protocols for instance methods.
3568 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3569 E = QualID->qual_end();
3570 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003571 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3572 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003573 }
3574 // Handle messages to a pointer to interface type.
3575 else if (const ObjCObjectPointerType *IFacePtr
3576 = ReceiverType->getAsObjCInterfacePointerType()) {
3577 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003578 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3579 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003580
3581 // Search protocols for instance methods.
3582 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3583 E = IFacePtr->qual_end();
3584 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003585 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3586 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003587 }
Douglas Gregor13438f92010-04-06 16:40:00 +00003588 // Handle messages to "id".
3589 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003590 // We're messaging "id", so provide all instance methods we know
3591 // about as code-completion results.
3592
3593 // If we have an external source, load the entire class method
3594 // pool from the PCH file.
3595 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003596 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3597 I != N; ++I) {
3598 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregor719770d2010-04-06 17:30:22 +00003599 if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
3600 FactoryMethodPool.count(Sel))
3601 continue;
3602
3603 ReadMethodPool(Sel, /*isInstance=*/true);
3604 }
3605 }
3606
Douglas Gregor13438f92010-04-06 16:40:00 +00003607 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3608 M = InstanceMethodPool.begin(),
3609 MEnd = InstanceMethodPool.end();
3610 M != MEnd;
3611 ++M) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003612 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003613 MethList = MethList->Next) {
3614 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3615 NumSelIdents))
3616 continue;
3617
3618 Result R(MethList->Method, 0);
3619 R.StartParameter = NumSelIdents;
3620 R.AllParametersAreInformative = false;
3621 Results.MaybeAddResult(R, CurContext);
3622 }
3623 }
3624 }
3625
Steve Naroffc4df6d22009-11-07 02:08:14 +00003626 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003627 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003628}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003629
3630/// \brief Add all of the protocol declarations that we find in the given
3631/// (translation unit) context.
3632static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00003633 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00003634 ResultBuilder &Results) {
3635 typedef CodeCompleteConsumer::Result Result;
3636
3637 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3638 DEnd = Ctx->decls_end();
3639 D != DEnd; ++D) {
3640 // Record any protocols we find.
3641 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00003642 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003643 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003644
3645 // Record any forward-declared protocols we find.
3646 if (ObjCForwardProtocolDecl *Forward
3647 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3648 for (ObjCForwardProtocolDecl::protocol_iterator
3649 P = Forward->protocol_begin(),
3650 PEnd = Forward->protocol_end();
3651 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00003652 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003653 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003654 }
3655 }
3656}
3657
3658void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3659 unsigned NumProtocols) {
3660 ResultBuilder Results(*this);
3661 Results.EnterNewScope();
3662
3663 // Tell the result set to ignore all of the protocols we have
3664 // already seen.
3665 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003666 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3667 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00003668 Results.Ignore(Protocol);
3669
3670 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00003671 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3672 Results);
3673
3674 Results.ExitScope();
3675 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3676}
3677
3678void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3679 ResultBuilder Results(*this);
3680 Results.EnterNewScope();
3681
3682 // Add all protocols.
3683 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3684 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003685
3686 Results.ExitScope();
3687 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3688}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003689
3690/// \brief Add all of the Objective-C interface declarations that we find in
3691/// the given (translation unit) context.
3692static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3693 bool OnlyForwardDeclarations,
3694 bool OnlyUnimplemented,
3695 ResultBuilder &Results) {
3696 typedef CodeCompleteConsumer::Result Result;
3697
3698 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3699 DEnd = Ctx->decls_end();
3700 D != DEnd; ++D) {
3701 // Record any interfaces we find.
3702 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3703 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3704 (!OnlyUnimplemented || !Class->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003705 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003706
3707 // Record any forward-declared interfaces we find.
3708 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3709 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3710 C != CEnd; ++C)
3711 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3712 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003713 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3714 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003715 }
3716 }
3717}
3718
3719void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3720 ResultBuilder Results(*this);
3721 Results.EnterNewScope();
3722
3723 // Add all classes.
3724 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3725 false, Results);
3726
3727 Results.ExitScope();
3728 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3729}
3730
Douglas Gregorc83c6872010-04-15 22:33:43 +00003731void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3732 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003733 ResultBuilder Results(*this);
3734 Results.EnterNewScope();
3735
3736 // Make sure that we ignore the class we're currently defining.
3737 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003738 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003739 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003740 Results.Ignore(CurClass);
3741
3742 // Add all classes.
3743 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3744 false, Results);
3745
3746 Results.ExitScope();
3747 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3748}
3749
3750void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3751 ResultBuilder Results(*this);
3752 Results.EnterNewScope();
3753
3754 // Add all unimplemented classes.
3755 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3756 true, Results);
3757
3758 Results.ExitScope();
3759 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3760}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003761
3762void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003763 IdentifierInfo *ClassName,
3764 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003765 typedef CodeCompleteConsumer::Result Result;
3766
3767 ResultBuilder Results(*this);
3768
3769 // Ignore any categories we find that have already been implemented by this
3770 // interface.
3771 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3772 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003773 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003774 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3775 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3776 Category = Category->getNextClassCategory())
3777 CategoryNames.insert(Category->getIdentifier());
3778
3779 // Add all of the categories we know about.
3780 Results.EnterNewScope();
3781 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3782 for (DeclContext::decl_iterator D = TU->decls_begin(),
3783 DEnd = TU->decls_end();
3784 D != DEnd; ++D)
3785 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3786 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003787 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003788 Results.ExitScope();
3789
3790 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3791}
3792
3793void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003794 IdentifierInfo *ClassName,
3795 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003796 typedef CodeCompleteConsumer::Result Result;
3797
3798 // Find the corresponding interface. If we couldn't find the interface, the
3799 // program itself is ill-formed. However, we'll try to be helpful still by
3800 // providing the list of all of the categories we know about.
3801 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003802 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003803 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3804 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003805 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003806
3807 ResultBuilder Results(*this);
3808
3809 // Add all of the categories that have have corresponding interface
3810 // declarations in this class and any of its superclasses, except for
3811 // already-implemented categories in the class itself.
3812 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3813 Results.EnterNewScope();
3814 bool IgnoreImplemented = true;
3815 while (Class) {
3816 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3817 Category = Category->getNextClassCategory())
3818 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3819 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003820 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003821
3822 Class = Class->getSuperClass();
3823 IgnoreImplemented = false;
3824 }
3825 Results.ExitScope();
3826
3827 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3828}
Douglas Gregor322328b2009-11-18 22:32:06 +00003829
Douglas Gregor424b2a52009-11-18 22:56:13 +00003830void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00003831 typedef CodeCompleteConsumer::Result Result;
3832 ResultBuilder Results(*this);
3833
3834 // Figure out where this @synthesize lives.
3835 ObjCContainerDecl *Container
3836 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3837 if (!Container ||
3838 (!isa<ObjCImplementationDecl>(Container) &&
3839 !isa<ObjCCategoryImplDecl>(Container)))
3840 return;
3841
3842 // Ignore any properties that have already been implemented.
3843 for (DeclContext::decl_iterator D = Container->decls_begin(),
3844 DEnd = Container->decls_end();
3845 D != DEnd; ++D)
3846 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3847 Results.Ignore(PropertyImpl->getPropertyDecl());
3848
3849 // Add any properties that we find.
3850 Results.EnterNewScope();
3851 if (ObjCImplementationDecl *ClassImpl
3852 = dyn_cast<ObjCImplementationDecl>(Container))
3853 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3854 Results);
3855 else
3856 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3857 false, CurContext, Results);
3858 Results.ExitScope();
3859
3860 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3861}
3862
3863void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3864 IdentifierInfo *PropertyName,
3865 DeclPtrTy ObjCImpDecl) {
3866 typedef CodeCompleteConsumer::Result Result;
3867 ResultBuilder Results(*this);
3868
3869 // Figure out where this @synthesize lives.
3870 ObjCContainerDecl *Container
3871 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3872 if (!Container ||
3873 (!isa<ObjCImplementationDecl>(Container) &&
3874 !isa<ObjCCategoryImplDecl>(Container)))
3875 return;
3876
3877 // Figure out which interface we're looking into.
3878 ObjCInterfaceDecl *Class = 0;
3879 if (ObjCImplementationDecl *ClassImpl
3880 = dyn_cast<ObjCImplementationDecl>(Container))
3881 Class = ClassImpl->getClassInterface();
3882 else
3883 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3884 ->getClassInterface();
3885
3886 // Add all of the instance variables in this class and its superclasses.
3887 Results.EnterNewScope();
3888 for(; Class; Class = Class->getSuperClass()) {
3889 // FIXME: We could screen the type of each ivar for compatibility with
3890 // the property, but is that being too paternal?
3891 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3892 IVarEnd = Class->ivar_end();
3893 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00003894 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00003895 }
3896 Results.ExitScope();
3897
3898 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3899}
Douglas Gregore8f5a172010-04-07 00:21:17 +00003900
3901typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
3902
3903/// \brief Find all of the methods that reside in the given container
3904/// (and its superclasses, protocols, etc.) that meet the given
3905/// criteria. Insert those methods into the map of known methods,
3906/// indexed by selector so they can be easily found.
3907static void FindImplementableMethods(ASTContext &Context,
3908 ObjCContainerDecl *Container,
3909 bool WantInstanceMethods,
3910 QualType ReturnType,
3911 bool IsInImplementation,
3912 KnownMethodsMap &KnownMethods) {
3913 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
3914 // Recurse into protocols.
3915 const ObjCList<ObjCProtocolDecl> &Protocols
3916 = IFace->getReferencedProtocols();
3917 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3918 E = Protocols.end();
3919 I != E; ++I)
3920 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3921 IsInImplementation, KnownMethods);
3922
3923 // If we're not in the implementation of a class, also visit the
3924 // superclass.
3925 if (!IsInImplementation && IFace->getSuperClass())
3926 FindImplementableMethods(Context, IFace->getSuperClass(),
3927 WantInstanceMethods, ReturnType,
3928 IsInImplementation, KnownMethods);
3929
3930 // Add methods from any class extensions (but not from categories;
3931 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00003932 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
3933 Cat = Cat->getNextClassExtension())
3934 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
3935 WantInstanceMethods, ReturnType,
Douglas Gregore8f5a172010-04-07 00:21:17 +00003936 IsInImplementation, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00003937 }
3938
3939 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
3940 // Recurse into protocols.
3941 const ObjCList<ObjCProtocolDecl> &Protocols
3942 = Category->getReferencedProtocols();
3943 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3944 E = Protocols.end();
3945 I != E; ++I)
3946 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3947 IsInImplementation, KnownMethods);
3948 }
3949
3950 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3951 // Recurse into protocols.
3952 const ObjCList<ObjCProtocolDecl> &Protocols
3953 = Protocol->getReferencedProtocols();
3954 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3955 E = Protocols.end();
3956 I != E; ++I)
3957 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3958 IsInImplementation, KnownMethods);
3959 }
3960
3961 // Add methods in this container. This operation occurs last because
3962 // we want the methods from this container to override any methods
3963 // we've previously seen with the same selector.
3964 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3965 MEnd = Container->meth_end();
3966 M != MEnd; ++M) {
3967 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3968 if (!ReturnType.isNull() &&
3969 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
3970 continue;
3971
3972 KnownMethods[(*M)->getSelector()] = *M;
3973 }
3974 }
3975}
3976
3977void Sema::CodeCompleteObjCMethodDecl(Scope *S,
3978 bool IsInstanceMethod,
3979 TypeTy *ReturnTy,
3980 DeclPtrTy IDecl) {
3981 // Determine the return type of the method we're declaring, if
3982 // provided.
3983 QualType ReturnType = GetTypeFromParser(ReturnTy);
3984
3985 // Determine where we should start searching for methods, and where we
3986 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
3987 bool IsInImplementation = false;
3988 if (Decl *D = IDecl.getAs<Decl>()) {
3989 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
3990 SearchDecl = Impl->getClassInterface();
3991 CurrentDecl = Impl;
3992 IsInImplementation = true;
3993 } else if (ObjCCategoryImplDecl *CatImpl
3994 = dyn_cast<ObjCCategoryImplDecl>(D)) {
3995 SearchDecl = CatImpl->getCategoryDecl();
3996 CurrentDecl = CatImpl;
3997 IsInImplementation = true;
3998 } else {
3999 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4000 CurrentDecl = SearchDecl;
4001 }
4002 }
4003
4004 if (!SearchDecl && S) {
4005 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4006 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4007 CurrentDecl = SearchDecl;
4008 }
4009 }
4010
4011 if (!SearchDecl || !CurrentDecl) {
4012 HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
4013 return;
4014 }
4015
4016 // Find all of the methods that we could declare/implement here.
4017 KnownMethodsMap KnownMethods;
4018 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4019 ReturnType, IsInImplementation, KnownMethods);
4020
4021 // Erase any methods that have already been declared or
4022 // implemented here.
4023 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4024 MEnd = CurrentDecl->meth_end();
4025 M != MEnd; ++M) {
4026 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4027 continue;
4028
4029 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4030 if (Pos != KnownMethods.end())
4031 KnownMethods.erase(Pos);
4032 }
4033
4034 // Add declarations or definitions for each of the known methods.
4035 typedef CodeCompleteConsumer::Result Result;
4036 ResultBuilder Results(*this);
4037 Results.EnterNewScope();
4038 PrintingPolicy Policy(Context.PrintingPolicy);
4039 Policy.AnonymousTagLocations = false;
4040 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4041 MEnd = KnownMethods.end();
4042 M != MEnd; ++M) {
4043 ObjCMethodDecl *Method = M->second;
4044 CodeCompletionString *Pattern = new CodeCompletionString;
4045
4046 // If the result type was not already provided, add it to the
4047 // pattern as (type).
4048 if (ReturnType.isNull()) {
4049 std::string TypeStr;
4050 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4051 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4052 Pattern->AddTextChunk(TypeStr);
4053 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4054 }
4055
4056 Selector Sel = Method->getSelector();
4057
4058 // Add the first part of the selector to the pattern.
4059 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4060
4061 // Add parameters to the pattern.
4062 unsigned I = 0;
4063 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4064 PEnd = Method->param_end();
4065 P != PEnd; (void)++P, ++I) {
4066 // Add the part of the selector name.
4067 if (I == 0)
4068 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4069 else if (I < Sel.getNumArgs()) {
4070 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4071 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4072 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4073 } else
4074 break;
4075
4076 // Add the parameter type.
4077 std::string TypeStr;
4078 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4079 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4080 Pattern->AddTextChunk(TypeStr);
4081 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4082
4083 if (IdentifierInfo *Id = (*P)->getIdentifier())
4084 Pattern->AddTextChunk(Id->getName());
4085 }
4086
4087 if (Method->isVariadic()) {
4088 if (Method->param_size() > 0)
4089 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4090 Pattern->AddTextChunk("...");
4091 }
4092
Douglas Gregor447107d2010-05-28 00:57:46 +00004093 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004094 // We will be defining the method here, so add a compound statement.
4095 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4096 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4097 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4098 if (!Method->getResultType()->isVoidType()) {
4099 // If the result type is not void, add a return clause.
4100 Pattern->AddTextChunk("return");
4101 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4102 Pattern->AddPlaceholderChunk("expression");
4103 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4104 } else
4105 Pattern->AddPlaceholderChunk("statements");
4106
4107 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4108 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4109 }
4110
4111 Results.AddResult(Result(Pattern));
4112 }
4113
4114 Results.ExitScope();
4115
4116 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4117}