blob: 0b30da5d854f2c9dfaddd439449f5c2cffed60d5 [file] [log] [blame]
Douglas Gregor2436e712009-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 Gregorc580c522010-01-14 01:09:38 +000014#include "Lookup.h"
Douglas Gregor2436e712009-09-17 21:32:03 +000015#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregord720daf2010-04-06 17:30:22 +000016#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000023#include "llvm/ADT/StringSwitch.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000024#include <list>
25#include <map>
26#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000027
28using namespace clang;
29
Douglas Gregor3545ff42009-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 Gregor05e7ca32009-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 Gregor3545ff42009-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 Gregor05e7ca32009-12-06 20:23:50 +0000108 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-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 Gregor6ae4c522010-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 Gregor7aa6b222010-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 Gregor3545ff42009-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 Gregor6ae4c522010-01-14 03:21:49 +0000135 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000136
Douglas Gregorf64acca2010-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 Gregor3545ff42009-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 Gregor7aa6b222010-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 Gregor6ae4c522010-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 Gregor7c208612010-01-14 00:20:49 +0000167 /// \brief Determine whether the given declaration is at all interesting
168 /// as a code-completion result.
Douglas Gregor6ae4c522010-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 Gregore0717ab2010-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 Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000188 ///
Douglas Gregorc580c522010-01-14 01:09:38 +0000189 /// \param CurContext the result to add (if it is unique).
Douglas Gregor2af2f672009-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 Gregor3545ff42009-09-21 16:56:56 +0000193
Douglas Gregorc580c522010-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 Gregor09bbc652010-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 Gregorc580c522010-01-14 01:09:38 +0000207
Douglas Gregor78a21012010-01-14 16:01:26 +0000208 /// \brief Add a new non-declaration result to this result set.
209 void AddResult(Result R);
210
Douglas Gregor3545ff42009-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 Gregorbaf69612009-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 Gregor3545ff42009-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 Gregor9d64c5e2009-09-21 20:51:25 +0000226 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor70febae2010-05-28 00:49:12 +0000227 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000228 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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 Gregore412a5a2009-09-23 22:26:46 +0000236 bool IsMember(NamedDecl *ND) const;
Douglas Gregor2b8162b2010-01-14 16:08:12 +0000237 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregora817a192010-05-27 23:06:34 +0000238 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000239 //@}
240 };
241}
242
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000295 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000303 return X.DeclOrIterator.getOpaqueValue()
304 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000305 X.SingleDeclIndex == Y.SingleDeclIndex;
306 }
307
308 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000309 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000310 }
311};
312
Douglas Gregor05e7ca32009-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 Gregor2af2f672009-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());
372 else
373 assert(Parent->isTranslationUnit());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000374 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000375 return Result;
376}
377
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000378bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
379 bool &AsNestedNameSpecifier) const {
380 AsNestedNameSpecifier = false;
381
Douglas Gregor7c208612010-01-14 00:20:49 +0000382 ND = ND->getUnderlyingDecl();
383 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregor58acf322009-10-09 22:16:47 +0000384
385 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000386 if (!ND->getDeclName())
387 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000388
389 // Friend declarations and declarations introduced due to friends are never
390 // added as results.
John McCallbbbbe4e2010-03-11 07:50:04 +0000391 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregor7c208612010-01-14 00:20:49 +0000392 return false;
393
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000394 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000395 if (isa<ClassTemplateSpecializationDecl>(ND) ||
396 isa<ClassTemplatePartialSpecializationDecl>(ND))
397 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000398
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000399 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000400 if (isa<UsingDecl>(ND))
401 return false;
402
403 // Some declarations have reserved names that we don't want to ever show.
404 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000405 // __va_list_tag is a freak of nature. Find it and skip it.
406 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregor7c208612010-01-14 00:20:49 +0000407 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000408
Douglas Gregor58acf322009-10-09 22:16:47 +0000409 // Filter out names reserved for the implementation (C99 7.1.3,
410 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000411 //
412 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000413 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000414 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000415 if (Name[0] == '_' &&
416 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
Douglas Gregor7c208612010-01-14 00:20:49 +0000417 return false;
Douglas Gregor58acf322009-10-09 22:16:47 +0000418 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000419 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000420
Douglas Gregor3545ff42009-09-21 16:56:56 +0000421 // C++ constructors are never found by name lookup.
Douglas Gregor7c208612010-01-14 00:20:49 +0000422 if (isa<CXXConstructorDecl>(ND))
423 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000424
425 // Filter out any unwanted results.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000426 if (Filter && !(this->*Filter)(ND)) {
427 // Check whether it is interesting as a nested-name-specifier.
428 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
429 IsNestedNameSpecifier(ND) &&
430 (Filter != &ResultBuilder::IsMember ||
431 (isa<CXXRecordDecl>(ND) &&
432 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
433 AsNestedNameSpecifier = true;
434 return true;
435 }
436
Douglas Gregor7c208612010-01-14 00:20:49 +0000437 return false;
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000438 }
John McCalle87beb22010-04-23 18:46:30 +0000439
440 if (Filter == &ResultBuilder::IsNestedNameSpecifier)
441 AsNestedNameSpecifier = true;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000442
Douglas Gregor7c208612010-01-14 00:20:49 +0000443 // ... then it must be interesting!
444 return true;
445}
446
Douglas Gregore0717ab2010-01-14 00:41:07 +0000447bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
448 NamedDecl *Hiding) {
449 // In C, there is no way to refer to a hidden name.
450 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
451 // name if we introduce the tag type.
452 if (!SemaRef.getLangOptions().CPlusPlus)
453 return true;
454
455 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
456
457 // There is no way to qualify a name declared in a function or method.
458 if (HiddenCtx->isFunctionOrMethod())
459 return true;
460
461 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
462 return true;
463
464 // We can refer to the result with the appropriate qualification. Do it.
465 R.Hidden = true;
466 R.QualifierIsInformative = false;
467
468 if (!R.Qualifier)
469 R.Qualifier = getRequiredQualification(SemaRef.Context,
470 CurContext,
471 R.Declaration->getDeclContext());
472 return false;
473}
474
Douglas Gregor7c208612010-01-14 00:20:49 +0000475void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
476 assert(!ShadowMaps.empty() && "Must enter into a results scope");
477
478 if (R.Kind != Result::RK_Declaration) {
479 // For non-declaration results, just add the result.
480 Results.push_back(R);
481 return;
482 }
483
484 // Look through using declarations.
485 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
486 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
487 return;
488 }
489
490 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
491 unsigned IDNS = CanonDecl->getIdentifierNamespace();
492
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000493 bool AsNestedNameSpecifier = false;
494 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000495 return;
496
Douglas Gregor3545ff42009-09-21 16:56:56 +0000497 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000498 ShadowMapEntry::iterator I, IEnd;
499 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
500 if (NamePos != SMap.end()) {
501 I = NamePos->second.begin();
502 IEnd = NamePos->second.end();
503 }
504
505 for (; I != IEnd; ++I) {
506 NamedDecl *ND = I->first;
507 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000508 if (ND->getCanonicalDecl() == CanonDecl) {
509 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000510 Results[Index].Declaration = R.Declaration;
511
Douglas Gregor3545ff42009-09-21 16:56:56 +0000512 // We're done.
513 return;
514 }
515 }
516
517 // This is a new declaration in this scope. However, check whether this
518 // declaration name is hidden by a similarly-named declaration in an outer
519 // scope.
520 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
521 --SMEnd;
522 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000523 ShadowMapEntry::iterator I, IEnd;
524 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
525 if (NamePos != SM->end()) {
526 I = NamePos->second.begin();
527 IEnd = NamePos->second.end();
528 }
529 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000530 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000531 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor3545ff42009-09-21 16:56:56 +0000532 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
533 Decl::IDNS_ObjCProtocol)))
534 continue;
535
536 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000537 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000538 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000539 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000540 continue;
541
542 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000543 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000544 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000545
546 break;
547 }
548 }
549
550 // Make sure that any given declaration only shows up in the result set once.
551 if (!AllDeclsFound.insert(CanonDecl))
552 return;
553
Douglas Gregore412a5a2009-09-23 22:26:46 +0000554 // If the filter is for nested-name-specifiers, then this result starts a
555 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000556 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000557 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000558 R.Priority = CCP_NestedNameSpecifier;
559 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000560
Douglas Gregor5bf52692009-09-22 23:15:58 +0000561 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000562 if (R.QualifierIsInformative && !R.Qualifier &&
563 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000564 DeclContext *Ctx = R.Declaration->getDeclContext();
565 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
566 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
567 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
568 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
569 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
570 else
571 R.QualifierIsInformative = false;
572 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000573
Douglas Gregor3545ff42009-09-21 16:56:56 +0000574 // Insert this result into the set of results and into the current shadow
575 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000576 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000577 Results.push_back(R);
578}
579
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000580enum SimplifiedTypeClass {
581 STC_Arithmetic,
582 STC_Array,
583 STC_Block,
584 STC_Function,
585 STC_ObjectiveC,
586 STC_Other,
587 STC_Pointer,
588 STC_Record,
589 STC_Void
590};
591
592/// \brief A simplified classification of types used to determine whether two
593/// types are "similar enough" when adjusting priorities.
594static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
595 switch (T->getTypeClass()) {
596 case Type::Builtin:
597 switch (cast<BuiltinType>(T)->getKind()) {
598 case BuiltinType::Void:
599 return STC_Void;
600
601 case BuiltinType::NullPtr:
602 return STC_Pointer;
603
604 case BuiltinType::Overload:
605 case BuiltinType::Dependent:
606 case BuiltinType::UndeducedAuto:
607 return STC_Other;
608
609 case BuiltinType::ObjCId:
610 case BuiltinType::ObjCClass:
611 case BuiltinType::ObjCSel:
612 return STC_ObjectiveC;
613
614 default:
615 return STC_Arithmetic;
616 }
617 return STC_Other;
618
619 case Type::Complex:
620 return STC_Arithmetic;
621
622 case Type::Pointer:
623 return STC_Pointer;
624
625 case Type::BlockPointer:
626 return STC_Block;
627
628 case Type::LValueReference:
629 case Type::RValueReference:
630 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
631
632 case Type::ConstantArray:
633 case Type::IncompleteArray:
634 case Type::VariableArray:
635 case Type::DependentSizedArray:
636 return STC_Array;
637
638 case Type::DependentSizedExtVector:
639 case Type::Vector:
640 case Type::ExtVector:
641 return STC_Arithmetic;
642
643 case Type::FunctionProto:
644 case Type::FunctionNoProto:
645 return STC_Function;
646
647 case Type::Record:
648 return STC_Record;
649
650 case Type::Enum:
651 return STC_Arithmetic;
652
653 case Type::ObjCObject:
654 case Type::ObjCInterface:
655 case Type::ObjCObjectPointer:
656 return STC_ObjectiveC;
657
658 default:
659 return STC_Other;
660 }
661}
662
663/// \brief Get the type that a given expression will have if this declaration
664/// is used as an expression in its "typical" code-completion form.
665static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
666 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
667
668 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
669 return C.getTypeDeclType(Type);
670 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
671 return C.getObjCInterfaceType(Iface);
672
673 QualType T;
674 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
675 T = Function->getResultType();
676 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
677 T = Method->getResultType();
678 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
679 T = FunTmpl->getTemplatedDecl()->getResultType();
680 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
681 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
682 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
683 T = Property->getType();
684 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
685 T = Value->getType();
686 else
687 return QualType();
688
689 return T.getNonReferenceType();
690}
691
Douglas Gregorc580c522010-01-14 01:09:38 +0000692void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000693 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000694 if (R.Kind != Result::RK_Declaration) {
695 // For non-declaration results, just add the result.
696 Results.push_back(R);
697 return;
698 }
699
Douglas Gregorc580c522010-01-14 01:09:38 +0000700 // Look through using declarations.
701 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
702 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
703 return;
704 }
705
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000706 bool AsNestedNameSpecifier = false;
707 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000708 return;
709
710 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
711 return;
712
713 // Make sure that any given declaration only shows up in the result set once.
714 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
715 return;
716
717 // If the filter is for nested-name-specifiers, then this result starts a
718 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000719 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000720 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000721 R.Priority = CCP_NestedNameSpecifier;
722 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000723 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
724 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
725 ->getLookupContext()))
726 R.QualifierIsInformative = true;
727
Douglas Gregorc580c522010-01-14 01:09:38 +0000728 // If this result is supposed to have an informative qualifier, add one.
729 if (R.QualifierIsInformative && !R.Qualifier &&
730 !R.StartsNestedNameSpecifier) {
731 DeclContext *Ctx = R.Declaration->getDeclContext();
732 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
733 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
734 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
735 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000736 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000737 else
738 R.QualifierIsInformative = false;
739 }
740
Douglas Gregora2db7932010-05-26 22:00:08 +0000741 // Adjust the priority if this result comes from a base class.
742 if (InBaseClass)
743 R.Priority += CCD_InBaseClass;
744
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000745 if (!PreferredType.isNull()) {
746 if (ValueDecl *Value = dyn_cast<ValueDecl>(R.Declaration)) {
747 CanQualType T = SemaRef.Context.getCanonicalType(
748 getDeclUsageType(SemaRef.Context, Value));
749 // Check for exactly-matching types (modulo qualifiers).
750 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, T))
751 R.Priority /= CCF_ExactTypeMatch;
752 // Check for nearly-matching types, based on classification of each.
753 else if ((getSimplifiedTypeClass(PreferredType)
754 == getSimplifiedTypeClass(T)) &&
755 !(PreferredType->isEnumeralType() && T->isEnumeralType()))
756 R.Priority /= CCF_SimilarTypeMatch;
757 }
758 }
759
Douglas Gregorc580c522010-01-14 01:09:38 +0000760 // Insert this result into the set of results.
761 Results.push_back(R);
762}
763
Douglas Gregor78a21012010-01-14 16:01:26 +0000764void ResultBuilder::AddResult(Result R) {
765 assert(R.Kind != Result::RK_Declaration &&
766 "Declaration results need more context");
767 Results.push_back(R);
768}
769
Douglas Gregor3545ff42009-09-21 16:56:56 +0000770/// \brief Enter into a new scope.
771void ResultBuilder::EnterNewScope() {
772 ShadowMaps.push_back(ShadowMap());
773}
774
775/// \brief Exit from the current scope.
776void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000777 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
778 EEnd = ShadowMaps.back().end();
779 E != EEnd;
780 ++E)
781 E->second.Destroy();
782
Douglas Gregor3545ff42009-09-21 16:56:56 +0000783 ShadowMaps.pop_back();
784}
785
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000786/// \brief Determines whether this given declaration will be found by
787/// ordinary name lookup.
788bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +0000789 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
790
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000791 unsigned IDNS = Decl::IDNS_Ordinary;
792 if (SemaRef.getLangOptions().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +0000793 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregorc580c522010-01-14 01:09:38 +0000794 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
795 return true;
796
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000797 return ND->getIdentifierNamespace() & IDNS;
798}
799
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000800/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +0000801/// ordinary name lookup but is not a type name.
802bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
803 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
804 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
805 return false;
806
807 unsigned IDNS = Decl::IDNS_Ordinary;
808 if (SemaRef.getLangOptions().CPlusPlus)
809 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
810 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
811 return true;
812
813 return ND->getIdentifierNamespace() & IDNS;
814}
815
816/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000817/// ordinary name lookup.
818bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +0000819 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
820
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000821 unsigned IDNS = Decl::IDNS_Ordinary;
822 if (SemaRef.getLangOptions().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +0000823 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000824
825 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +0000826 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
827 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000828}
829
Douglas Gregor3545ff42009-09-21 16:56:56 +0000830/// \brief Determines whether the given declaration is suitable as the
831/// start of a C++ nested-name-specifier, e.g., a class or namespace.
832bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
833 // Allow us to find class templates, too.
834 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
835 ND = ClassTemplate->getTemplatedDecl();
836
837 return SemaRef.isAcceptableNestedNameSpecifier(ND);
838}
839
840/// \brief Determines whether the given declaration is an enumeration.
841bool ResultBuilder::IsEnum(NamedDecl *ND) const {
842 return isa<EnumDecl>(ND);
843}
844
845/// \brief Determines whether the given declaration is a class or struct.
846bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
847 // Allow us to find class templates, too.
848 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
849 ND = ClassTemplate->getTemplatedDecl();
850
851 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +0000852 return RD->getTagKind() == TTK_Class ||
853 RD->getTagKind() == TTK_Struct;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000854
855 return false;
856}
857
858/// \brief Determines whether the given declaration is a union.
859bool ResultBuilder::IsUnion(NamedDecl *ND) const {
860 // Allow us to find class templates, too.
861 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
862 ND = ClassTemplate->getTemplatedDecl();
863
864 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +0000865 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000866
867 return false;
868}
869
870/// \brief Determines whether the given declaration is a namespace.
871bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
872 return isa<NamespaceDecl>(ND);
873}
874
875/// \brief Determines whether the given declaration is a namespace or
876/// namespace alias.
877bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
878 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
879}
880
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000881/// \brief Determines whether the given declaration is a type.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000882bool ResultBuilder::IsType(NamedDecl *ND) const {
883 return isa<TypeDecl>(ND);
884}
885
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000886/// \brief Determines which members of a class should be visible via
887/// "." or "->". Only value declarations, nested name specifiers, and
888/// using declarations thereof should show up.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000889bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000890 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
891 ND = Using->getTargetDecl();
892
Douglas Gregor70788392009-12-11 18:14:22 +0000893 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
894 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +0000895}
896
Douglas Gregora817a192010-05-27 23:06:34 +0000897static bool isObjCReceiverType(ASTContext &C, QualType T) {
898 T = C.getCanonicalType(T);
899 switch (T->getTypeClass()) {
900 case Type::ObjCObject:
901 case Type::ObjCInterface:
902 case Type::ObjCObjectPointer:
903 return true;
904
905 case Type::Builtin:
906 switch (cast<BuiltinType>(T)->getKind()) {
907 case BuiltinType::ObjCId:
908 case BuiltinType::ObjCClass:
909 case BuiltinType::ObjCSel:
910 return true;
911
912 default:
913 break;
914 }
915 return false;
916
917 default:
918 break;
919 }
920
921 if (!C.getLangOptions().CPlusPlus)
922 return false;
923
924 // FIXME: We could perform more analysis here to determine whether a
925 // particular class type has any conversions to Objective-C types. For now,
926 // just accept all class types.
927 return T->isDependentType() || T->isRecordType();
928}
929
930bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
931 QualType T = getDeclUsageType(SemaRef.Context, ND);
932 if (T.isNull())
933 return false;
934
935 T = SemaRef.Context.getBaseElementType(T);
936 return isObjCReceiverType(SemaRef.Context, T);
937}
938
939
Douglas Gregor2b8162b2010-01-14 16:08:12 +0000940/// \rief Determines whether the given declaration is an Objective-C
941/// instance variable.
942bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
943 return isa<ObjCIvarDecl>(ND);
944}
945
Douglas Gregorc580c522010-01-14 01:09:38 +0000946namespace {
947 /// \brief Visible declaration consumer that adds a code-completion result
948 /// for each visible declaration.
949 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
950 ResultBuilder &Results;
951 DeclContext *CurContext;
952
953 public:
954 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
955 : Results(Results), CurContext(CurContext) { }
956
Douglas Gregor09bbc652010-01-14 15:47:35 +0000957 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
958 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +0000959 }
960 };
961}
962
Douglas Gregor3545ff42009-09-21 16:56:56 +0000963/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +0000964static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000965 ResultBuilder &Results) {
966 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora2db7932010-05-26 22:00:08 +0000967 Results.AddResult(Result("short", CCP_Type));
968 Results.AddResult(Result("long", CCP_Type));
969 Results.AddResult(Result("signed", CCP_Type));
970 Results.AddResult(Result("unsigned", CCP_Type));
971 Results.AddResult(Result("void", CCP_Type));
972 Results.AddResult(Result("char", CCP_Type));
973 Results.AddResult(Result("int", CCP_Type));
974 Results.AddResult(Result("float", CCP_Type));
975 Results.AddResult(Result("double", CCP_Type));
976 Results.AddResult(Result("enum", CCP_Type));
977 Results.AddResult(Result("struct", CCP_Type));
978 Results.AddResult(Result("union", CCP_Type));
979 Results.AddResult(Result("const", CCP_Type));
980 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000981
Douglas Gregor3545ff42009-09-21 16:56:56 +0000982 if (LangOpts.C99) {
983 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +0000984 Results.AddResult(Result("_Complex", CCP_Type));
985 Results.AddResult(Result("_Imaginary", CCP_Type));
986 Results.AddResult(Result("_Bool", CCP_Type));
987 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000988 }
989
990 if (LangOpts.CPlusPlus) {
991 // C++-specific
Douglas Gregora2db7932010-05-26 22:00:08 +0000992 Results.AddResult(Result("bool", CCP_Type));
993 Results.AddResult(Result("class", CCP_Type));
994 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000995
Douglas Gregorf4c33342010-05-28 00:22:41 +0000996 // typename qualified-id
997 CodeCompletionString *Pattern = new CodeCompletionString;
998 Pattern->AddTypedTextChunk("typename");
999 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1000 Pattern->AddPlaceholderChunk("qualifier");
1001 Pattern->AddTextChunk("::");
1002 Pattern->AddPlaceholderChunk("name");
1003 Results.AddResult(Result(Pattern));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001004
Douglas Gregor3545ff42009-09-21 16:56:56 +00001005 if (LangOpts.CPlusPlus0x) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001006 Results.AddResult(Result("auto", CCP_Type));
1007 Results.AddResult(Result("char16_t", CCP_Type));
1008 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001009
1010 CodeCompletionString *Pattern = new CodeCompletionString;
1011 Pattern->AddTypedTextChunk("decltype");
1012 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1013 Pattern->AddPlaceholderChunk("expression");
1014 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1015 Results.AddResult(Result(Pattern));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001016 }
1017 }
1018
1019 // GNU extensions
1020 if (LangOpts.GNUMode) {
1021 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001022 // Results.AddResult(Result("_Decimal32"));
1023 // Results.AddResult(Result("_Decimal64"));
1024 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001025
Douglas Gregorf4c33342010-05-28 00:22:41 +00001026 CodeCompletionString *Pattern = new CodeCompletionString;
1027 Pattern->AddTypedTextChunk("typeof");
1028 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1029 Pattern->AddPlaceholderChunk("expression");
1030 Results.AddResult(Result(Pattern));
1031
1032 Pattern = new CodeCompletionString;
1033 Pattern->AddTypedTextChunk("typeof");
1034 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1035 Pattern->AddPlaceholderChunk("type");
1036 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1037 Results.AddResult(Result(Pattern));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001038 }
1039}
1040
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001041static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
1042 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001043 ResultBuilder &Results) {
1044 typedef CodeCompleteConsumer::Result Result;
1045 // Note: we don't suggest either "auto" or "register", because both
1046 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1047 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001048 Results.AddResult(Result("extern"));
1049 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001050}
1051
1052static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
1053 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001054 ResultBuilder &Results) {
1055 typedef CodeCompleteConsumer::Result Result;
1056 switch (CCC) {
1057 case Action::CCC_Class:
1058 case Action::CCC_MemberTemplate:
1059 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001060 Results.AddResult(Result("explicit"));
1061 Results.AddResult(Result("friend"));
1062 Results.AddResult(Result("mutable"));
1063 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001064 }
1065 // Fall through
1066
Douglas Gregorf1934162010-01-13 21:24:21 +00001067 case Action::CCC_ObjCInterface:
1068 case Action::CCC_ObjCImplementation:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001069 case Action::CCC_Namespace:
1070 case Action::CCC_Template:
1071 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001072 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001073 break;
1074
Douglas Gregor48d46252010-01-13 21:54:15 +00001075 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001076 case Action::CCC_Expression:
1077 case Action::CCC_Statement:
1078 case Action::CCC_ForInit:
1079 case Action::CCC_Condition:
Douglas Gregor6da3db42010-05-25 05:58:43 +00001080 case Action::CCC_RecoveryInFunction:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001081 break;
1082 }
1083}
1084
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001085static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1086static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1087static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001088 ResultBuilder &Results,
1089 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001090static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001091 ResultBuilder &Results,
1092 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001093static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001094 ResultBuilder &Results,
1095 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001096static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001097
Douglas Gregorf4c33342010-05-28 00:22:41 +00001098static void AddTypedefResult(ResultBuilder &Results) {
1099 CodeCompletionString *Pattern = new CodeCompletionString;
1100 Pattern->AddTypedTextChunk("typedef");
1101 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1102 Pattern->AddPlaceholderChunk("type");
1103 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1104 Pattern->AddPlaceholderChunk("name");
1105 Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1106}
1107
Douglas Gregor70febae2010-05-28 00:49:12 +00001108static bool WantTypesInContext(Action::CodeCompletionContext CCC,
1109 const LangOptions &LangOpts) {
1110 if (LangOpts.CPlusPlus)
1111 return true;
1112
1113 switch (CCC) {
1114 case Action::CCC_Namespace:
1115 case Action::CCC_Class:
1116 case Action::CCC_ObjCInstanceVariableList:
1117 case Action::CCC_Template:
1118 case Action::CCC_MemberTemplate:
1119 case Action::CCC_Statement:
1120 case Action::CCC_RecoveryInFunction:
1121 return true;
1122
1123 case Action::CCC_ObjCInterface:
1124 case Action::CCC_ObjCImplementation:
1125 case Action::CCC_Expression:
1126 case Action::CCC_Condition:
1127 return false;
1128
1129 case Action::CCC_ForInit:
1130 return LangOpts.ObjC1 || LangOpts.C99;
1131 }
1132
1133 return false;
1134}
1135
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001136/// \brief Add language constructs that show up for "ordinary" names.
1137static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
1138 Scope *S,
1139 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001140 ResultBuilder &Results) {
1141 typedef CodeCompleteConsumer::Result Result;
1142 switch (CCC) {
1143 case Action::CCC_Namespace:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001144 if (SemaRef.getLangOptions().CPlusPlus) {
1145 CodeCompletionString *Pattern = 0;
1146
1147 if (Results.includeCodePatterns()) {
1148 // namespace <identifier> { declarations }
1149 CodeCompletionString *Pattern = new CodeCompletionString;
1150 Pattern->AddTypedTextChunk("namespace");
1151 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1152 Pattern->AddPlaceholderChunk("identifier");
1153 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1154 Pattern->AddPlaceholderChunk("declarations");
1155 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1156 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1157 Results.AddResult(Result(Pattern));
1158 }
1159
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001160 // namespace identifier = identifier ;
1161 Pattern = new CodeCompletionString;
1162 Pattern->AddTypedTextChunk("namespace");
1163 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001164 Pattern->AddPlaceholderChunk("name");
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001165 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001166 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregor78a21012010-01-14 16:01:26 +00001167 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001168
1169 // Using directives
1170 Pattern = new CodeCompletionString;
1171 Pattern->AddTypedTextChunk("using");
1172 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1173 Pattern->AddTextChunk("namespace");
1174 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1175 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregor78a21012010-01-14 16:01:26 +00001176 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001177
1178 // asm(string-literal)
1179 Pattern = new CodeCompletionString;
1180 Pattern->AddTypedTextChunk("asm");
1181 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1182 Pattern->AddPlaceholderChunk("string-literal");
1183 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00001184 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001185
Douglas Gregorf4c33342010-05-28 00:22:41 +00001186 if (Results.includeCodePatterns()) {
1187 // Explicit template instantiation
1188 Pattern = new CodeCompletionString;
1189 Pattern->AddTypedTextChunk("template");
1190 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1191 Pattern->AddPlaceholderChunk("declaration");
1192 Results.AddResult(Result(Pattern));
1193 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001194 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001195
1196 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001197 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001198
Douglas Gregorf4c33342010-05-28 00:22:41 +00001199 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001200 // Fall through
1201
1202 case Action::CCC_Class:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001203 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001204 // Using declaration
1205 CodeCompletionString *Pattern = new CodeCompletionString;
1206 Pattern->AddTypedTextChunk("using");
1207 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001208 Pattern->AddPlaceholderChunk("qualifier");
1209 Pattern->AddTextChunk("::");
1210 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00001211 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001212
Douglas Gregorf4c33342010-05-28 00:22:41 +00001213 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001214 if (SemaRef.CurContext->isDependentContext()) {
1215 Pattern = new CodeCompletionString;
1216 Pattern->AddTypedTextChunk("using");
1217 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1218 Pattern->AddTextChunk("typename");
1219 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001220 Pattern->AddPlaceholderChunk("qualifier");
1221 Pattern->AddTextChunk("::");
1222 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00001223 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001224 }
1225
1226 if (CCC == Action::CCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001227 AddTypedefResult(Results);
1228
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001229 // public:
1230 Pattern = new CodeCompletionString;
1231 Pattern->AddTypedTextChunk("public");
1232 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001233 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001234
1235 // protected:
1236 Pattern = new CodeCompletionString;
1237 Pattern->AddTypedTextChunk("protected");
1238 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001239 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001240
1241 // private:
1242 Pattern = new CodeCompletionString;
1243 Pattern->AddTypedTextChunk("private");
1244 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001245 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001246 }
1247 }
1248 // Fall through
1249
1250 case Action::CCC_Template:
1251 case Action::CCC_MemberTemplate:
Douglas Gregorf64acca2010-05-25 21:41:55 +00001252 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001253 // template < parameters >
1254 CodeCompletionString *Pattern = new CodeCompletionString;
1255 Pattern->AddTypedTextChunk("template");
1256 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1257 Pattern->AddPlaceholderChunk("parameters");
1258 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor78a21012010-01-14 16:01:26 +00001259 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001260 }
1261
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001262 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1263 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001264 break;
1265
Douglas Gregorf1934162010-01-13 21:24:21 +00001266 case Action::CCC_ObjCInterface:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001267 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1268 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1269 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001270 break;
1271
1272 case Action::CCC_ObjCImplementation:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001273 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1274 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1275 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001276 break;
1277
Douglas Gregor48d46252010-01-13 21:54:15 +00001278 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001279 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001280 break;
1281
Douglas Gregor6da3db42010-05-25 05:58:43 +00001282 case Action::CCC_RecoveryInFunction:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001283 case Action::CCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001284 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001285
1286 CodeCompletionString *Pattern = 0;
Douglas Gregorf64acca2010-05-25 21:41:55 +00001287 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001288 Pattern = new CodeCompletionString;
1289 Pattern->AddTypedTextChunk("try");
1290 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1291 Pattern->AddPlaceholderChunk("statements");
1292 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1293 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1294 Pattern->AddTextChunk("catch");
1295 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1296 Pattern->AddPlaceholderChunk("declaration");
1297 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1298 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1299 Pattern->AddPlaceholderChunk("statements");
1300 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1301 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor78a21012010-01-14 16:01:26 +00001302 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001303 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001304 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001305 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001306
Douglas Gregorf64acca2010-05-25 21:41:55 +00001307 if (Results.includeCodePatterns()) {
1308 // if (condition) { statements }
1309 Pattern = new CodeCompletionString;
1310 Pattern->AddTypedTextChunk("if");
1311 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1312 if (SemaRef.getLangOptions().CPlusPlus)
1313 Pattern->AddPlaceholderChunk("condition");
1314 else
1315 Pattern->AddPlaceholderChunk("expression");
1316 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1317 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1318 Pattern->AddPlaceholderChunk("statements");
1319 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1320 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1321 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001322
Douglas Gregorf64acca2010-05-25 21:41:55 +00001323 // switch (condition) { }
1324 Pattern = new CodeCompletionString;
1325 Pattern->AddTypedTextChunk("switch");
1326 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1327 if (SemaRef.getLangOptions().CPlusPlus)
1328 Pattern->AddPlaceholderChunk("condition");
1329 else
1330 Pattern->AddPlaceholderChunk("expression");
1331 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1332 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1333 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1334 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1335 Results.AddResult(Result(Pattern));
1336 }
1337
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001338 // Switch-specific statements.
Douglas Gregorf4c33342010-05-28 00:22:41 +00001339 if (!SemaRef.getSwitchStack().empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001340 // case expression:
1341 Pattern = new CodeCompletionString;
1342 Pattern->AddTypedTextChunk("case");
Douglas Gregorf4c33342010-05-28 00:22:41 +00001343 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001344 Pattern->AddPlaceholderChunk("expression");
1345 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001346 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001347
1348 // default:
1349 Pattern = new CodeCompletionString;
1350 Pattern->AddTypedTextChunk("default");
1351 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001352 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001353 }
1354
Douglas Gregorf64acca2010-05-25 21:41:55 +00001355 if (Results.includeCodePatterns()) {
1356 /// while (condition) { statements }
1357 Pattern = new CodeCompletionString;
1358 Pattern->AddTypedTextChunk("while");
1359 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1360 if (SemaRef.getLangOptions().CPlusPlus)
1361 Pattern->AddPlaceholderChunk("condition");
1362 else
1363 Pattern->AddPlaceholderChunk("expression");
1364 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1365 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1366 Pattern->AddPlaceholderChunk("statements");
1367 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1368 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1369 Results.AddResult(Result(Pattern));
1370
1371 // do { statements } while ( expression );
1372 Pattern = new CodeCompletionString;
1373 Pattern->AddTypedTextChunk("do");
1374 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1375 Pattern->AddPlaceholderChunk("statements");
1376 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1377 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1378 Pattern->AddTextChunk("while");
1379 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001380 Pattern->AddPlaceholderChunk("expression");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001381 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1382 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001383
Douglas Gregorf64acca2010-05-25 21:41:55 +00001384 // for ( for-init-statement ; condition ; expression ) { statements }
1385 Pattern = new CodeCompletionString;
1386 Pattern->AddTypedTextChunk("for");
1387 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1388 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1389 Pattern->AddPlaceholderChunk("init-statement");
1390 else
1391 Pattern->AddPlaceholderChunk("init-expression");
1392 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1393 Pattern->AddPlaceholderChunk("condition");
1394 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1395 Pattern->AddPlaceholderChunk("inc-expression");
1396 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1397 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1398 Pattern->AddPlaceholderChunk("statements");
1399 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1400 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1401 Results.AddResult(Result(Pattern));
1402 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001403
1404 if (S->getContinueParent()) {
1405 // continue ;
1406 Pattern = new CodeCompletionString;
1407 Pattern->AddTypedTextChunk("continue");
Douglas Gregor78a21012010-01-14 16:01:26 +00001408 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001409 }
1410
1411 if (S->getBreakParent()) {
1412 // break ;
1413 Pattern = new CodeCompletionString;
1414 Pattern->AddTypedTextChunk("break");
Douglas Gregor78a21012010-01-14 16:01:26 +00001415 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001416 }
1417
1418 // "return expression ;" or "return ;", depending on whether we
1419 // know the function is void or not.
1420 bool isVoid = false;
1421 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1422 isVoid = Function->getResultType()->isVoidType();
1423 else if (ObjCMethodDecl *Method
1424 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1425 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001426 else if (SemaRef.getCurBlock() &&
1427 !SemaRef.getCurBlock()->ReturnType.isNull())
1428 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001429 Pattern = new CodeCompletionString;
1430 Pattern->AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001431 if (!isVoid) {
1432 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001433 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001434 }
Douglas Gregor78a21012010-01-14 16:01:26 +00001435 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001436
Douglas Gregorf4c33342010-05-28 00:22:41 +00001437 // goto identifier ;
1438 Pattern = new CodeCompletionString;
1439 Pattern->AddTypedTextChunk("goto");
1440 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1441 Pattern->AddPlaceholderChunk("label");
1442 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001443
Douglas Gregorf4c33342010-05-28 00:22:41 +00001444 // Using directives
1445 Pattern = new CodeCompletionString;
1446 Pattern->AddTypedTextChunk("using");
1447 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1448 Pattern->AddTextChunk("namespace");
1449 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1450 Pattern->AddPlaceholderChunk("identifier");
1451 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001452 }
1453
1454 // Fall through (for statement expressions).
1455 case Action::CCC_ForInit:
1456 case Action::CCC_Condition:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001457 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001458 // Fall through: conditions and statements can have expressions.
1459
1460 case Action::CCC_Expression: {
1461 CodeCompletionString *Pattern = 0;
1462 if (SemaRef.getLangOptions().CPlusPlus) {
1463 // 'this', if we're in a non-static member function.
1464 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1465 if (!Method->isStatic())
Douglas Gregor78a21012010-01-14 16:01:26 +00001466 Results.AddResult(Result("this"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001467
1468 // true, false
Douglas Gregor78a21012010-01-14 16:01:26 +00001469 Results.AddResult(Result("true"));
1470 Results.AddResult(Result("false"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001471
Douglas Gregorf4c33342010-05-28 00:22:41 +00001472 // dynamic_cast < type-id > ( expression )
1473 Pattern = new CodeCompletionString;
1474 Pattern->AddTypedTextChunk("dynamic_cast");
1475 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1476 Pattern->AddPlaceholderChunk("type");
1477 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1478 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1479 Pattern->AddPlaceholderChunk("expression");
1480 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1481 Results.AddResult(Result(Pattern));
1482
1483 // static_cast < type-id > ( expression )
1484 Pattern = new CodeCompletionString;
1485 Pattern->AddTypedTextChunk("static_cast");
1486 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1487 Pattern->AddPlaceholderChunk("type");
1488 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1489 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1490 Pattern->AddPlaceholderChunk("expression");
1491 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1492 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001493
Douglas Gregorf4c33342010-05-28 00:22:41 +00001494 // reinterpret_cast < type-id > ( expression )
1495 Pattern = new CodeCompletionString;
1496 Pattern->AddTypedTextChunk("reinterpret_cast");
1497 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1498 Pattern->AddPlaceholderChunk("type");
1499 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1500 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1501 Pattern->AddPlaceholderChunk("expression");
1502 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1503 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001504
Douglas Gregorf4c33342010-05-28 00:22:41 +00001505 // const_cast < type-id > ( expression )
1506 Pattern = new CodeCompletionString;
1507 Pattern->AddTypedTextChunk("const_cast");
1508 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1509 Pattern->AddPlaceholderChunk("type");
1510 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1511 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1512 Pattern->AddPlaceholderChunk("expression");
1513 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1514 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001515
Douglas Gregorf4c33342010-05-28 00:22:41 +00001516 // typeid ( expression-or-type )
1517 Pattern = new CodeCompletionString;
1518 Pattern->AddTypedTextChunk("typeid");
1519 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1520 Pattern->AddPlaceholderChunk("expression-or-type");
1521 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1522 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001523
Douglas Gregorf4c33342010-05-28 00:22:41 +00001524 // new T ( ... )
1525 Pattern = new CodeCompletionString;
1526 Pattern->AddTypedTextChunk("new");
1527 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1528 Pattern->AddPlaceholderChunk("type");
1529 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1530 Pattern->AddPlaceholderChunk("expressions");
1531 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1532 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001533
Douglas Gregorf4c33342010-05-28 00:22:41 +00001534 // new T [ ] ( ... )
1535 Pattern = new CodeCompletionString;
1536 Pattern->AddTypedTextChunk("new");
1537 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1538 Pattern->AddPlaceholderChunk("type");
1539 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1540 Pattern->AddPlaceholderChunk("size");
1541 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1542 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1543 Pattern->AddPlaceholderChunk("expressions");
1544 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1545 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001546
Douglas Gregorf4c33342010-05-28 00:22:41 +00001547 // delete expression
1548 Pattern = new CodeCompletionString;
1549 Pattern->AddTypedTextChunk("delete");
1550 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1551 Pattern->AddPlaceholderChunk("expression");
1552 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001553
Douglas Gregorf4c33342010-05-28 00:22:41 +00001554 // delete [] expression
1555 Pattern = new CodeCompletionString;
1556 Pattern->AddTypedTextChunk("delete");
1557 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1558 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1559 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1560 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1561 Pattern->AddPlaceholderChunk("expression");
1562 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001563
Douglas Gregorf4c33342010-05-28 00:22:41 +00001564 // throw expression
1565 Pattern = new CodeCompletionString;
1566 Pattern->AddTypedTextChunk("throw");
1567 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1568 Pattern->AddPlaceholderChunk("expression");
1569 Results.AddResult(Result(Pattern));
Douglas Gregora2db7932010-05-26 22:00:08 +00001570
1571 // FIXME: Rethrow?
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001572 }
1573
1574 if (SemaRef.getLangOptions().ObjC1) {
1575 // Add "super", if we're in an Objective-C class with a superclass.
1576 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
1577 if (Method->getClassInterface()->getSuperClass())
Douglas Gregor78a21012010-01-14 16:01:26 +00001578 Results.AddResult(Result("super"));
Douglas Gregorf1934162010-01-13 21:24:21 +00001579
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001580 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001581 }
1582
Douglas Gregorf4c33342010-05-28 00:22:41 +00001583 // sizeof expression
1584 Pattern = new CodeCompletionString;
1585 Pattern->AddTypedTextChunk("sizeof");
1586 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1587 Pattern->AddPlaceholderChunk("expression-or-type");
1588 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1589 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001590 break;
1591 }
1592 }
1593
Douglas Gregor70febae2010-05-28 00:49:12 +00001594 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1595 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001596
1597 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor78a21012010-01-14 16:01:26 +00001598 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001599}
1600
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001601/// \brief If the given declaration has an associated type, add it as a result
1602/// type chunk.
1603static void AddResultTypeChunk(ASTContext &Context,
1604 NamedDecl *ND,
1605 CodeCompletionString *Result) {
1606 if (!ND)
1607 return;
1608
1609 // Determine the type of the declaration (if it has a type).
1610 QualType T;
1611 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1612 T = Function->getResultType();
1613 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1614 T = Method->getResultType();
1615 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1616 T = FunTmpl->getTemplatedDecl()->getResultType();
1617 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1618 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1619 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1620 /* Do nothing: ignore unresolved using declarations*/
1621 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1622 T = Value->getType();
1623 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1624 T = Property->getType();
1625
1626 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1627 return;
1628
Douglas Gregorcf04b022010-04-05 21:25:31 +00001629 PrintingPolicy Policy(Context.PrintingPolicy);
1630 Policy.AnonymousTagLocations = false;
1631
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001632 std::string TypeStr;
Douglas Gregorcf04b022010-04-05 21:25:31 +00001633 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001634 Result->AddResultTypeChunk(TypeStr);
1635}
1636
Douglas Gregor3545ff42009-09-21 16:56:56 +00001637/// \brief Add function parameter chunks to the given code completion string.
1638static void AddFunctionParameterChunks(ASTContext &Context,
1639 FunctionDecl *Function,
1640 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001641 typedef CodeCompletionString::Chunk Chunk;
1642
Douglas Gregor3545ff42009-09-21 16:56:56 +00001643 CodeCompletionString *CCStr = Result;
1644
1645 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1646 ParmVarDecl *Param = Function->getParamDecl(P);
1647
1648 if (Param->hasDefaultArg()) {
1649 // When we see an optional default argument, put that argument and
1650 // the remaining default arguments into a new, optional string.
1651 CodeCompletionString *Opt = new CodeCompletionString;
1652 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1653 CCStr = Opt;
1654 }
1655
1656 if (P != 0)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001657 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001658
1659 // Format the placeholder string.
1660 std::string PlaceholderStr;
1661 if (Param->getIdentifier())
1662 PlaceholderStr = Param->getIdentifier()->getName();
1663
1664 Param->getType().getAsStringInternal(PlaceholderStr,
1665 Context.PrintingPolicy);
1666
1667 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001668 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001669 }
Douglas Gregorba449032009-09-22 21:42:17 +00001670
1671 if (const FunctionProtoType *Proto
1672 = Function->getType()->getAs<FunctionProtoType>())
1673 if (Proto->isVariadic())
1674 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001675}
1676
1677/// \brief Add template parameter chunks to the given code completion string.
1678static void AddTemplateParameterChunks(ASTContext &Context,
1679 TemplateDecl *Template,
1680 CodeCompletionString *Result,
1681 unsigned MaxParameters = 0) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001682 typedef CodeCompletionString::Chunk Chunk;
1683
Douglas Gregor3545ff42009-09-21 16:56:56 +00001684 CodeCompletionString *CCStr = Result;
1685 bool FirstParameter = true;
1686
1687 TemplateParameterList *Params = Template->getTemplateParameters();
1688 TemplateParameterList::iterator PEnd = Params->end();
1689 if (MaxParameters)
1690 PEnd = Params->begin() + MaxParameters;
1691 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1692 bool HasDefaultArg = false;
1693 std::string PlaceholderStr;
1694 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1695 if (TTP->wasDeclaredWithTypename())
1696 PlaceholderStr = "typename";
1697 else
1698 PlaceholderStr = "class";
1699
1700 if (TTP->getIdentifier()) {
1701 PlaceholderStr += ' ';
1702 PlaceholderStr += TTP->getIdentifier()->getName();
1703 }
1704
1705 HasDefaultArg = TTP->hasDefaultArgument();
1706 } else if (NonTypeTemplateParmDecl *NTTP
1707 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1708 if (NTTP->getIdentifier())
1709 PlaceholderStr = NTTP->getIdentifier()->getName();
1710 NTTP->getType().getAsStringInternal(PlaceholderStr,
1711 Context.PrintingPolicy);
1712 HasDefaultArg = NTTP->hasDefaultArgument();
1713 } else {
1714 assert(isa<TemplateTemplateParmDecl>(*P));
1715 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1716
1717 // Since putting the template argument list into the placeholder would
1718 // be very, very long, we just use an abbreviation.
1719 PlaceholderStr = "template<...> class";
1720 if (TTP->getIdentifier()) {
1721 PlaceholderStr += ' ';
1722 PlaceholderStr += TTP->getIdentifier()->getName();
1723 }
1724
1725 HasDefaultArg = TTP->hasDefaultArgument();
1726 }
1727
1728 if (HasDefaultArg) {
1729 // When we see an optional default argument, put that argument and
1730 // the remaining default arguments into a new, optional string.
1731 CodeCompletionString *Opt = new CodeCompletionString;
1732 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1733 CCStr = Opt;
1734 }
1735
1736 if (FirstParameter)
1737 FirstParameter = false;
1738 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001739 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001740
1741 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001742 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001743 }
1744}
1745
Douglas Gregorf2510672009-09-21 19:57:38 +00001746/// \brief Add a qualifier to the given code-completion string, if the
1747/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00001748static void
1749AddQualifierToCompletionString(CodeCompletionString *Result,
1750 NestedNameSpecifier *Qualifier,
1751 bool QualifierIsInformative,
1752 ASTContext &Context) {
Douglas Gregorf2510672009-09-21 19:57:38 +00001753 if (!Qualifier)
1754 return;
1755
1756 std::string PrintedNNS;
1757 {
1758 llvm::raw_string_ostream OS(PrintedNNS);
1759 Qualifier->print(OS, Context.PrintingPolicy);
1760 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00001761 if (QualifierIsInformative)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001762 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor5bf52692009-09-22 23:15:58 +00001763 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001764 Result->AddTextChunk(PrintedNNS);
Douglas Gregorf2510672009-09-21 19:57:38 +00001765}
1766
Douglas Gregor0f622362009-12-11 18:44:16 +00001767static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1768 FunctionDecl *Function) {
1769 const FunctionProtoType *Proto
1770 = Function->getType()->getAs<FunctionProtoType>();
1771 if (!Proto || !Proto->getTypeQuals())
1772 return;
1773
1774 std::string QualsStr;
1775 if (Proto->getTypeQuals() & Qualifiers::Const)
1776 QualsStr += " const";
1777 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1778 QualsStr += " volatile";
1779 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1780 QualsStr += " restrict";
1781 Result->AddInformativeChunk(QualsStr);
1782}
1783
Douglas Gregor3545ff42009-09-21 16:56:56 +00001784/// \brief If possible, create a new code completion string for the given
1785/// result.
1786///
1787/// \returns Either a new, heap-allocated code completion string describing
1788/// how to use this result, or NULL to indicate that the string or name of the
1789/// result is all that is needed.
1790CodeCompletionString *
1791CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001792 typedef CodeCompletionString::Chunk Chunk;
1793
Douglas Gregorf09935f2009-12-01 05:55:20 +00001794 if (Kind == RK_Pattern)
1795 return Pattern->Clone();
1796
1797 CodeCompletionString *Result = new CodeCompletionString;
1798
1799 if (Kind == RK_Keyword) {
1800 Result->AddTypedTextChunk(Keyword);
1801 return Result;
1802 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001803
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001804 if (Kind == RK_Macro) {
1805 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001806 assert(MI && "Not a macro?");
1807
1808 Result->AddTypedTextChunk(Macro->getName());
1809
1810 if (!MI->isFunctionLike())
1811 return Result;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001812
1813 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001814 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001815 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1816 A != AEnd; ++A) {
1817 if (A != MI->arg_begin())
Douglas Gregor9eb77012009-11-07 00:00:49 +00001818 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001819
1820 if (!MI->isVariadic() || A != AEnd - 1) {
1821 // Non-variadic argument.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001822 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001823 continue;
1824 }
1825
1826 // Variadic argument; cope with the different between GNU and C99
1827 // variadic macros, providing a single placeholder for the rest of the
1828 // arguments.
1829 if ((*A)->isStr("__VA_ARGS__"))
1830 Result->AddPlaceholderChunk("...");
1831 else {
1832 std::string Arg = (*A)->getName();
1833 Arg += "...";
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001834 Result->AddPlaceholderChunk(Arg);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001835 }
1836 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001837 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001838 return Result;
1839 }
1840
Douglas Gregorf64acca2010-05-25 21:41:55 +00001841 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001842 NamedDecl *ND = Declaration;
1843
Douglas Gregor9eb77012009-11-07 00:00:49 +00001844 if (StartsNestedNameSpecifier) {
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001845 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001846 Result->AddTextChunk("::");
1847 return Result;
1848 }
1849
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001850 AddResultTypeChunk(S.Context, ND, Result);
1851
Douglas Gregor3545ff42009-09-21 16:56:56 +00001852 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001853 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1854 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001855 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001856 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001857 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001858 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001859 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001860 return Result;
1861 }
1862
1863 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001864 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1865 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001866 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001867 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001868
1869 // Figure out which template parameters are deduced (or have default
1870 // arguments).
1871 llvm::SmallVector<bool, 16> Deduced;
1872 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1873 unsigned LastDeducibleArgument;
1874 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1875 --LastDeducibleArgument) {
1876 if (!Deduced[LastDeducibleArgument - 1]) {
1877 // C++0x: Figure out if the template argument has a default. If so,
1878 // the user doesn't need to type this argument.
1879 // FIXME: We need to abstract template parameters better!
1880 bool HasDefaultArg = false;
1881 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1882 LastDeducibleArgument - 1);
1883 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1884 HasDefaultArg = TTP->hasDefaultArgument();
1885 else if (NonTypeTemplateParmDecl *NTTP
1886 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1887 HasDefaultArg = NTTP->hasDefaultArgument();
1888 else {
1889 assert(isa<TemplateTemplateParmDecl>(Param));
1890 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00001891 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001892 }
1893
1894 if (!HasDefaultArg)
1895 break;
1896 }
1897 }
1898
1899 if (LastDeducibleArgument) {
1900 // Some of the function template arguments cannot be deduced from a
1901 // function call, so we introduce an explicit template argument list
1902 // containing all of the arguments up to the first deducible argument.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001903 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001904 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1905 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001906 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001907 }
1908
1909 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +00001910 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001911 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001912 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001913 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001914 return Result;
1915 }
1916
1917 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001918 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1919 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001920 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001921 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001922 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001923 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001924 return Result;
1925 }
1926
Douglas Gregord3c5d792009-11-17 16:44:22 +00001927 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00001928 Selector Sel = Method->getSelector();
1929 if (Sel.isUnarySelector()) {
1930 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1931 return Result;
1932 }
1933
Douglas Gregor1b605f72009-11-19 01:08:35 +00001934 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1935 SelName += ':';
1936 if (StartParameter == 0)
1937 Result->AddTypedTextChunk(SelName);
1938 else {
1939 Result->AddInformativeChunk(SelName);
1940
1941 // If there is only one parameter, and we're past it, add an empty
1942 // typed-text chunk since there is nothing to type.
1943 if (Method->param_size() == 1)
1944 Result->AddTypedTextChunk("");
1945 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00001946 unsigned Idx = 0;
1947 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1948 PEnd = Method->param_end();
1949 P != PEnd; (void)++P, ++Idx) {
1950 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001951 std::string Keyword;
1952 if (Idx > StartParameter)
Douglas Gregor6a803932010-01-12 06:38:28 +00001953 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001954 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1955 Keyword += II->getName().str();
1956 Keyword += ":";
Douglas Gregorc8537c52009-11-19 07:41:15 +00001957 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001958 Result->AddInformativeChunk(Keyword);
1959 } else if (Idx == StartParameter)
1960 Result->AddTypedTextChunk(Keyword);
1961 else
1962 Result->AddTextChunk(Keyword);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001963 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00001964
1965 // If we're before the starting parameter, skip the placeholder.
1966 if (Idx < StartParameter)
1967 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00001968
1969 std::string Arg;
1970 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1971 Arg = "(" + Arg + ")";
1972 if (IdentifierInfo *II = (*P)->getIdentifier())
1973 Arg += II->getName().str();
Douglas Gregorc8537c52009-11-19 07:41:15 +00001974 if (AllParametersAreInformative)
1975 Result->AddInformativeChunk(Arg);
1976 else
1977 Result->AddPlaceholderChunk(Arg);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001978 }
1979
Douglas Gregor04c5f972009-12-23 00:21:46 +00001980 if (Method->isVariadic()) {
1981 if (AllParametersAreInformative)
1982 Result->AddInformativeChunk(", ...");
1983 else
1984 Result->AddPlaceholderChunk(", ...");
1985 }
1986
Douglas Gregord3c5d792009-11-17 16:44:22 +00001987 return Result;
1988 }
1989
Douglas Gregorf09935f2009-12-01 05:55:20 +00001990 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00001991 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1992 S.Context);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001993
1994 Result->AddTypedTextChunk(ND->getNameAsString());
1995 return Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001996}
1997
Douglas Gregorf0f51982009-09-23 00:34:09 +00001998CodeCompletionString *
1999CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2000 unsigned CurrentArg,
2001 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002002 typedef CodeCompletionString::Chunk Chunk;
2003
Douglas Gregorf0f51982009-09-23 00:34:09 +00002004 CodeCompletionString *Result = new CodeCompletionString;
2005 FunctionDecl *FDecl = getFunction();
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002006 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002007 const FunctionProtoType *Proto
2008 = dyn_cast<FunctionProtoType>(getFunctionType());
2009 if (!FDecl && !Proto) {
2010 // Function without a prototype. Just give the return type and a
2011 // highlighted ellipsis.
2012 const FunctionType *FT = getFunctionType();
2013 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002014 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor9eb77012009-11-07 00:00:49 +00002015 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2016 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2017 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002018 return Result;
2019 }
2020
2021 if (FDecl)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002022 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregorf0f51982009-09-23 00:34:09 +00002023 else
2024 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002025 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002026
Douglas Gregor9eb77012009-11-07 00:00:49 +00002027 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002028 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2029 for (unsigned I = 0; I != NumParams; ++I) {
2030 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002031 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002032
2033 std::string ArgString;
2034 QualType ArgType;
2035
2036 if (FDecl) {
2037 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2038 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2039 } else {
2040 ArgType = Proto->getArgType(I);
2041 }
2042
2043 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2044
2045 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002046 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002047 ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002048 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002049 Result->AddTextChunk(ArgString);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002050 }
2051
2052 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002053 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002054 if (CurrentArg < NumParams)
2055 Result->AddTextChunk("...");
2056 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00002057 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002058 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00002059 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002060
2061 return Result;
2062}
2063
Douglas Gregor3545ff42009-09-21 16:56:56 +00002064namespace {
2065 struct SortCodeCompleteResult {
2066 typedef CodeCompleteConsumer::Result Result;
2067
Douglas Gregore6688e62009-09-28 03:51:44 +00002068 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor249d6822009-12-05 09:08:56 +00002069 Selector XSel = X.getObjCSelector();
2070 Selector YSel = Y.getObjCSelector();
2071 if (!XSel.isNull() && !YSel.isNull()) {
2072 // We are comparing two selectors.
2073 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2074 if (N == 0)
2075 ++N;
2076 for (unsigned I = 0; I != N; ++I) {
2077 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2078 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2079 if (!XId || !YId)
2080 return XId && !YId;
2081
2082 switch (XId->getName().compare_lower(YId->getName())) {
2083 case -1: return true;
2084 case 1: return false;
2085 default: break;
2086 }
2087 }
2088
2089 return XSel.getNumArgs() < YSel.getNumArgs();
2090 }
2091
2092 // For non-selectors, order by kind.
2093 if (X.getNameKind() != Y.getNameKind())
Douglas Gregore6688e62009-09-28 03:51:44 +00002094 return X.getNameKind() < Y.getNameKind();
2095
Douglas Gregor249d6822009-12-05 09:08:56 +00002096 // Order identifiers by comparison of their lowercased names.
2097 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2098 return XId->getName().compare_lower(
2099 Y.getAsIdentifierInfo()->getName()) < 0;
2100
2101 // Order overloaded operators by the order in which they appear
2102 // in our list of operators.
2103 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2104 return XOp < Y.getCXXOverloadedOperator();
2105
2106 // Order C++0x user-defined literal operators lexically by their
2107 // lowercased suffixes.
2108 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2109 return XLit->getName().compare_lower(
2110 Y.getCXXLiteralIdentifier()->getName()) < 0;
2111
2112 // The only stable ordering we have is to turn the name into a
2113 // string and then compare the lower-case strings. This is
2114 // inefficient, but thankfully does not happen too often.
Benjamin Kramer4053e5d2009-12-05 10:22:15 +00002115 return llvm::StringRef(X.getAsString()).compare_lower(
2116 Y.getAsString()) < 0;
Douglas Gregore6688e62009-09-28 03:51:44 +00002117 }
2118
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002119 /// \brief Retrieve the name that should be used to order a result.
2120 ///
2121 /// If the name needs to be constructed as a string, that string will be
2122 /// saved into Saved and the returned StringRef will refer to it.
2123 static llvm::StringRef getOrderedName(const Result &R,
2124 std::string &Saved) {
2125 switch (R.Kind) {
2126 case Result::RK_Keyword:
2127 return R.Keyword;
2128
2129 case Result::RK_Pattern:
2130 return R.Pattern->getTypedText();
2131
2132 case Result::RK_Macro:
2133 return R.Macro->getName();
2134
2135 case Result::RK_Declaration:
2136 // Handle declarations below.
2137 break;
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002138 }
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002139
2140 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002141
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002142 // If the name is a simple identifier (by far the common case), or a
2143 // zero-argument selector, just return a reference to that identifier.
2144 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2145 return Id->getName();
2146 if (Name.isObjCZeroArgSelector())
2147 if (IdentifierInfo *Id
2148 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2149 return Id->getName();
2150
2151 Saved = Name.getAsString();
2152 return Saved;
2153 }
2154
2155 bool operator()(const Result &X, const Result &Y) const {
2156 std::string XSaved, YSaved;
2157 llvm::StringRef XStr = getOrderedName(X, XSaved);
2158 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2159 int cmp = XStr.compare_lower(YStr);
2160 if (cmp)
2161 return cmp < 0;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002162
2163 // Non-hidden names precede hidden names.
2164 if (X.Hidden != Y.Hidden)
2165 return !X.Hidden;
2166
Douglas Gregore412a5a2009-09-23 22:26:46 +00002167 // Non-nested-name-specifiers precede nested-name-specifiers.
2168 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2169 return !X.StartsNestedNameSpecifier;
2170
Douglas Gregor3545ff42009-09-21 16:56:56 +00002171 return false;
2172 }
2173 };
2174}
2175
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002176static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002177 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002178 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2179 MEnd = PP.macro_end();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002180 M != MEnd; ++M)
Douglas Gregor78a21012010-01-14 16:01:26 +00002181 Results.AddResult(M->first);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002182 Results.ExitScope();
2183}
2184
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002185static void HandleCodeCompleteResults(Sema *S,
2186 CodeCompleteConsumer *CodeCompleter,
2187 CodeCompleteConsumer::Result *Results,
2188 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002189 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2190
2191 if (CodeCompleter)
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002192 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002193
2194 for (unsigned I = 0; I != NumResults; ++I)
2195 Results[I].Destroy();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002196}
2197
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002198void Sema::CodeCompleteOrdinaryName(Scope *S,
2199 CodeCompletionContext CompletionContext) {
Douglas Gregor92253692009-12-07 09:54:55 +00002200 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002201 ResultBuilder Results(*this);
2202
2203 // Determine how to filter results, e.g., so that the names of
2204 // values (functions, enumerators, function templates, etc.) are
2205 // only allowed where we can have an expression.
2206 switch (CompletionContext) {
2207 case CCC_Namespace:
2208 case CCC_Class:
Douglas Gregorf1934162010-01-13 21:24:21 +00002209 case CCC_ObjCInterface:
2210 case CCC_ObjCImplementation:
Douglas Gregor48d46252010-01-13 21:54:15 +00002211 case CCC_ObjCInstanceVariableList:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002212 case CCC_Template:
2213 case CCC_MemberTemplate:
2214 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2215 break;
2216
2217 case CCC_Expression:
2218 case CCC_Statement:
2219 case CCC_ForInit:
2220 case CCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00002221 if (WantTypesInContext(CompletionContext, getLangOptions()))
2222 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2223 else
2224 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002225 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00002226
2227 case CCC_RecoveryInFunction:
2228 // Unfiltered
2229 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002230 }
2231
Douglas Gregorc580c522010-01-14 01:09:38 +00002232 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2233 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor92253692009-12-07 09:54:55 +00002234
2235 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002236 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00002237 Results.ExitScope();
2238
Douglas Gregor9eb77012009-11-07 00:00:49 +00002239 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002240 AddMacroResults(PP, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002241 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00002242}
2243
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002244/// \brief Perform code-completion in an expression context when we know what
2245/// type we're looking for.
2246void Sema::CodeCompleteExpression(Scope *S, QualType T) {
2247 typedef CodeCompleteConsumer::Result Result;
2248 ResultBuilder Results(*this);
2249
2250 if (WantTypesInContext(CCC_Expression, getLangOptions()))
2251 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2252 else
2253 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2254 Results.setPreferredType(T.getNonReferenceType());
2255
2256 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2257 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2258
2259 Results.EnterNewScope();
2260 AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
2261 Results.ExitScope();
2262
2263 if (CodeCompleter->includeMacros())
2264 AddMacroResults(PP, Results);
2265 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2266}
2267
2268
Douglas Gregor9291bad2009-11-18 01:29:26 +00002269static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00002270 bool AllowCategories,
Douglas Gregor9291bad2009-11-18 01:29:26 +00002271 DeclContext *CurContext,
2272 ResultBuilder &Results) {
2273 typedef CodeCompleteConsumer::Result Result;
2274
2275 // Add properties in this container.
2276 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2277 PEnd = Container->prop_end();
2278 P != PEnd;
2279 ++P)
2280 Results.MaybeAddResult(Result(*P, 0), CurContext);
2281
2282 // Add properties in referenced protocols.
2283 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2284 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2285 PEnd = Protocol->protocol_end();
2286 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002287 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002288 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00002289 if (AllowCategories) {
2290 // Look through categories.
2291 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2292 Category; Category = Category->getNextClassCategory())
2293 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2294 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002295
2296 // Look through protocols.
2297 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2298 E = IFace->protocol_end();
2299 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002300 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002301
2302 // Look in the superclass.
2303 if (IFace->getSuperClass())
Douglas Gregor5d649882009-11-18 22:32:06 +00002304 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2305 Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002306 } else if (const ObjCCategoryDecl *Category
2307 = dyn_cast<ObjCCategoryDecl>(Container)) {
2308 // Look through protocols.
2309 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2310 PEnd = Category->protocol_end();
2311 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002312 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002313 }
2314}
2315
Douglas Gregor2436e712009-09-17 21:32:03 +00002316void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2317 SourceLocation OpLoc,
2318 bool IsArrow) {
2319 if (!BaseE || !CodeCompleter)
2320 return;
2321
Douglas Gregor3545ff42009-09-21 16:56:56 +00002322 typedef CodeCompleteConsumer::Result Result;
2323
Douglas Gregor2436e712009-09-17 21:32:03 +00002324 Expr *Base = static_cast<Expr *>(BaseE);
2325 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002326
2327 if (IsArrow) {
2328 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2329 BaseType = Ptr->getPointeeType();
2330 else if (BaseType->isObjCObjectPointerType())
2331 /*Do nothing*/ ;
2332 else
2333 return;
2334 }
2335
Douglas Gregore412a5a2009-09-23 22:26:46 +00002336 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002337 Results.EnterNewScope();
2338 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2339 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002340 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00002341 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2342 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002343
Douglas Gregor9291bad2009-11-18 01:29:26 +00002344 if (getLangOptions().CPlusPlus) {
2345 if (!Results.empty()) {
2346 // The "template" keyword can follow "->" or "." in the grammar.
2347 // However, we only want to suggest the template keyword if something
2348 // is dependent.
2349 bool IsDependent = BaseType->isDependentType();
2350 if (!IsDependent) {
2351 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2352 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2353 IsDependent = Ctx->isDependentContext();
2354 break;
2355 }
2356 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002357
Douglas Gregor9291bad2009-11-18 01:29:26 +00002358 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00002359 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002360 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002361 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002362 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2363 // Objective-C property reference.
2364
2365 // Add property results based on our interface.
2366 const ObjCObjectPointerType *ObjCPtr
2367 = BaseType->getAsObjCInterfacePointerType();
2368 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor5d649882009-11-18 22:32:06 +00002369 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002370
2371 // Add properties from the protocols in a qualified interface.
2372 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2373 E = ObjCPtr->qual_end();
2374 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002375 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002376 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00002377 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00002378 // Objective-C instance variable access.
2379 ObjCInterfaceDecl *Class = 0;
2380 if (const ObjCObjectPointerType *ObjCPtr
2381 = BaseType->getAs<ObjCObjectPointerType>())
2382 Class = ObjCPtr->getInterfaceDecl();
2383 else
John McCall8b07ec22010-05-15 11:32:37 +00002384 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00002385
2386 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00002387 if (Class) {
2388 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2389 Results.setFilter(&ResultBuilder::IsObjCIvar);
2390 LookupVisibleDecls(Class, LookupMemberName, Consumer);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002391 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002392 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002393
2394 // FIXME: How do we cope with isa?
2395
2396 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002397
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002398 // Hand off the results found for code completion.
2399 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002400}
2401
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002402void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2403 if (!CodeCompleter)
2404 return;
2405
Douglas Gregor3545ff42009-09-21 16:56:56 +00002406 typedef CodeCompleteConsumer::Result Result;
2407 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002408 switch ((DeclSpec::TST)TagSpec) {
2409 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002410 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002411 break;
2412
2413 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002414 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002415 break;
2416
2417 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002418 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002419 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002420 break;
2421
2422 default:
2423 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2424 return;
2425 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002426
John McCalle87beb22010-04-23 18:46:30 +00002427 ResultBuilder Results(*this);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002428 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00002429
2430 // First pass: look for tags.
2431 Results.setFilter(Filter);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002432 LookupVisibleDecls(S, LookupTagName, Consumer);
John McCalle87beb22010-04-23 18:46:30 +00002433
2434 // Second pass: look for nested name specifiers.
2435 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2436 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002437
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002438 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002439}
2440
Douglas Gregord328d572009-09-21 18:10:23 +00002441void Sema::CodeCompleteCase(Scope *S) {
2442 if (getSwitchStack().empty() || !CodeCompleter)
2443 return;
2444
2445 SwitchStmt *Switch = getSwitchStack().back();
2446 if (!Switch->getCond()->getType()->isEnumeralType())
2447 return;
2448
2449 // Code-complete the cases of a switch statement over an enumeration type
2450 // by providing the list of
2451 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2452
2453 // Determine which enumerators we have already seen in the switch statement.
2454 // FIXME: Ideally, we would also be able to look *past* the code-completion
2455 // token, in case we are code-completing in the middle of the switch and not
2456 // at the end. However, we aren't able to do so at the moment.
2457 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00002458 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00002459 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2460 SC = SC->getNextSwitchCase()) {
2461 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2462 if (!Case)
2463 continue;
2464
2465 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2466 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2467 if (EnumConstantDecl *Enumerator
2468 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2469 // We look into the AST of the case statement to determine which
2470 // enumerator was named. Alternatively, we could compute the value of
2471 // the integral constant expression, then compare it against the
2472 // values of each enumerator. However, value-based approach would not
2473 // work as well with C++ templates where enumerators declared within a
2474 // template are type- and value-dependent.
2475 EnumeratorsSeen.insert(Enumerator);
2476
Douglas Gregorf2510672009-09-21 19:57:38 +00002477 // If this is a qualified-id, keep track of the nested-name-specifier
2478 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00002479 //
2480 // switch (TagD.getKind()) {
2481 // case TagDecl::TK_enum:
2482 // break;
2483 // case XXX
2484 //
Douglas Gregorf2510672009-09-21 19:57:38 +00002485 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00002486 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2487 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002488 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00002489 }
2490 }
2491
Douglas Gregorf2510672009-09-21 19:57:38 +00002492 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2493 // If there are no prior enumerators in C++, check whether we have to
2494 // qualify the names of the enumerators that we suggest, because they
2495 // may not be visible in this scope.
2496 Qualifier = getRequiredQualification(Context, CurContext,
2497 Enum->getDeclContext());
2498
2499 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2500 }
2501
Douglas Gregord328d572009-09-21 18:10:23 +00002502 // Add any enumerators that have not yet been mentioned.
2503 ResultBuilder Results(*this);
2504 Results.EnterNewScope();
2505 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2506 EEnd = Enum->enumerator_end();
2507 E != EEnd; ++E) {
2508 if (EnumeratorsSeen.count(*E))
2509 continue;
2510
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002511 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2512 CurContext, 0, false);
Douglas Gregord328d572009-09-21 18:10:23 +00002513 }
2514 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00002515
Douglas Gregor9eb77012009-11-07 00:00:49 +00002516 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002517 AddMacroResults(PP, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002518 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00002519}
2520
Douglas Gregorcabea402009-09-22 15:41:20 +00002521namespace {
2522 struct IsBetterOverloadCandidate {
2523 Sema &S;
John McCallbc077cf2010-02-08 23:07:23 +00002524 SourceLocation Loc;
Douglas Gregorcabea402009-09-22 15:41:20 +00002525
2526 public:
John McCallbc077cf2010-02-08 23:07:23 +00002527 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2528 : S(S), Loc(Loc) { }
Douglas Gregorcabea402009-09-22 15:41:20 +00002529
2530 bool
2531 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCallbc077cf2010-02-08 23:07:23 +00002532 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregorcabea402009-09-22 15:41:20 +00002533 }
2534 };
2535}
2536
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002537static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2538 if (NumArgs && !Args)
2539 return true;
2540
2541 for (unsigned I = 0; I != NumArgs; ++I)
2542 if (!Args[I])
2543 return true;
2544
2545 return false;
2546}
2547
Douglas Gregorcabea402009-09-22 15:41:20 +00002548void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2549 ExprTy **ArgsIn, unsigned NumArgs) {
2550 if (!CodeCompleter)
2551 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002552
2553 // When we're code-completing for a call, we fall back to ordinary
2554 // name code-completion whenever we can't produce specific
2555 // results. We may want to revisit this strategy in the future,
2556 // e.g., by merging the two kinds of results.
2557
Douglas Gregorcabea402009-09-22 15:41:20 +00002558 Expr *Fn = (Expr *)FnIn;
2559 Expr **Args = (Expr **)ArgsIn;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002560
Douglas Gregorcabea402009-09-22 15:41:20 +00002561 // Ignore type-dependent call expressions entirely.
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002562 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregor3ef59522009-12-11 19:06:04 +00002563 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002564 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00002565 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002566 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002567
John McCall57500772009-12-16 12:17:52 +00002568 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00002569 SourceLocation Loc = Fn->getExprLoc();
2570 OverloadCandidateSet CandidateSet(Loc);
John McCall57500772009-12-16 12:17:52 +00002571
Douglas Gregorcabea402009-09-22 15:41:20 +00002572 // FIXME: What if we're calling something that isn't a function declaration?
2573 // FIXME: What if we're calling a pseudo-destructor?
2574 // FIXME: What if we're calling a member function?
2575
Douglas Gregorff59f672010-01-21 15:46:19 +00002576 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2577 llvm::SmallVector<ResultCandidate, 8> Results;
2578
John McCall57500772009-12-16 12:17:52 +00002579 Expr *NakedFn = Fn->IgnoreParenCasts();
2580 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2581 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2582 /*PartialOverloading=*/ true);
2583 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2584 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorff59f672010-01-21 15:46:19 +00002585 if (FDecl) {
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002586 if (!getLangOptions().CPlusPlus ||
2587 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorff59f672010-01-21 15:46:19 +00002588 Results.push_back(ResultCandidate(FDecl));
2589 else
John McCallb89836b2010-01-26 01:37:31 +00002590 // FIXME: access?
John McCalla0296f72010-03-19 07:35:19 +00002591 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2592 Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002593 false, /*PartialOverloading*/true);
Douglas Gregorff59f672010-01-21 15:46:19 +00002594 }
John McCall57500772009-12-16 12:17:52 +00002595 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002596
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002597 QualType ParamType;
2598
Douglas Gregorff59f672010-01-21 15:46:19 +00002599 if (!CandidateSet.empty()) {
2600 // Sort the overload candidate set by placing the best overloads first.
2601 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCallbc077cf2010-02-08 23:07:23 +00002602 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregorcabea402009-09-22 15:41:20 +00002603
Douglas Gregorff59f672010-01-21 15:46:19 +00002604 // Add the remaining viable overload candidates as code-completion reslults.
2605 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2606 CandEnd = CandidateSet.end();
2607 Cand != CandEnd; ++Cand) {
2608 if (Cand->Viable)
2609 Results.push_back(ResultCandidate(Cand->Function));
2610 }
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002611
2612 // From the viable candidates, try to determine the type of this parameter.
2613 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2614 if (const FunctionType *FType = Results[I].getFunctionType())
2615 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2616 if (NumArgs < Proto->getNumArgs()) {
2617 if (ParamType.isNull())
2618 ParamType = Proto->getArgType(NumArgs);
2619 else if (!Context.hasSameUnqualifiedType(
2620 ParamType.getNonReferenceType(),
2621 Proto->getArgType(NumArgs).getNonReferenceType())) {
2622 ParamType = QualType();
2623 break;
2624 }
2625 }
2626 }
2627 } else {
2628 // Try to determine the parameter type from the type of the expression
2629 // being called.
2630 QualType FunctionType = Fn->getType();
2631 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2632 FunctionType = Ptr->getPointeeType();
2633 else if (const BlockPointerType *BlockPtr
2634 = FunctionType->getAs<BlockPointerType>())
2635 FunctionType = BlockPtr->getPointeeType();
2636 else if (const MemberPointerType *MemPtr
2637 = FunctionType->getAs<MemberPointerType>())
2638 FunctionType = MemPtr->getPointeeType();
2639
2640 if (const FunctionProtoType *Proto
2641 = FunctionType->getAs<FunctionProtoType>()) {
2642 if (NumArgs < Proto->getNumArgs())
2643 ParamType = Proto->getArgType(NumArgs);
2644 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002645 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00002646
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002647 if (ParamType.isNull())
2648 CodeCompleteOrdinaryName(S, CCC_Expression);
2649 else
2650 CodeCompleteExpression(S, ParamType);
2651
Douglas Gregorc01890e2010-04-06 20:19:47 +00002652 if (!Results.empty())
Douglas Gregor3ef59522009-12-11 19:06:04 +00002653 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2654 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00002655}
2656
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002657void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2658 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2659 if (!VD) {
2660 CodeCompleteOrdinaryName(S, CCC_Expression);
2661 return;
2662 }
2663
2664 CodeCompleteExpression(S, VD->getType());
2665}
2666
2667void Sema::CodeCompleteReturn(Scope *S) {
2668 QualType ResultType;
2669 if (isa<BlockDecl>(CurContext)) {
2670 if (BlockScopeInfo *BSI = getCurBlock())
2671 ResultType = BSI->ReturnType;
2672 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2673 ResultType = Function->getResultType();
2674 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2675 ResultType = Method->getResultType();
2676
2677 if (ResultType.isNull())
2678 CodeCompleteOrdinaryName(S, CCC_Expression);
2679 else
2680 CodeCompleteExpression(S, ResultType);
2681}
2682
2683void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2684 if (LHS)
2685 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2686 else
2687 CodeCompleteOrdinaryName(S, CCC_Expression);
2688}
2689
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002690void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00002691 bool EnteringContext) {
2692 if (!SS.getScopeRep() || !CodeCompleter)
2693 return;
2694
Douglas Gregor3545ff42009-09-21 16:56:56 +00002695 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2696 if (!Ctx)
2697 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00002698
2699 // Try to instantiate any non-dependent declaration contexts before
2700 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00002701 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00002702 return;
2703
Douglas Gregor3545ff42009-09-21 16:56:56 +00002704 ResultBuilder Results(*this);
Douglas Gregor200c99d2010-01-14 03:35:48 +00002705 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2706 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002707
2708 // The "template" keyword can follow "::" in the grammar, but only
2709 // put it into the grammar if the nested-name-specifier is dependent.
2710 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2711 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00002712 Results.AddResult("template");
Douglas Gregor3545ff42009-09-21 16:56:56 +00002713
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002714 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002715}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002716
2717void Sema::CodeCompleteUsing(Scope *S) {
2718 if (!CodeCompleter)
2719 return;
2720
Douglas Gregor3545ff42009-09-21 16:56:56 +00002721 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002722 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002723
2724 // If we aren't in class scope, we could see the "namespace" keyword.
2725 if (!S->isClassScope())
Douglas Gregor78a21012010-01-14 16:01:26 +00002726 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002727
2728 // After "using", we can see anything that would start a
2729 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002730 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2731 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002732 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002733
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002734 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002735}
2736
2737void Sema::CodeCompleteUsingDirective(Scope *S) {
2738 if (!CodeCompleter)
2739 return;
2740
Douglas Gregor3545ff42009-09-21 16:56:56 +00002741 // After "using namespace", we expect to see a namespace name or namespace
2742 // alias.
2743 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002744 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002745 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2746 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002747 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002748 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002749}
2750
2751void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2752 if (!CodeCompleter)
2753 return;
2754
Douglas Gregor3545ff42009-09-21 16:56:56 +00002755 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2756 DeclContext *Ctx = (DeclContext *)S->getEntity();
2757 if (!S->getParent())
2758 Ctx = Context.getTranslationUnitDecl();
2759
2760 if (Ctx && Ctx->isFileContext()) {
2761 // We only want to see those namespaces that have already been defined
2762 // within this scope, because its likely that the user is creating an
2763 // extended namespace declaration. Keep track of the most recent
2764 // definition of each namespace.
2765 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2766 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2767 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2768 NS != NSEnd; ++NS)
2769 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2770
2771 // Add the most recent definition (or extended definition) of each
2772 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00002773 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002774 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2775 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2776 NS != NSEnd; ++NS)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002777 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2778 CurContext, 0, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002779 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002780 }
2781
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002782 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002783}
2784
2785void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2786 if (!CodeCompleter)
2787 return;
2788
Douglas Gregor3545ff42009-09-21 16:56:56 +00002789 // After "namespace", we expect to see a namespace or alias.
2790 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002791 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2792 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002793 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002794}
2795
Douglas Gregorc811ede2009-09-18 20:05:18 +00002796void Sema::CodeCompleteOperatorName(Scope *S) {
2797 if (!CodeCompleter)
2798 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002799
2800 typedef CodeCompleteConsumer::Result Result;
2801 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002802 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00002803
Douglas Gregor3545ff42009-09-21 16:56:56 +00002804 // Add the names of overloadable operators.
2805#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2806 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00002807 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002808#include "clang/Basic/OperatorKinds.def"
2809
2810 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002811 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002812 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2813 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002814
2815 // Add any type specifiers
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002816 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002817 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002818
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002819 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00002820}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002821
Douglas Gregorf1934162010-01-13 21:24:21 +00002822// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2823// true or false.
2824#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002825static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002826 ResultBuilder &Results,
2827 bool NeedAt) {
2828 typedef CodeCompleteConsumer::Result Result;
2829 // Since we have an implementation, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002830 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002831
2832 CodeCompletionString *Pattern = 0;
2833 if (LangOpts.ObjC2) {
2834 // @dynamic
2835 Pattern = new CodeCompletionString;
2836 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2837 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2838 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002839 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002840
2841 // @synthesize
2842 Pattern = new CodeCompletionString;
2843 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2844 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2845 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002846 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002847 }
2848}
2849
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002850static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002851 ResultBuilder &Results,
2852 bool NeedAt) {
2853 typedef CodeCompleteConsumer::Result Result;
2854
2855 // Since we have an interface or protocol, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002856 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002857
2858 if (LangOpts.ObjC2) {
2859 // @property
Douglas Gregor78a21012010-01-14 16:01:26 +00002860 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002861
2862 // @required
Douglas Gregor78a21012010-01-14 16:01:26 +00002863 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002864
2865 // @optional
Douglas Gregor78a21012010-01-14 16:01:26 +00002866 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002867 }
2868}
2869
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002870static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00002871 typedef CodeCompleteConsumer::Result Result;
2872 CodeCompletionString *Pattern = 0;
2873
2874 // @class name ;
2875 Pattern = new CodeCompletionString;
2876 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2877 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00002878 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00002879 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002880
Douglas Gregorf4c33342010-05-28 00:22:41 +00002881 if (Results.includeCodePatterns()) {
2882 // @interface name
2883 // FIXME: Could introduce the whole pattern, including superclasses and
2884 // such.
2885 Pattern = new CodeCompletionString;
2886 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2887 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2888 Pattern->AddPlaceholderChunk("class");
2889 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002890
Douglas Gregorf4c33342010-05-28 00:22:41 +00002891 // @protocol name
2892 Pattern = new CodeCompletionString;
2893 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2894 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2895 Pattern->AddPlaceholderChunk("protocol");
2896 Results.AddResult(Result(Pattern));
2897
2898 // @implementation name
2899 Pattern = new CodeCompletionString;
2900 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2901 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2902 Pattern->AddPlaceholderChunk("class");
2903 Results.AddResult(Result(Pattern));
2904 }
Douglas Gregorf1934162010-01-13 21:24:21 +00002905
2906 // @compatibility_alias name
2907 Pattern = new CodeCompletionString;
2908 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2909 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2910 Pattern->AddPlaceholderChunk("alias");
2911 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2912 Pattern->AddPlaceholderChunk("class");
Douglas Gregor78a21012010-01-14 16:01:26 +00002913 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002914}
2915
Douglas Gregorf48706c2009-12-07 09:27:33 +00002916void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2917 bool InInterface) {
2918 typedef CodeCompleteConsumer::Result Result;
2919 ResultBuilder Results(*this);
2920 Results.EnterNewScope();
Douglas Gregorf1934162010-01-13 21:24:21 +00002921 if (ObjCImpDecl)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002922 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00002923 else if (InInterface)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002924 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00002925 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002926 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00002927 Results.ExitScope();
2928 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2929}
2930
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002931static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002932 typedef CodeCompleteConsumer::Result Result;
2933 CodeCompletionString *Pattern = 0;
2934
2935 // @encode ( type-name )
2936 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002937 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002938 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2939 Pattern->AddPlaceholderChunk("type-name");
2940 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002941 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002942
2943 // @protocol ( protocol-name )
2944 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002945 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002946 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2947 Pattern->AddPlaceholderChunk("protocol-name");
2948 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002949 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002950
2951 // @selector ( selector )
2952 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002953 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002954 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2955 Pattern->AddPlaceholderChunk("selector");
2956 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002957 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002958}
2959
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002960static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002961 typedef CodeCompleteConsumer::Result Result;
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002962 CodeCompletionString *Pattern = 0;
Douglas Gregorf1934162010-01-13 21:24:21 +00002963
Douglas Gregorf4c33342010-05-28 00:22:41 +00002964 if (Results.includeCodePatterns()) {
2965 // @try { statements } @catch ( declaration ) { statements } @finally
2966 // { statements }
2967 Pattern = new CodeCompletionString;
2968 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2969 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2970 Pattern->AddPlaceholderChunk("statements");
2971 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2972 Pattern->AddTextChunk("@catch");
2973 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2974 Pattern->AddPlaceholderChunk("parameter");
2975 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2976 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2977 Pattern->AddPlaceholderChunk("statements");
2978 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2979 Pattern->AddTextChunk("@finally");
2980 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2981 Pattern->AddPlaceholderChunk("statements");
2982 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2983 Results.AddResult(Result(Pattern));
2984 }
Douglas Gregorf1934162010-01-13 21:24:21 +00002985
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002986 // @throw
2987 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002988 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor6a803932010-01-12 06:38:28 +00002989 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002990 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor78a21012010-01-14 16:01:26 +00002991 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002992
Douglas Gregorf4c33342010-05-28 00:22:41 +00002993 if (Results.includeCodePatterns()) {
2994 // @synchronized ( expression ) { statements }
2995 Pattern = new CodeCompletionString;
2996 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
2997 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2998 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2999 Pattern->AddPlaceholderChunk("expression");
3000 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3001 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3002 Pattern->AddPlaceholderChunk("statements");
3003 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3004 Results.AddResult(Result(Pattern));
3005 }
Douglas Gregorf1934162010-01-13 21:24:21 +00003006}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003007
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003008static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00003009 ResultBuilder &Results,
3010 bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003011 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor78a21012010-01-14 16:01:26 +00003012 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3013 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3014 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003015 if (LangOpts.ObjC2)
Douglas Gregor78a21012010-01-14 16:01:26 +00003016 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003017}
3018
3019void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3020 ResultBuilder Results(*this);
3021 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003022 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00003023 Results.ExitScope();
3024 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3025}
3026
3027void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003028 ResultBuilder Results(*this);
3029 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003030 AddObjCStatementResults(Results, false);
3031 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003032 Results.ExitScope();
3033 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3034}
3035
3036void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3037 ResultBuilder Results(*this);
3038 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003039 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003040 Results.ExitScope();
3041 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3042}
3043
Douglas Gregore6078da2009-11-19 00:14:45 +00003044/// \brief Determine whether the addition of the given flag to an Objective-C
3045/// property's attributes will cause a conflict.
3046static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3047 // Check if we've already added this flag.
3048 if (Attributes & NewFlag)
3049 return true;
3050
3051 Attributes |= NewFlag;
3052
3053 // Check for collisions with "readonly".
3054 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3055 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3056 ObjCDeclSpec::DQ_PR_assign |
3057 ObjCDeclSpec::DQ_PR_copy |
3058 ObjCDeclSpec::DQ_PR_retain)))
3059 return true;
3060
3061 // Check for more than one of { assign, copy, retain }.
3062 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3063 ObjCDeclSpec::DQ_PR_copy |
3064 ObjCDeclSpec::DQ_PR_retain);
3065 if (AssignCopyRetMask &&
3066 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3067 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3068 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3069 return true;
3070
3071 return false;
3072}
3073
Douglas Gregor36029f42009-11-18 23:08:07 +00003074void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00003075 if (!CodeCompleter)
3076 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00003077
Steve Naroff936354c2009-10-08 21:55:05 +00003078 unsigned Attributes = ODS.getPropertyAttributes();
3079
3080 typedef CodeCompleteConsumer::Result Result;
3081 ResultBuilder Results(*this);
3082 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00003083 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregor78a21012010-01-14 16:01:26 +00003084 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003085 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregor78a21012010-01-14 16:01:26 +00003086 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003087 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregor78a21012010-01-14 16:01:26 +00003088 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003089 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregor78a21012010-01-14 16:01:26 +00003090 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003091 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregor78a21012010-01-14 16:01:26 +00003092 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003093 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregor78a21012010-01-14 16:01:26 +00003094 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003095 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003096 CodeCompletionString *Setter = new CodeCompletionString;
3097 Setter->AddTypedTextChunk("setter");
3098 Setter->AddTextChunk(" = ");
3099 Setter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003100 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003101 }
Douglas Gregore6078da2009-11-19 00:14:45 +00003102 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003103 CodeCompletionString *Getter = new CodeCompletionString;
3104 Getter->AddTypedTextChunk("getter");
3105 Getter->AddTextChunk(" = ");
3106 Getter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003107 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003108 }
Steve Naroff936354c2009-10-08 21:55:05 +00003109 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003110 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00003111}
Steve Naroffeae65032009-11-07 02:08:14 +00003112
Douglas Gregorc8537c52009-11-19 07:41:15 +00003113/// \brief Descripts the kind of Objective-C method that we want to find
3114/// via code completion.
3115enum ObjCMethodKind {
3116 MK_Any, //< Any kind of method, provided it means other specified criteria.
3117 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3118 MK_OneArgSelector //< One-argument selector.
3119};
3120
3121static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3122 ObjCMethodKind WantKind,
3123 IdentifierInfo **SelIdents,
3124 unsigned NumSelIdents) {
3125 Selector Sel = Method->getSelector();
3126 if (NumSelIdents > Sel.getNumArgs())
3127 return false;
3128
3129 switch (WantKind) {
3130 case MK_Any: break;
3131 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3132 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3133 }
3134
3135 for (unsigned I = 0; I != NumSelIdents; ++I)
3136 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3137 return false;
3138
3139 return true;
3140}
3141
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003142/// \brief Add all of the Objective-C methods in the given Objective-C
3143/// container to the set of results.
3144///
3145/// The container will be a class, protocol, category, or implementation of
3146/// any of the above. This mether will recurse to include methods from
3147/// the superclasses of classes along with their categories, protocols, and
3148/// implementations.
3149///
3150/// \param Container the container in which we'll look to find methods.
3151///
3152/// \param WantInstance whether to add instance methods (only); if false, this
3153/// routine will add factory methods (only).
3154///
3155/// \param CurContext the context in which we're performing the lookup that
3156/// finds methods.
3157///
3158/// \param Results the structure into which we'll add results.
3159static void AddObjCMethods(ObjCContainerDecl *Container,
3160 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00003161 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003162 IdentifierInfo **SelIdents,
3163 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003164 DeclContext *CurContext,
3165 ResultBuilder &Results) {
3166 typedef CodeCompleteConsumer::Result Result;
3167 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3168 MEnd = Container->meth_end();
3169 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00003170 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3171 // Check whether the selector identifiers we've been given are a
3172 // subset of the identifiers for this particular method.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003173 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregor1b605f72009-11-19 01:08:35 +00003174 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003175
Douglas Gregor1b605f72009-11-19 01:08:35 +00003176 Result R = Result(*M, 0);
3177 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003178 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor1b605f72009-11-19 01:08:35 +00003179 Results.MaybeAddResult(R, CurContext);
3180 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003181 }
3182
3183 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3184 if (!IFace)
3185 return;
3186
3187 // Add methods in protocols.
3188 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3189 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3190 E = Protocols.end();
3191 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003192 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003193 CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003194
3195 // Add methods in categories.
3196 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3197 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00003198 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3199 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003200
3201 // Add a categories protocol methods.
3202 const ObjCList<ObjCProtocolDecl> &Protocols
3203 = CatDecl->getReferencedProtocols();
3204 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3205 E = Protocols.end();
3206 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003207 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3208 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003209
3210 // Add methods in category implementations.
3211 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003212 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3213 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003214 }
3215
3216 // Add methods in superclass.
3217 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003218 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3219 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003220
3221 // Add methods in our implementation, if any.
3222 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003223 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3224 NumSelIdents, CurContext, Results);
3225}
3226
3227
3228void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3229 DeclPtrTy *Methods,
3230 unsigned NumMethods) {
3231 typedef CodeCompleteConsumer::Result Result;
3232
3233 // Try to find the interface where getters might live.
3234 ObjCInterfaceDecl *Class
3235 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3236 if (!Class) {
3237 if (ObjCCategoryDecl *Category
3238 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3239 Class = Category->getClassInterface();
3240
3241 if (!Class)
3242 return;
3243 }
3244
3245 // Find all of the potential getters.
3246 ResultBuilder Results(*this);
3247 Results.EnterNewScope();
3248
3249 // FIXME: We need to do this because Objective-C methods don't get
3250 // pushed into DeclContexts early enough. Argh!
3251 for (unsigned I = 0; I != NumMethods; ++I) {
3252 if (ObjCMethodDecl *Method
3253 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3254 if (Method->isInstanceMethod() &&
3255 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3256 Result R = Result(Method, 0);
3257 R.AllParametersAreInformative = true;
3258 Results.MaybeAddResult(R, CurContext);
3259 }
3260 }
3261
3262 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3263 Results.ExitScope();
3264 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3265}
3266
3267void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3268 DeclPtrTy *Methods,
3269 unsigned NumMethods) {
3270 typedef CodeCompleteConsumer::Result Result;
3271
3272 // Try to find the interface where setters might live.
3273 ObjCInterfaceDecl *Class
3274 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3275 if (!Class) {
3276 if (ObjCCategoryDecl *Category
3277 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3278 Class = Category->getClassInterface();
3279
3280 if (!Class)
3281 return;
3282 }
3283
3284 // Find all of the potential getters.
3285 ResultBuilder Results(*this);
3286 Results.EnterNewScope();
3287
3288 // FIXME: We need to do this because Objective-C methods don't get
3289 // pushed into DeclContexts early enough. Argh!
3290 for (unsigned I = 0; I != NumMethods; ++I) {
3291 if (ObjCMethodDecl *Method
3292 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3293 if (Method->isInstanceMethod() &&
3294 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3295 Result R = Result(Method, 0);
3296 R.AllParametersAreInformative = true;
3297 Results.MaybeAddResult(R, CurContext);
3298 }
3299 }
3300
3301 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3302
3303 Results.ExitScope();
3304 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003305}
3306
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003307/// \brief When we have an expression with type "id", we may assume
3308/// that it has some more-specific class type based on knowledge of
3309/// common uses of Objective-C. This routine returns that class type,
3310/// or NULL if no better result could be determined.
3311static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3312 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3313 if (!Msg)
3314 return 0;
3315
3316 Selector Sel = Msg->getSelector();
3317 if (Sel.isNull())
3318 return 0;
3319
3320 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3321 if (!Id)
3322 return 0;
3323
3324 ObjCMethodDecl *Method = Msg->getMethodDecl();
3325 if (!Method)
3326 return 0;
3327
3328 // Determine the class that we're sending the message to.
Douglas Gregor9a129192010-04-21 00:45:42 +00003329 ObjCInterfaceDecl *IFace = 0;
3330 switch (Msg->getReceiverKind()) {
3331 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00003332 if (const ObjCObjectType *ObjType
3333 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3334 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00003335 break;
3336
3337 case ObjCMessageExpr::Instance: {
3338 QualType T = Msg->getInstanceReceiver()->getType();
3339 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3340 IFace = Ptr->getInterfaceDecl();
3341 break;
3342 }
3343
3344 case ObjCMessageExpr::SuperInstance:
3345 case ObjCMessageExpr::SuperClass:
3346 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003347 }
3348
3349 if (!IFace)
3350 return 0;
3351
3352 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3353 if (Method->isInstanceMethod())
3354 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3355 .Case("retain", IFace)
3356 .Case("autorelease", IFace)
3357 .Case("copy", IFace)
3358 .Case("copyWithZone", IFace)
3359 .Case("mutableCopy", IFace)
3360 .Case("mutableCopyWithZone", IFace)
3361 .Case("awakeFromCoder", IFace)
3362 .Case("replacementObjectFromCoder", IFace)
3363 .Case("class", IFace)
3364 .Case("classForCoder", IFace)
3365 .Case("superclass", Super)
3366 .Default(0);
3367
3368 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3369 .Case("new", IFace)
3370 .Case("alloc", IFace)
3371 .Case("allocWithZone", IFace)
3372 .Case("class", IFace)
3373 .Case("superclass", Super)
3374 .Default(0);
3375}
3376
Douglas Gregora817a192010-05-27 23:06:34 +00003377void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3378 typedef CodeCompleteConsumer::Result Result;
3379 ResultBuilder Results(*this);
3380
3381 // Find anything that looks like it could be a message receiver.
3382 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3383 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3384 Results.EnterNewScope();
3385 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
3386
3387 // If we are in an Objective-C method inside a class that has a superclass,
3388 // add "super" as an option.
3389 if (ObjCMethodDecl *Method = getCurMethodDecl())
3390 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3391 if (Iface->getSuperClass())
3392 Results.AddResult(Result("super"));
3393
3394 Results.ExitScope();
3395
3396 if (CodeCompleter->includeMacros())
3397 AddMacroResults(PP, Results);
3398 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3399
3400}
3401
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003402void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3403 IdentifierInfo **SelIdents,
3404 unsigned NumSelIdents) {
3405 ObjCInterfaceDecl *CDecl = 0;
3406 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3407 // Figure out which interface we're in.
3408 CDecl = CurMethod->getClassInterface();
3409 if (!CDecl)
3410 return;
3411
3412 // Find the superclass of this class.
3413 CDecl = CDecl->getSuperClass();
3414 if (!CDecl)
3415 return;
3416
3417 if (CurMethod->isInstanceMethod()) {
3418 // We are inside an instance method, which means that the message
3419 // send [super ...] is actually calling an instance method on the
3420 // current object. Build the super expression and handle this like
3421 // an instance method.
3422 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3423 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3424 OwningExprResult Super
3425 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3426 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3427 SelIdents, NumSelIdents);
3428 }
3429
3430 // Fall through to send to the superclass in CDecl.
3431 } else {
3432 // "super" may be the name of a type or variable. Figure out which
3433 // it is.
3434 IdentifierInfo *Super = &Context.Idents.get("super");
3435 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3436 LookupOrdinaryName);
3437 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3438 // "super" names an interface. Use it.
3439 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00003440 if (const ObjCObjectType *Iface
3441 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3442 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003443 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3444 // "super" names an unresolved type; we can't be more specific.
3445 } else {
3446 // Assume that "super" names some kind of value and parse that way.
3447 CXXScopeSpec SS;
3448 UnqualifiedId id;
3449 id.setIdentifier(Super, SuperLoc);
3450 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3451 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3452 SelIdents, NumSelIdents);
3453 }
3454
3455 // Fall through
3456 }
3457
3458 TypeTy *Receiver = 0;
3459 if (CDecl)
3460 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3461 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3462 NumSelIdents);
3463}
3464
3465void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003466 IdentifierInfo **SelIdents,
3467 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003468 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00003469 ObjCInterfaceDecl *CDecl = 0;
3470
Douglas Gregor8ce33212009-11-17 17:59:40 +00003471 // If the given name refers to an interface type, retrieve the
3472 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003473 if (Receiver) {
3474 QualType T = GetTypeFromParser(Receiver, 0);
3475 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00003476 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3477 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00003478 }
3479
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003480 // Add all of the factory methods in this Objective-C class, its protocols,
3481 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00003482 ResultBuilder Results(*this);
3483 Results.EnterNewScope();
Douglas Gregor6285f752010-04-06 16:40:00 +00003484
3485 if (CDecl)
3486 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3487 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003488 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00003489 // We're messaging "id" as a type; provide all class/factory methods.
3490
Douglas Gregord720daf2010-04-06 17:30:22 +00003491 // If we have an external source, load the entire class method
3492 // pool from the PCH file.
3493 if (ExternalSource) {
3494 for (uint32_t I = 0, N = ExternalSource->GetNumKnownSelectors(); I != N;
3495 ++I) {
3496 Selector Sel = ExternalSource->GetSelector(I);
3497 if (Sel.isNull() || FactoryMethodPool.count(Sel) ||
3498 InstanceMethodPool.count(Sel))
3499 continue;
3500
3501 ReadMethodPool(Sel, /*isInstance=*/false);
3502 }
3503 }
3504
Douglas Gregor6285f752010-04-06 16:40:00 +00003505 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3506 M = FactoryMethodPool.begin(),
3507 MEnd = FactoryMethodPool.end();
3508 M != MEnd;
3509 ++M) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003510 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003511 MethList = MethList->Next) {
3512 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3513 NumSelIdents))
3514 continue;
3515
3516 Result R(MethList->Method, 0);
3517 R.StartParameter = NumSelIdents;
3518 R.AllParametersAreInformative = false;
3519 Results.MaybeAddResult(R, CurContext);
3520 }
3521 }
3522 }
3523
Steve Naroffeae65032009-11-07 02:08:14 +00003524 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003525 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003526}
3527
Douglas Gregor1b605f72009-11-19 01:08:35 +00003528void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3529 IdentifierInfo **SelIdents,
3530 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003531 typedef CodeCompleteConsumer::Result Result;
Steve Naroffeae65032009-11-07 02:08:14 +00003532
3533 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00003534
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003535 // If necessary, apply function/array conversion to the receiver.
3536 // C99 6.7.5.3p[7,8].
Douglas Gregorb92a1562010-02-03 00:27:59 +00003537 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003538 QualType ReceiverType = RecExpr->getType();
Steve Naroffeae65032009-11-07 02:08:14 +00003539
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003540 // Build the set of methods we can see.
3541 ResultBuilder Results(*this);
3542 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003543
3544 // If we're messaging an expression with type "id" or "Class", check
3545 // whether we know something special about the receiver that allows
3546 // us to assume a more-specific receiver type.
3547 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3548 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3549 ReceiverType = Context.getObjCObjectPointerType(
3550 Context.getObjCInterfaceType(IFace));
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003551
Douglas Gregora3329fa2009-11-18 00:06:18 +00003552 // Handle messages to Class. This really isn't a message to an instance
3553 // method, so we treat it the same way we would treat a message send to a
3554 // class method.
3555 if (ReceiverType->isObjCClassType() ||
3556 ReceiverType->isObjCQualifiedClassType()) {
3557 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3558 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003559 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3560 CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003561 }
3562 }
3563 // Handle messages to a qualified ID ("id<foo>").
3564 else if (const ObjCObjectPointerType *QualID
3565 = ReceiverType->getAsObjCQualifiedIdType()) {
3566 // Search protocols for instance methods.
3567 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3568 E = QualID->qual_end();
3569 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003570 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3571 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003572 }
3573 // Handle messages to a pointer to interface type.
3574 else if (const ObjCObjectPointerType *IFacePtr
3575 = ReceiverType->getAsObjCInterfacePointerType()) {
3576 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003577 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3578 NumSelIdents, CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003579
3580 // Search protocols for instance methods.
3581 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3582 E = IFacePtr->qual_end();
3583 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003584 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3585 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003586 }
Douglas Gregor6285f752010-04-06 16:40:00 +00003587 // Handle messages to "id".
3588 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003589 // We're messaging "id", so provide all instance methods we know
3590 // about as code-completion results.
3591
3592 // If we have an external source, load the entire class method
3593 // pool from the PCH file.
3594 if (ExternalSource) {
3595 for (uint32_t I = 0, N = ExternalSource->GetNumKnownSelectors(); I != N;
3596 ++I) {
3597 Selector Sel = ExternalSource->GetSelector(I);
3598 if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
3599 FactoryMethodPool.count(Sel))
3600 continue;
3601
3602 ReadMethodPool(Sel, /*isInstance=*/true);
3603 }
3604 }
3605
Douglas Gregor6285f752010-04-06 16:40:00 +00003606 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3607 M = InstanceMethodPool.begin(),
3608 MEnd = InstanceMethodPool.end();
3609 M != MEnd;
3610 ++M) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003611 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003612 MethList = MethList->Next) {
3613 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3614 NumSelIdents))
3615 continue;
3616
3617 Result R(MethList->Method, 0);
3618 R.StartParameter = NumSelIdents;
3619 R.AllParametersAreInformative = false;
3620 Results.MaybeAddResult(R, CurContext);
3621 }
3622 }
3623 }
3624
Steve Naroffeae65032009-11-07 02:08:14 +00003625 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003626 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003627}
Douglas Gregorbaf69612009-11-18 04:19:12 +00003628
3629/// \brief Add all of the protocol declarations that we find in the given
3630/// (translation unit) context.
3631static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003632 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00003633 ResultBuilder &Results) {
3634 typedef CodeCompleteConsumer::Result Result;
3635
3636 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3637 DEnd = Ctx->decls_end();
3638 D != DEnd; ++D) {
3639 // Record any protocols we find.
3640 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003641 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003642 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003643
3644 // Record any forward-declared protocols we find.
3645 if (ObjCForwardProtocolDecl *Forward
3646 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3647 for (ObjCForwardProtocolDecl::protocol_iterator
3648 P = Forward->protocol_begin(),
3649 PEnd = Forward->protocol_end();
3650 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003651 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003652 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003653 }
3654 }
3655}
3656
3657void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3658 unsigned NumProtocols) {
3659 ResultBuilder Results(*this);
3660 Results.EnterNewScope();
3661
3662 // Tell the result set to ignore all of the protocols we have
3663 // already seen.
3664 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003665 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3666 Protocols[I].second))
Douglas Gregorbaf69612009-11-18 04:19:12 +00003667 Results.Ignore(Protocol);
3668
3669 // Add all protocols.
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003670 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3671 Results);
3672
3673 Results.ExitScope();
3674 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3675}
3676
3677void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3678 ResultBuilder Results(*this);
3679 Results.EnterNewScope();
3680
3681 // Add all protocols.
3682 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3683 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003684
3685 Results.ExitScope();
3686 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3687}
Douglas Gregor49c22a72009-11-18 16:26:39 +00003688
3689/// \brief Add all of the Objective-C interface declarations that we find in
3690/// the given (translation unit) context.
3691static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3692 bool OnlyForwardDeclarations,
3693 bool OnlyUnimplemented,
3694 ResultBuilder &Results) {
3695 typedef CodeCompleteConsumer::Result Result;
3696
3697 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3698 DEnd = Ctx->decls_end();
3699 D != DEnd; ++D) {
3700 // Record any interfaces we find.
3701 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3702 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3703 (!OnlyUnimplemented || !Class->getImplementation()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003704 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003705
3706 // Record any forward-declared interfaces we find.
3707 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3708 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3709 C != CEnd; ++C)
3710 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3711 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003712 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3713 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003714 }
3715 }
3716}
3717
3718void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3719 ResultBuilder Results(*this);
3720 Results.EnterNewScope();
3721
3722 // Add all classes.
3723 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3724 false, Results);
3725
3726 Results.ExitScope();
3727 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3728}
3729
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003730void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3731 SourceLocation ClassNameLoc) {
Douglas Gregor49c22a72009-11-18 16:26:39 +00003732 ResultBuilder Results(*this);
3733 Results.EnterNewScope();
3734
3735 // Make sure that we ignore the class we're currently defining.
3736 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003737 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003738 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00003739 Results.Ignore(CurClass);
3740
3741 // Add all classes.
3742 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3743 false, Results);
3744
3745 Results.ExitScope();
3746 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3747}
3748
3749void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3750 ResultBuilder Results(*this);
3751 Results.EnterNewScope();
3752
3753 // Add all unimplemented classes.
3754 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3755 true, Results);
3756
3757 Results.ExitScope();
3758 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3759}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003760
3761void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003762 IdentifierInfo *ClassName,
3763 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003764 typedef CodeCompleteConsumer::Result Result;
3765
3766 ResultBuilder Results(*this);
3767
3768 // Ignore any categories we find that have already been implemented by this
3769 // interface.
3770 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3771 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003772 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003773 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3774 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3775 Category = Category->getNextClassCategory())
3776 CategoryNames.insert(Category->getIdentifier());
3777
3778 // Add all of the categories we know about.
3779 Results.EnterNewScope();
3780 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3781 for (DeclContext::decl_iterator D = TU->decls_begin(),
3782 DEnd = TU->decls_end();
3783 D != DEnd; ++D)
3784 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3785 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003786 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003787 Results.ExitScope();
3788
3789 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3790}
3791
3792void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003793 IdentifierInfo *ClassName,
3794 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003795 typedef CodeCompleteConsumer::Result Result;
3796
3797 // Find the corresponding interface. If we couldn't find the interface, the
3798 // program itself is ill-formed. However, we'll try to be helpful still by
3799 // providing the list of all of the categories we know about.
3800 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003801 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003802 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3803 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003804 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003805
3806 ResultBuilder Results(*this);
3807
3808 // Add all of the categories that have have corresponding interface
3809 // declarations in this class and any of its superclasses, except for
3810 // already-implemented categories in the class itself.
3811 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3812 Results.EnterNewScope();
3813 bool IgnoreImplemented = true;
3814 while (Class) {
3815 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3816 Category = Category->getNextClassCategory())
3817 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3818 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003819 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003820
3821 Class = Class->getSuperClass();
3822 IgnoreImplemented = false;
3823 }
3824 Results.ExitScope();
3825
3826 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3827}
Douglas Gregor5d649882009-11-18 22:32:06 +00003828
Douglas Gregor52e78bd2009-11-18 22:56:13 +00003829void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor5d649882009-11-18 22:32:06 +00003830 typedef CodeCompleteConsumer::Result Result;
3831 ResultBuilder Results(*this);
3832
3833 // Figure out where this @synthesize lives.
3834 ObjCContainerDecl *Container
3835 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3836 if (!Container ||
3837 (!isa<ObjCImplementationDecl>(Container) &&
3838 !isa<ObjCCategoryImplDecl>(Container)))
3839 return;
3840
3841 // Ignore any properties that have already been implemented.
3842 for (DeclContext::decl_iterator D = Container->decls_begin(),
3843 DEnd = Container->decls_end();
3844 D != DEnd; ++D)
3845 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3846 Results.Ignore(PropertyImpl->getPropertyDecl());
3847
3848 // Add any properties that we find.
3849 Results.EnterNewScope();
3850 if (ObjCImplementationDecl *ClassImpl
3851 = dyn_cast<ObjCImplementationDecl>(Container))
3852 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3853 Results);
3854 else
3855 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3856 false, CurContext, Results);
3857 Results.ExitScope();
3858
3859 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3860}
3861
3862void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3863 IdentifierInfo *PropertyName,
3864 DeclPtrTy ObjCImpDecl) {
3865 typedef CodeCompleteConsumer::Result Result;
3866 ResultBuilder Results(*this);
3867
3868 // Figure out where this @synthesize lives.
3869 ObjCContainerDecl *Container
3870 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3871 if (!Container ||
3872 (!isa<ObjCImplementationDecl>(Container) &&
3873 !isa<ObjCCategoryImplDecl>(Container)))
3874 return;
3875
3876 // Figure out which interface we're looking into.
3877 ObjCInterfaceDecl *Class = 0;
3878 if (ObjCImplementationDecl *ClassImpl
3879 = dyn_cast<ObjCImplementationDecl>(Container))
3880 Class = ClassImpl->getClassInterface();
3881 else
3882 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3883 ->getClassInterface();
3884
3885 // Add all of the instance variables in this class and its superclasses.
3886 Results.EnterNewScope();
3887 for(; Class; Class = Class->getSuperClass()) {
3888 // FIXME: We could screen the type of each ivar for compatibility with
3889 // the property, but is that being too paternal?
3890 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3891 IVarEnd = Class->ivar_end();
3892 IVar != IVarEnd; ++IVar)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003893 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor5d649882009-11-18 22:32:06 +00003894 }
3895 Results.ExitScope();
3896
3897 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3898}
Douglas Gregor636a61e2010-04-07 00:21:17 +00003899
3900typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
3901
3902/// \brief Find all of the methods that reside in the given container
3903/// (and its superclasses, protocols, etc.) that meet the given
3904/// criteria. Insert those methods into the map of known methods,
3905/// indexed by selector so they can be easily found.
3906static void FindImplementableMethods(ASTContext &Context,
3907 ObjCContainerDecl *Container,
3908 bool WantInstanceMethods,
3909 QualType ReturnType,
3910 bool IsInImplementation,
3911 KnownMethodsMap &KnownMethods) {
3912 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
3913 // Recurse into protocols.
3914 const ObjCList<ObjCProtocolDecl> &Protocols
3915 = IFace->getReferencedProtocols();
3916 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3917 E = Protocols.end();
3918 I != E; ++I)
3919 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3920 IsInImplementation, KnownMethods);
3921
3922 // If we're not in the implementation of a class, also visit the
3923 // superclass.
3924 if (!IsInImplementation && IFace->getSuperClass())
3925 FindImplementableMethods(Context, IFace->getSuperClass(),
3926 WantInstanceMethods, ReturnType,
3927 IsInImplementation, KnownMethods);
3928
3929 // Add methods from any class extensions (but not from categories;
3930 // those should go into category implementations).
3931 for (ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
3932 Cat = Cat->getNextClassCategory()) {
3933 if (!Cat->IsClassExtension())
3934 continue;
3935
3936 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
3937 IsInImplementation, KnownMethods);
3938 }
3939 }
3940
3941 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
3942 // Recurse into protocols.
3943 const ObjCList<ObjCProtocolDecl> &Protocols
3944 = Category->getReferencedProtocols();
3945 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3946 E = Protocols.end();
3947 I != E; ++I)
3948 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3949 IsInImplementation, KnownMethods);
3950 }
3951
3952 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3953 // Recurse into protocols.
3954 const ObjCList<ObjCProtocolDecl> &Protocols
3955 = Protocol->getReferencedProtocols();
3956 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3957 E = Protocols.end();
3958 I != E; ++I)
3959 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3960 IsInImplementation, KnownMethods);
3961 }
3962
3963 // Add methods in this container. This operation occurs last because
3964 // we want the methods from this container to override any methods
3965 // we've previously seen with the same selector.
3966 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3967 MEnd = Container->meth_end();
3968 M != MEnd; ++M) {
3969 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3970 if (!ReturnType.isNull() &&
3971 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
3972 continue;
3973
3974 KnownMethods[(*M)->getSelector()] = *M;
3975 }
3976 }
3977}
3978
3979void Sema::CodeCompleteObjCMethodDecl(Scope *S,
3980 bool IsInstanceMethod,
3981 TypeTy *ReturnTy,
3982 DeclPtrTy IDecl) {
3983 // Determine the return type of the method we're declaring, if
3984 // provided.
3985 QualType ReturnType = GetTypeFromParser(ReturnTy);
3986
3987 // Determine where we should start searching for methods, and where we
3988 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
3989 bool IsInImplementation = false;
3990 if (Decl *D = IDecl.getAs<Decl>()) {
3991 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
3992 SearchDecl = Impl->getClassInterface();
3993 CurrentDecl = Impl;
3994 IsInImplementation = true;
3995 } else if (ObjCCategoryImplDecl *CatImpl
3996 = dyn_cast<ObjCCategoryImplDecl>(D)) {
3997 SearchDecl = CatImpl->getCategoryDecl();
3998 CurrentDecl = CatImpl;
3999 IsInImplementation = true;
4000 } else {
4001 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4002 CurrentDecl = SearchDecl;
4003 }
4004 }
4005
4006 if (!SearchDecl && S) {
4007 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4008 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4009 CurrentDecl = SearchDecl;
4010 }
4011 }
4012
4013 if (!SearchDecl || !CurrentDecl) {
4014 HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
4015 return;
4016 }
4017
4018 // Find all of the methods that we could declare/implement here.
4019 KnownMethodsMap KnownMethods;
4020 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4021 ReturnType, IsInImplementation, KnownMethods);
4022
4023 // Erase any methods that have already been declared or
4024 // implemented here.
4025 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4026 MEnd = CurrentDecl->meth_end();
4027 M != MEnd; ++M) {
4028 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4029 continue;
4030
4031 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4032 if (Pos != KnownMethods.end())
4033 KnownMethods.erase(Pos);
4034 }
4035
4036 // Add declarations or definitions for each of the known methods.
4037 typedef CodeCompleteConsumer::Result Result;
4038 ResultBuilder Results(*this);
4039 Results.EnterNewScope();
4040 PrintingPolicy Policy(Context.PrintingPolicy);
4041 Policy.AnonymousTagLocations = false;
4042 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4043 MEnd = KnownMethods.end();
4044 M != MEnd; ++M) {
4045 ObjCMethodDecl *Method = M->second;
4046 CodeCompletionString *Pattern = new CodeCompletionString;
4047
4048 // If the result type was not already provided, add it to the
4049 // pattern as (type).
4050 if (ReturnType.isNull()) {
4051 std::string TypeStr;
4052 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4053 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4054 Pattern->AddTextChunk(TypeStr);
4055 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4056 }
4057
4058 Selector Sel = Method->getSelector();
4059
4060 // Add the first part of the selector to the pattern.
4061 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4062
4063 // Add parameters to the pattern.
4064 unsigned I = 0;
4065 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4066 PEnd = Method->param_end();
4067 P != PEnd; (void)++P, ++I) {
4068 // Add the part of the selector name.
4069 if (I == 0)
4070 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4071 else if (I < Sel.getNumArgs()) {
4072 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4073 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4074 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4075 } else
4076 break;
4077
4078 // Add the parameter type.
4079 std::string TypeStr;
4080 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4081 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4082 Pattern->AddTextChunk(TypeStr);
4083 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4084
4085 if (IdentifierInfo *Id = (*P)->getIdentifier())
4086 Pattern->AddTextChunk(Id->getName());
4087 }
4088
4089 if (Method->isVariadic()) {
4090 if (Method->param_size() > 0)
4091 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4092 Pattern->AddTextChunk("...");
4093 }
4094
Douglas Gregord37c59d2010-05-28 00:57:46 +00004095 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00004096 // We will be defining the method here, so add a compound statement.
4097 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4098 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4099 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4100 if (!Method->getResultType()->isVoidType()) {
4101 // If the result type is not void, add a return clause.
4102 Pattern->AddTextChunk("return");
4103 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4104 Pattern->AddPlaceholderChunk("expression");
4105 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4106 } else
4107 Pattern->AddPlaceholderChunk("statements");
4108
4109 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4110 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4111 }
4112
4113 Results.AddResult(Result(Pattern));
4114 }
4115
4116 Results.ExitScope();
4117
4118 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4119}