blob: d40853d724b277b4e32d4a6970f7e4e85efa7fbd [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.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001576 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1577 // The interface can be NULL.
1578 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1579 if (ID->getSuperClass())
1580 Results.AddResult(Result("super"));
1581 }
1582
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001583 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001584 }
1585
Douglas Gregorf4c33342010-05-28 00:22:41 +00001586 // sizeof expression
1587 Pattern = new CodeCompletionString;
1588 Pattern->AddTypedTextChunk("sizeof");
1589 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1590 Pattern->AddPlaceholderChunk("expression-or-type");
1591 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1592 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001593 break;
1594 }
1595 }
1596
Douglas Gregor70febae2010-05-28 00:49:12 +00001597 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1598 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001599
1600 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor78a21012010-01-14 16:01:26 +00001601 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001602}
1603
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001604/// \brief If the given declaration has an associated type, add it as a result
1605/// type chunk.
1606static void AddResultTypeChunk(ASTContext &Context,
1607 NamedDecl *ND,
1608 CodeCompletionString *Result) {
1609 if (!ND)
1610 return;
1611
1612 // Determine the type of the declaration (if it has a type).
1613 QualType T;
1614 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1615 T = Function->getResultType();
1616 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1617 T = Method->getResultType();
1618 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1619 T = FunTmpl->getTemplatedDecl()->getResultType();
1620 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1621 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1622 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1623 /* Do nothing: ignore unresolved using declarations*/
1624 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1625 T = Value->getType();
1626 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1627 T = Property->getType();
1628
1629 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1630 return;
1631
Douglas Gregorcf04b022010-04-05 21:25:31 +00001632 PrintingPolicy Policy(Context.PrintingPolicy);
1633 Policy.AnonymousTagLocations = false;
1634
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001635 std::string TypeStr;
Douglas Gregorcf04b022010-04-05 21:25:31 +00001636 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001637 Result->AddResultTypeChunk(TypeStr);
1638}
1639
Douglas Gregor3545ff42009-09-21 16:56:56 +00001640/// \brief Add function parameter chunks to the given code completion string.
1641static void AddFunctionParameterChunks(ASTContext &Context,
1642 FunctionDecl *Function,
1643 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001644 typedef CodeCompletionString::Chunk Chunk;
1645
Douglas Gregor3545ff42009-09-21 16:56:56 +00001646 CodeCompletionString *CCStr = Result;
1647
1648 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1649 ParmVarDecl *Param = Function->getParamDecl(P);
1650
1651 if (Param->hasDefaultArg()) {
1652 // When we see an optional default argument, put that argument and
1653 // the remaining default arguments into a new, optional string.
1654 CodeCompletionString *Opt = new CodeCompletionString;
1655 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1656 CCStr = Opt;
1657 }
1658
1659 if (P != 0)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001660 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001661
1662 // Format the placeholder string.
1663 std::string PlaceholderStr;
1664 if (Param->getIdentifier())
1665 PlaceholderStr = Param->getIdentifier()->getName();
1666
1667 Param->getType().getAsStringInternal(PlaceholderStr,
1668 Context.PrintingPolicy);
1669
1670 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001671 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001672 }
Douglas Gregorba449032009-09-22 21:42:17 +00001673
1674 if (const FunctionProtoType *Proto
1675 = Function->getType()->getAs<FunctionProtoType>())
1676 if (Proto->isVariadic())
1677 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001678}
1679
1680/// \brief Add template parameter chunks to the given code completion string.
1681static void AddTemplateParameterChunks(ASTContext &Context,
1682 TemplateDecl *Template,
1683 CodeCompletionString *Result,
1684 unsigned MaxParameters = 0) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001685 typedef CodeCompletionString::Chunk Chunk;
1686
Douglas Gregor3545ff42009-09-21 16:56:56 +00001687 CodeCompletionString *CCStr = Result;
1688 bool FirstParameter = true;
1689
1690 TemplateParameterList *Params = Template->getTemplateParameters();
1691 TemplateParameterList::iterator PEnd = Params->end();
1692 if (MaxParameters)
1693 PEnd = Params->begin() + MaxParameters;
1694 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1695 bool HasDefaultArg = false;
1696 std::string PlaceholderStr;
1697 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1698 if (TTP->wasDeclaredWithTypename())
1699 PlaceholderStr = "typename";
1700 else
1701 PlaceholderStr = "class";
1702
1703 if (TTP->getIdentifier()) {
1704 PlaceholderStr += ' ';
1705 PlaceholderStr += TTP->getIdentifier()->getName();
1706 }
1707
1708 HasDefaultArg = TTP->hasDefaultArgument();
1709 } else if (NonTypeTemplateParmDecl *NTTP
1710 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1711 if (NTTP->getIdentifier())
1712 PlaceholderStr = NTTP->getIdentifier()->getName();
1713 NTTP->getType().getAsStringInternal(PlaceholderStr,
1714 Context.PrintingPolicy);
1715 HasDefaultArg = NTTP->hasDefaultArgument();
1716 } else {
1717 assert(isa<TemplateTemplateParmDecl>(*P));
1718 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1719
1720 // Since putting the template argument list into the placeholder would
1721 // be very, very long, we just use an abbreviation.
1722 PlaceholderStr = "template<...> class";
1723 if (TTP->getIdentifier()) {
1724 PlaceholderStr += ' ';
1725 PlaceholderStr += TTP->getIdentifier()->getName();
1726 }
1727
1728 HasDefaultArg = TTP->hasDefaultArgument();
1729 }
1730
1731 if (HasDefaultArg) {
1732 // When we see an optional default argument, put that argument and
1733 // the remaining default arguments into a new, optional string.
1734 CodeCompletionString *Opt = new CodeCompletionString;
1735 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1736 CCStr = Opt;
1737 }
1738
1739 if (FirstParameter)
1740 FirstParameter = false;
1741 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001742 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001743
1744 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001745 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001746 }
1747}
1748
Douglas Gregorf2510672009-09-21 19:57:38 +00001749/// \brief Add a qualifier to the given code-completion string, if the
1750/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00001751static void
1752AddQualifierToCompletionString(CodeCompletionString *Result,
1753 NestedNameSpecifier *Qualifier,
1754 bool QualifierIsInformative,
1755 ASTContext &Context) {
Douglas Gregorf2510672009-09-21 19:57:38 +00001756 if (!Qualifier)
1757 return;
1758
1759 std::string PrintedNNS;
1760 {
1761 llvm::raw_string_ostream OS(PrintedNNS);
1762 Qualifier->print(OS, Context.PrintingPolicy);
1763 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00001764 if (QualifierIsInformative)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001765 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor5bf52692009-09-22 23:15:58 +00001766 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001767 Result->AddTextChunk(PrintedNNS);
Douglas Gregorf2510672009-09-21 19:57:38 +00001768}
1769
Douglas Gregor0f622362009-12-11 18:44:16 +00001770static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1771 FunctionDecl *Function) {
1772 const FunctionProtoType *Proto
1773 = Function->getType()->getAs<FunctionProtoType>();
1774 if (!Proto || !Proto->getTypeQuals())
1775 return;
1776
1777 std::string QualsStr;
1778 if (Proto->getTypeQuals() & Qualifiers::Const)
1779 QualsStr += " const";
1780 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1781 QualsStr += " volatile";
1782 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1783 QualsStr += " restrict";
1784 Result->AddInformativeChunk(QualsStr);
1785}
1786
Douglas Gregor3545ff42009-09-21 16:56:56 +00001787/// \brief If possible, create a new code completion string for the given
1788/// result.
1789///
1790/// \returns Either a new, heap-allocated code completion string describing
1791/// how to use this result, or NULL to indicate that the string or name of the
1792/// result is all that is needed.
1793CodeCompletionString *
1794CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001795 typedef CodeCompletionString::Chunk Chunk;
1796
Douglas Gregorf09935f2009-12-01 05:55:20 +00001797 if (Kind == RK_Pattern)
1798 return Pattern->Clone();
1799
1800 CodeCompletionString *Result = new CodeCompletionString;
1801
1802 if (Kind == RK_Keyword) {
1803 Result->AddTypedTextChunk(Keyword);
1804 return Result;
1805 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001806
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001807 if (Kind == RK_Macro) {
1808 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001809 assert(MI && "Not a macro?");
1810
1811 Result->AddTypedTextChunk(Macro->getName());
1812
1813 if (!MI->isFunctionLike())
1814 return Result;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001815
1816 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001817 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001818 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1819 A != AEnd; ++A) {
1820 if (A != MI->arg_begin())
Douglas Gregor9eb77012009-11-07 00:00:49 +00001821 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001822
1823 if (!MI->isVariadic() || A != AEnd - 1) {
1824 // Non-variadic argument.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001825 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001826 continue;
1827 }
1828
1829 // Variadic argument; cope with the different between GNU and C99
1830 // variadic macros, providing a single placeholder for the rest of the
1831 // arguments.
1832 if ((*A)->isStr("__VA_ARGS__"))
1833 Result->AddPlaceholderChunk("...");
1834 else {
1835 std::string Arg = (*A)->getName();
1836 Arg += "...";
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001837 Result->AddPlaceholderChunk(Arg);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001838 }
1839 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001840 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001841 return Result;
1842 }
1843
Douglas Gregorf64acca2010-05-25 21:41:55 +00001844 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001845 NamedDecl *ND = Declaration;
1846
Douglas Gregor9eb77012009-11-07 00:00:49 +00001847 if (StartsNestedNameSpecifier) {
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001848 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001849 Result->AddTextChunk("::");
1850 return Result;
1851 }
1852
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001853 AddResultTypeChunk(S.Context, ND, Result);
1854
Douglas Gregor3545ff42009-09-21 16:56:56 +00001855 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001856 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1857 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001858 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001859 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001860 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001861 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001862 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001863 return Result;
1864 }
1865
1866 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001867 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1868 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001869 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001870 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001871
1872 // Figure out which template parameters are deduced (or have default
1873 // arguments).
1874 llvm::SmallVector<bool, 16> Deduced;
1875 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1876 unsigned LastDeducibleArgument;
1877 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1878 --LastDeducibleArgument) {
1879 if (!Deduced[LastDeducibleArgument - 1]) {
1880 // C++0x: Figure out if the template argument has a default. If so,
1881 // the user doesn't need to type this argument.
1882 // FIXME: We need to abstract template parameters better!
1883 bool HasDefaultArg = false;
1884 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1885 LastDeducibleArgument - 1);
1886 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1887 HasDefaultArg = TTP->hasDefaultArgument();
1888 else if (NonTypeTemplateParmDecl *NTTP
1889 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1890 HasDefaultArg = NTTP->hasDefaultArgument();
1891 else {
1892 assert(isa<TemplateTemplateParmDecl>(Param));
1893 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00001894 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001895 }
1896
1897 if (!HasDefaultArg)
1898 break;
1899 }
1900 }
1901
1902 if (LastDeducibleArgument) {
1903 // Some of the function template arguments cannot be deduced from a
1904 // function call, so we introduce an explicit template argument list
1905 // containing all of the arguments up to the first deducible argument.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001906 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001907 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1908 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001909 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001910 }
1911
1912 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +00001913 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001914 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001915 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001916 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001917 return Result;
1918 }
1919
1920 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001921 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1922 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001923 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001924 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001925 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001926 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001927 return Result;
1928 }
1929
Douglas Gregord3c5d792009-11-17 16:44:22 +00001930 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00001931 Selector Sel = Method->getSelector();
1932 if (Sel.isUnarySelector()) {
1933 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1934 return Result;
1935 }
1936
Douglas Gregor1b605f72009-11-19 01:08:35 +00001937 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1938 SelName += ':';
1939 if (StartParameter == 0)
1940 Result->AddTypedTextChunk(SelName);
1941 else {
1942 Result->AddInformativeChunk(SelName);
1943
1944 // If there is only one parameter, and we're past it, add an empty
1945 // typed-text chunk since there is nothing to type.
1946 if (Method->param_size() == 1)
1947 Result->AddTypedTextChunk("");
1948 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00001949 unsigned Idx = 0;
1950 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1951 PEnd = Method->param_end();
1952 P != PEnd; (void)++P, ++Idx) {
1953 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001954 std::string Keyword;
1955 if (Idx > StartParameter)
Douglas Gregor6a803932010-01-12 06:38:28 +00001956 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001957 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1958 Keyword += II->getName().str();
1959 Keyword += ":";
Douglas Gregorc8537c52009-11-19 07:41:15 +00001960 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001961 Result->AddInformativeChunk(Keyword);
1962 } else if (Idx == StartParameter)
1963 Result->AddTypedTextChunk(Keyword);
1964 else
1965 Result->AddTextChunk(Keyword);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001966 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00001967
1968 // If we're before the starting parameter, skip the placeholder.
1969 if (Idx < StartParameter)
1970 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00001971
1972 std::string Arg;
1973 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1974 Arg = "(" + Arg + ")";
1975 if (IdentifierInfo *II = (*P)->getIdentifier())
1976 Arg += II->getName().str();
Douglas Gregorc8537c52009-11-19 07:41:15 +00001977 if (AllParametersAreInformative)
1978 Result->AddInformativeChunk(Arg);
1979 else
1980 Result->AddPlaceholderChunk(Arg);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001981 }
1982
Douglas Gregor04c5f972009-12-23 00:21:46 +00001983 if (Method->isVariadic()) {
1984 if (AllParametersAreInformative)
1985 Result->AddInformativeChunk(", ...");
1986 else
1987 Result->AddPlaceholderChunk(", ...");
1988 }
1989
Douglas Gregord3c5d792009-11-17 16:44:22 +00001990 return Result;
1991 }
1992
Douglas Gregorf09935f2009-12-01 05:55:20 +00001993 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00001994 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1995 S.Context);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001996
1997 Result->AddTypedTextChunk(ND->getNameAsString());
1998 return Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001999}
2000
Douglas Gregorf0f51982009-09-23 00:34:09 +00002001CodeCompletionString *
2002CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2003 unsigned CurrentArg,
2004 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002005 typedef CodeCompletionString::Chunk Chunk;
2006
Douglas Gregorf0f51982009-09-23 00:34:09 +00002007 CodeCompletionString *Result = new CodeCompletionString;
2008 FunctionDecl *FDecl = getFunction();
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002009 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002010 const FunctionProtoType *Proto
2011 = dyn_cast<FunctionProtoType>(getFunctionType());
2012 if (!FDecl && !Proto) {
2013 // Function without a prototype. Just give the return type and a
2014 // highlighted ellipsis.
2015 const FunctionType *FT = getFunctionType();
2016 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002017 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor9eb77012009-11-07 00:00:49 +00002018 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2019 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2020 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002021 return Result;
2022 }
2023
2024 if (FDecl)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002025 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregorf0f51982009-09-23 00:34:09 +00002026 else
2027 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002028 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002029
Douglas Gregor9eb77012009-11-07 00:00:49 +00002030 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002031 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2032 for (unsigned I = 0; I != NumParams; ++I) {
2033 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002034 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002035
2036 std::string ArgString;
2037 QualType ArgType;
2038
2039 if (FDecl) {
2040 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2041 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2042 } else {
2043 ArgType = Proto->getArgType(I);
2044 }
2045
2046 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2047
2048 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002049 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002050 ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002051 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002052 Result->AddTextChunk(ArgString);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002053 }
2054
2055 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002056 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002057 if (CurrentArg < NumParams)
2058 Result->AddTextChunk("...");
2059 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00002060 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002061 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00002062 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002063
2064 return Result;
2065}
2066
Douglas Gregor3545ff42009-09-21 16:56:56 +00002067namespace {
2068 struct SortCodeCompleteResult {
2069 typedef CodeCompleteConsumer::Result Result;
2070
Douglas Gregore6688e62009-09-28 03:51:44 +00002071 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor249d6822009-12-05 09:08:56 +00002072 Selector XSel = X.getObjCSelector();
2073 Selector YSel = Y.getObjCSelector();
2074 if (!XSel.isNull() && !YSel.isNull()) {
2075 // We are comparing two selectors.
2076 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2077 if (N == 0)
2078 ++N;
2079 for (unsigned I = 0; I != N; ++I) {
2080 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2081 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2082 if (!XId || !YId)
2083 return XId && !YId;
2084
2085 switch (XId->getName().compare_lower(YId->getName())) {
2086 case -1: return true;
2087 case 1: return false;
2088 default: break;
2089 }
2090 }
2091
2092 return XSel.getNumArgs() < YSel.getNumArgs();
2093 }
2094
2095 // For non-selectors, order by kind.
2096 if (X.getNameKind() != Y.getNameKind())
Douglas Gregore6688e62009-09-28 03:51:44 +00002097 return X.getNameKind() < Y.getNameKind();
2098
Douglas Gregor249d6822009-12-05 09:08:56 +00002099 // Order identifiers by comparison of their lowercased names.
2100 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2101 return XId->getName().compare_lower(
2102 Y.getAsIdentifierInfo()->getName()) < 0;
2103
2104 // Order overloaded operators by the order in which they appear
2105 // in our list of operators.
2106 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2107 return XOp < Y.getCXXOverloadedOperator();
2108
2109 // Order C++0x user-defined literal operators lexically by their
2110 // lowercased suffixes.
2111 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2112 return XLit->getName().compare_lower(
2113 Y.getCXXLiteralIdentifier()->getName()) < 0;
2114
2115 // The only stable ordering we have is to turn the name into a
2116 // string and then compare the lower-case strings. This is
2117 // inefficient, but thankfully does not happen too often.
Benjamin Kramer4053e5d2009-12-05 10:22:15 +00002118 return llvm::StringRef(X.getAsString()).compare_lower(
2119 Y.getAsString()) < 0;
Douglas Gregore6688e62009-09-28 03:51:44 +00002120 }
2121
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002122 /// \brief Retrieve the name that should be used to order a result.
2123 ///
2124 /// If the name needs to be constructed as a string, that string will be
2125 /// saved into Saved and the returned StringRef will refer to it.
2126 static llvm::StringRef getOrderedName(const Result &R,
2127 std::string &Saved) {
2128 switch (R.Kind) {
2129 case Result::RK_Keyword:
2130 return R.Keyword;
2131
2132 case Result::RK_Pattern:
2133 return R.Pattern->getTypedText();
2134
2135 case Result::RK_Macro:
2136 return R.Macro->getName();
2137
2138 case Result::RK_Declaration:
2139 // Handle declarations below.
2140 break;
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002141 }
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002142
2143 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002144
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002145 // If the name is a simple identifier (by far the common case), or a
2146 // zero-argument selector, just return a reference to that identifier.
2147 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2148 return Id->getName();
2149 if (Name.isObjCZeroArgSelector())
2150 if (IdentifierInfo *Id
2151 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2152 return Id->getName();
2153
2154 Saved = Name.getAsString();
2155 return Saved;
2156 }
2157
2158 bool operator()(const Result &X, const Result &Y) const {
2159 std::string XSaved, YSaved;
2160 llvm::StringRef XStr = getOrderedName(X, XSaved);
2161 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2162 int cmp = XStr.compare_lower(YStr);
2163 if (cmp)
2164 return cmp < 0;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002165
2166 // Non-hidden names precede hidden names.
2167 if (X.Hidden != Y.Hidden)
2168 return !X.Hidden;
2169
Douglas Gregore412a5a2009-09-23 22:26:46 +00002170 // Non-nested-name-specifiers precede nested-name-specifiers.
2171 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2172 return !X.StartsNestedNameSpecifier;
2173
Douglas Gregor3545ff42009-09-21 16:56:56 +00002174 return false;
2175 }
2176 };
2177}
2178
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002179static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002180 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002181 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2182 MEnd = PP.macro_end();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002183 M != MEnd; ++M)
Douglas Gregor78a21012010-01-14 16:01:26 +00002184 Results.AddResult(M->first);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002185 Results.ExitScope();
2186}
2187
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002188static void HandleCodeCompleteResults(Sema *S,
2189 CodeCompleteConsumer *CodeCompleter,
2190 CodeCompleteConsumer::Result *Results,
2191 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002192 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2193
2194 if (CodeCompleter)
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002195 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002196
2197 for (unsigned I = 0; I != NumResults; ++I)
2198 Results[I].Destroy();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002199}
2200
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002201void Sema::CodeCompleteOrdinaryName(Scope *S,
2202 CodeCompletionContext CompletionContext) {
Douglas Gregor92253692009-12-07 09:54:55 +00002203 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002204 ResultBuilder Results(*this);
2205
2206 // Determine how to filter results, e.g., so that the names of
2207 // values (functions, enumerators, function templates, etc.) are
2208 // only allowed where we can have an expression.
2209 switch (CompletionContext) {
2210 case CCC_Namespace:
2211 case CCC_Class:
Douglas Gregorf1934162010-01-13 21:24:21 +00002212 case CCC_ObjCInterface:
2213 case CCC_ObjCImplementation:
Douglas Gregor48d46252010-01-13 21:54:15 +00002214 case CCC_ObjCInstanceVariableList:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002215 case CCC_Template:
2216 case CCC_MemberTemplate:
2217 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2218 break;
2219
2220 case CCC_Expression:
2221 case CCC_Statement:
2222 case CCC_ForInit:
2223 case CCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00002224 if (WantTypesInContext(CompletionContext, getLangOptions()))
2225 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2226 else
2227 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002228 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00002229
2230 case CCC_RecoveryInFunction:
2231 // Unfiltered
2232 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002233 }
2234
Douglas Gregorc580c522010-01-14 01:09:38 +00002235 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2236 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor92253692009-12-07 09:54:55 +00002237
2238 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002239 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00002240 Results.ExitScope();
2241
Douglas Gregor9eb77012009-11-07 00:00:49 +00002242 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002243 AddMacroResults(PP, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002244 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00002245}
2246
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002247/// \brief Perform code-completion in an expression context when we know what
2248/// type we're looking for.
2249void Sema::CodeCompleteExpression(Scope *S, QualType T) {
2250 typedef CodeCompleteConsumer::Result Result;
2251 ResultBuilder Results(*this);
2252
2253 if (WantTypesInContext(CCC_Expression, getLangOptions()))
2254 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2255 else
2256 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2257 Results.setPreferredType(T.getNonReferenceType());
2258
2259 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2260 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2261
2262 Results.EnterNewScope();
2263 AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
2264 Results.ExitScope();
2265
2266 if (CodeCompleter->includeMacros())
2267 AddMacroResults(PP, Results);
2268 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2269}
2270
2271
Douglas Gregor9291bad2009-11-18 01:29:26 +00002272static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00002273 bool AllowCategories,
Douglas Gregor9291bad2009-11-18 01:29:26 +00002274 DeclContext *CurContext,
2275 ResultBuilder &Results) {
2276 typedef CodeCompleteConsumer::Result Result;
2277
2278 // Add properties in this container.
2279 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2280 PEnd = Container->prop_end();
2281 P != PEnd;
2282 ++P)
2283 Results.MaybeAddResult(Result(*P, 0), CurContext);
2284
2285 // Add properties in referenced protocols.
2286 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2287 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2288 PEnd = Protocol->protocol_end();
2289 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002290 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002291 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00002292 if (AllowCategories) {
2293 // Look through categories.
2294 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2295 Category; Category = Category->getNextClassCategory())
2296 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2297 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002298
2299 // Look through protocols.
2300 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2301 E = IFace->protocol_end();
2302 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002303 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002304
2305 // Look in the superclass.
2306 if (IFace->getSuperClass())
Douglas Gregor5d649882009-11-18 22:32:06 +00002307 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2308 Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002309 } else if (const ObjCCategoryDecl *Category
2310 = dyn_cast<ObjCCategoryDecl>(Container)) {
2311 // Look through protocols.
2312 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2313 PEnd = Category->protocol_end();
2314 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002315 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002316 }
2317}
2318
Douglas Gregor2436e712009-09-17 21:32:03 +00002319void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2320 SourceLocation OpLoc,
2321 bool IsArrow) {
2322 if (!BaseE || !CodeCompleter)
2323 return;
2324
Douglas Gregor3545ff42009-09-21 16:56:56 +00002325 typedef CodeCompleteConsumer::Result Result;
2326
Douglas Gregor2436e712009-09-17 21:32:03 +00002327 Expr *Base = static_cast<Expr *>(BaseE);
2328 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002329
2330 if (IsArrow) {
2331 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2332 BaseType = Ptr->getPointeeType();
2333 else if (BaseType->isObjCObjectPointerType())
2334 /*Do nothing*/ ;
2335 else
2336 return;
2337 }
2338
Douglas Gregore412a5a2009-09-23 22:26:46 +00002339 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002340 Results.EnterNewScope();
2341 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2342 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002343 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00002344 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2345 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002346
Douglas Gregor9291bad2009-11-18 01:29:26 +00002347 if (getLangOptions().CPlusPlus) {
2348 if (!Results.empty()) {
2349 // The "template" keyword can follow "->" or "." in the grammar.
2350 // However, we only want to suggest the template keyword if something
2351 // is dependent.
2352 bool IsDependent = BaseType->isDependentType();
2353 if (!IsDependent) {
2354 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2355 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2356 IsDependent = Ctx->isDependentContext();
2357 break;
2358 }
2359 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002360
Douglas Gregor9291bad2009-11-18 01:29:26 +00002361 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00002362 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002363 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002364 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002365 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2366 // Objective-C property reference.
2367
2368 // Add property results based on our interface.
2369 const ObjCObjectPointerType *ObjCPtr
2370 = BaseType->getAsObjCInterfacePointerType();
2371 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor5d649882009-11-18 22:32:06 +00002372 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002373
2374 // Add properties from the protocols in a qualified interface.
2375 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2376 E = ObjCPtr->qual_end();
2377 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002378 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002379 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00002380 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00002381 // Objective-C instance variable access.
2382 ObjCInterfaceDecl *Class = 0;
2383 if (const ObjCObjectPointerType *ObjCPtr
2384 = BaseType->getAs<ObjCObjectPointerType>())
2385 Class = ObjCPtr->getInterfaceDecl();
2386 else
John McCall8b07ec22010-05-15 11:32:37 +00002387 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00002388
2389 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00002390 if (Class) {
2391 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2392 Results.setFilter(&ResultBuilder::IsObjCIvar);
2393 LookupVisibleDecls(Class, LookupMemberName, Consumer);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002394 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002395 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002396
2397 // FIXME: How do we cope with isa?
2398
2399 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002400
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002401 // Hand off the results found for code completion.
2402 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002403}
2404
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002405void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2406 if (!CodeCompleter)
2407 return;
2408
Douglas Gregor3545ff42009-09-21 16:56:56 +00002409 typedef CodeCompleteConsumer::Result Result;
2410 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002411 switch ((DeclSpec::TST)TagSpec) {
2412 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002413 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002414 break;
2415
2416 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002417 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002418 break;
2419
2420 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002421 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002422 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002423 break;
2424
2425 default:
2426 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2427 return;
2428 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002429
John McCalle87beb22010-04-23 18:46:30 +00002430 ResultBuilder Results(*this);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002431 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00002432
2433 // First pass: look for tags.
2434 Results.setFilter(Filter);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002435 LookupVisibleDecls(S, LookupTagName, Consumer);
John McCalle87beb22010-04-23 18:46:30 +00002436
2437 // Second pass: look for nested name specifiers.
2438 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2439 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002440
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002441 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002442}
2443
Douglas Gregord328d572009-09-21 18:10:23 +00002444void Sema::CodeCompleteCase(Scope *S) {
2445 if (getSwitchStack().empty() || !CodeCompleter)
2446 return;
2447
2448 SwitchStmt *Switch = getSwitchStack().back();
2449 if (!Switch->getCond()->getType()->isEnumeralType())
2450 return;
2451
2452 // Code-complete the cases of a switch statement over an enumeration type
2453 // by providing the list of
2454 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2455
2456 // Determine which enumerators we have already seen in the switch statement.
2457 // FIXME: Ideally, we would also be able to look *past* the code-completion
2458 // token, in case we are code-completing in the middle of the switch and not
2459 // at the end. However, we aren't able to do so at the moment.
2460 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00002461 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00002462 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2463 SC = SC->getNextSwitchCase()) {
2464 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2465 if (!Case)
2466 continue;
2467
2468 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2469 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2470 if (EnumConstantDecl *Enumerator
2471 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2472 // We look into the AST of the case statement to determine which
2473 // enumerator was named. Alternatively, we could compute the value of
2474 // the integral constant expression, then compare it against the
2475 // values of each enumerator. However, value-based approach would not
2476 // work as well with C++ templates where enumerators declared within a
2477 // template are type- and value-dependent.
2478 EnumeratorsSeen.insert(Enumerator);
2479
Douglas Gregorf2510672009-09-21 19:57:38 +00002480 // If this is a qualified-id, keep track of the nested-name-specifier
2481 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00002482 //
2483 // switch (TagD.getKind()) {
2484 // case TagDecl::TK_enum:
2485 // break;
2486 // case XXX
2487 //
Douglas Gregorf2510672009-09-21 19:57:38 +00002488 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00002489 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2490 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002491 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00002492 }
2493 }
2494
Douglas Gregorf2510672009-09-21 19:57:38 +00002495 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2496 // If there are no prior enumerators in C++, check whether we have to
2497 // qualify the names of the enumerators that we suggest, because they
2498 // may not be visible in this scope.
2499 Qualifier = getRequiredQualification(Context, CurContext,
2500 Enum->getDeclContext());
2501
2502 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2503 }
2504
Douglas Gregord328d572009-09-21 18:10:23 +00002505 // Add any enumerators that have not yet been mentioned.
2506 ResultBuilder Results(*this);
2507 Results.EnterNewScope();
2508 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2509 EEnd = Enum->enumerator_end();
2510 E != EEnd; ++E) {
2511 if (EnumeratorsSeen.count(*E))
2512 continue;
2513
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002514 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2515 CurContext, 0, false);
Douglas Gregord328d572009-09-21 18:10:23 +00002516 }
2517 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00002518
Douglas Gregor9eb77012009-11-07 00:00:49 +00002519 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002520 AddMacroResults(PP, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002521 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00002522}
2523
Douglas Gregorcabea402009-09-22 15:41:20 +00002524namespace {
2525 struct IsBetterOverloadCandidate {
2526 Sema &S;
John McCallbc077cf2010-02-08 23:07:23 +00002527 SourceLocation Loc;
Douglas Gregorcabea402009-09-22 15:41:20 +00002528
2529 public:
John McCallbc077cf2010-02-08 23:07:23 +00002530 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2531 : S(S), Loc(Loc) { }
Douglas Gregorcabea402009-09-22 15:41:20 +00002532
2533 bool
2534 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCallbc077cf2010-02-08 23:07:23 +00002535 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregorcabea402009-09-22 15:41:20 +00002536 }
2537 };
2538}
2539
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002540static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2541 if (NumArgs && !Args)
2542 return true;
2543
2544 for (unsigned I = 0; I != NumArgs; ++I)
2545 if (!Args[I])
2546 return true;
2547
2548 return false;
2549}
2550
Douglas Gregorcabea402009-09-22 15:41:20 +00002551void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2552 ExprTy **ArgsIn, unsigned NumArgs) {
2553 if (!CodeCompleter)
2554 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002555
2556 // When we're code-completing for a call, we fall back to ordinary
2557 // name code-completion whenever we can't produce specific
2558 // results. We may want to revisit this strategy in the future,
2559 // e.g., by merging the two kinds of results.
2560
Douglas Gregorcabea402009-09-22 15:41:20 +00002561 Expr *Fn = (Expr *)FnIn;
2562 Expr **Args = (Expr **)ArgsIn;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002563
Douglas Gregorcabea402009-09-22 15:41:20 +00002564 // Ignore type-dependent call expressions entirely.
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002565 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregor3ef59522009-12-11 19:06:04 +00002566 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002567 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00002568 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002569 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002570
John McCall57500772009-12-16 12:17:52 +00002571 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00002572 SourceLocation Loc = Fn->getExprLoc();
2573 OverloadCandidateSet CandidateSet(Loc);
John McCall57500772009-12-16 12:17:52 +00002574
Douglas Gregorcabea402009-09-22 15:41:20 +00002575 // FIXME: What if we're calling something that isn't a function declaration?
2576 // FIXME: What if we're calling a pseudo-destructor?
2577 // FIXME: What if we're calling a member function?
2578
Douglas Gregorff59f672010-01-21 15:46:19 +00002579 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2580 llvm::SmallVector<ResultCandidate, 8> Results;
2581
John McCall57500772009-12-16 12:17:52 +00002582 Expr *NakedFn = Fn->IgnoreParenCasts();
2583 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2584 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2585 /*PartialOverloading=*/ true);
2586 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2587 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorff59f672010-01-21 15:46:19 +00002588 if (FDecl) {
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002589 if (!getLangOptions().CPlusPlus ||
2590 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorff59f672010-01-21 15:46:19 +00002591 Results.push_back(ResultCandidate(FDecl));
2592 else
John McCallb89836b2010-01-26 01:37:31 +00002593 // FIXME: access?
John McCalla0296f72010-03-19 07:35:19 +00002594 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2595 Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002596 false, /*PartialOverloading*/true);
Douglas Gregorff59f672010-01-21 15:46:19 +00002597 }
John McCall57500772009-12-16 12:17:52 +00002598 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002599
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002600 QualType ParamType;
2601
Douglas Gregorff59f672010-01-21 15:46:19 +00002602 if (!CandidateSet.empty()) {
2603 // Sort the overload candidate set by placing the best overloads first.
2604 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCallbc077cf2010-02-08 23:07:23 +00002605 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregorcabea402009-09-22 15:41:20 +00002606
Douglas Gregorff59f672010-01-21 15:46:19 +00002607 // Add the remaining viable overload candidates as code-completion reslults.
2608 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2609 CandEnd = CandidateSet.end();
2610 Cand != CandEnd; ++Cand) {
2611 if (Cand->Viable)
2612 Results.push_back(ResultCandidate(Cand->Function));
2613 }
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002614
2615 // From the viable candidates, try to determine the type of this parameter.
2616 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2617 if (const FunctionType *FType = Results[I].getFunctionType())
2618 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2619 if (NumArgs < Proto->getNumArgs()) {
2620 if (ParamType.isNull())
2621 ParamType = Proto->getArgType(NumArgs);
2622 else if (!Context.hasSameUnqualifiedType(
2623 ParamType.getNonReferenceType(),
2624 Proto->getArgType(NumArgs).getNonReferenceType())) {
2625 ParamType = QualType();
2626 break;
2627 }
2628 }
2629 }
2630 } else {
2631 // Try to determine the parameter type from the type of the expression
2632 // being called.
2633 QualType FunctionType = Fn->getType();
2634 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2635 FunctionType = Ptr->getPointeeType();
2636 else if (const BlockPointerType *BlockPtr
2637 = FunctionType->getAs<BlockPointerType>())
2638 FunctionType = BlockPtr->getPointeeType();
2639 else if (const MemberPointerType *MemPtr
2640 = FunctionType->getAs<MemberPointerType>())
2641 FunctionType = MemPtr->getPointeeType();
2642
2643 if (const FunctionProtoType *Proto
2644 = FunctionType->getAs<FunctionProtoType>()) {
2645 if (NumArgs < Proto->getNumArgs())
2646 ParamType = Proto->getArgType(NumArgs);
2647 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002648 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00002649
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002650 if (ParamType.isNull())
2651 CodeCompleteOrdinaryName(S, CCC_Expression);
2652 else
2653 CodeCompleteExpression(S, ParamType);
2654
Douglas Gregorc01890e2010-04-06 20:19:47 +00002655 if (!Results.empty())
Douglas Gregor3ef59522009-12-11 19:06:04 +00002656 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2657 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00002658}
2659
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002660void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2661 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2662 if (!VD) {
2663 CodeCompleteOrdinaryName(S, CCC_Expression);
2664 return;
2665 }
2666
2667 CodeCompleteExpression(S, VD->getType());
2668}
2669
2670void Sema::CodeCompleteReturn(Scope *S) {
2671 QualType ResultType;
2672 if (isa<BlockDecl>(CurContext)) {
2673 if (BlockScopeInfo *BSI = getCurBlock())
2674 ResultType = BSI->ReturnType;
2675 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2676 ResultType = Function->getResultType();
2677 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2678 ResultType = Method->getResultType();
2679
2680 if (ResultType.isNull())
2681 CodeCompleteOrdinaryName(S, CCC_Expression);
2682 else
2683 CodeCompleteExpression(S, ResultType);
2684}
2685
2686void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2687 if (LHS)
2688 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2689 else
2690 CodeCompleteOrdinaryName(S, CCC_Expression);
2691}
2692
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002693void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00002694 bool EnteringContext) {
2695 if (!SS.getScopeRep() || !CodeCompleter)
2696 return;
2697
Douglas Gregor3545ff42009-09-21 16:56:56 +00002698 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2699 if (!Ctx)
2700 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00002701
2702 // Try to instantiate any non-dependent declaration contexts before
2703 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00002704 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00002705 return;
2706
Douglas Gregor3545ff42009-09-21 16:56:56 +00002707 ResultBuilder Results(*this);
Douglas Gregor200c99d2010-01-14 03:35:48 +00002708 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2709 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002710
2711 // The "template" keyword can follow "::" in the grammar, but only
2712 // put it into the grammar if the nested-name-specifier is dependent.
2713 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2714 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00002715 Results.AddResult("template");
Douglas Gregor3545ff42009-09-21 16:56:56 +00002716
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002717 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002718}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002719
2720void Sema::CodeCompleteUsing(Scope *S) {
2721 if (!CodeCompleter)
2722 return;
2723
Douglas Gregor3545ff42009-09-21 16:56:56 +00002724 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002725 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002726
2727 // If we aren't in class scope, we could see the "namespace" keyword.
2728 if (!S->isClassScope())
Douglas Gregor78a21012010-01-14 16:01:26 +00002729 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002730
2731 // After "using", we can see anything that would start a
2732 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002733 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2734 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002735 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002736
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002737 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002738}
2739
2740void Sema::CodeCompleteUsingDirective(Scope *S) {
2741 if (!CodeCompleter)
2742 return;
2743
Douglas Gregor3545ff42009-09-21 16:56:56 +00002744 // After "using namespace", we expect to see a namespace name or namespace
2745 // alias.
2746 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002747 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002748 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2749 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002750 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002751 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002752}
2753
2754void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2755 if (!CodeCompleter)
2756 return;
2757
Douglas Gregor3545ff42009-09-21 16:56:56 +00002758 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2759 DeclContext *Ctx = (DeclContext *)S->getEntity();
2760 if (!S->getParent())
2761 Ctx = Context.getTranslationUnitDecl();
2762
2763 if (Ctx && Ctx->isFileContext()) {
2764 // We only want to see those namespaces that have already been defined
2765 // within this scope, because its likely that the user is creating an
2766 // extended namespace declaration. Keep track of the most recent
2767 // definition of each namespace.
2768 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2769 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2770 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2771 NS != NSEnd; ++NS)
2772 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2773
2774 // Add the most recent definition (or extended definition) of each
2775 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00002776 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002777 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2778 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2779 NS != NSEnd; ++NS)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002780 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2781 CurContext, 0, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002782 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002783 }
2784
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002785 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002786}
2787
2788void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2789 if (!CodeCompleter)
2790 return;
2791
Douglas Gregor3545ff42009-09-21 16:56:56 +00002792 // After "namespace", we expect to see a namespace or alias.
2793 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002794 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2795 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002796 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002797}
2798
Douglas Gregorc811ede2009-09-18 20:05:18 +00002799void Sema::CodeCompleteOperatorName(Scope *S) {
2800 if (!CodeCompleter)
2801 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002802
2803 typedef CodeCompleteConsumer::Result Result;
2804 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002805 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00002806
Douglas Gregor3545ff42009-09-21 16:56:56 +00002807 // Add the names of overloadable operators.
2808#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2809 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00002810 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002811#include "clang/Basic/OperatorKinds.def"
2812
2813 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002814 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002815 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2816 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002817
2818 // Add any type specifiers
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002819 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002820 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002821
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002822 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00002823}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002824
Douglas Gregorf1934162010-01-13 21:24:21 +00002825// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2826// true or false.
2827#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002828static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002829 ResultBuilder &Results,
2830 bool NeedAt) {
2831 typedef CodeCompleteConsumer::Result Result;
2832 // Since we have an implementation, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002833 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002834
2835 CodeCompletionString *Pattern = 0;
2836 if (LangOpts.ObjC2) {
2837 // @dynamic
2838 Pattern = new CodeCompletionString;
2839 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2840 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2841 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002842 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002843
2844 // @synthesize
2845 Pattern = new CodeCompletionString;
2846 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2847 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2848 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002849 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002850 }
2851}
2852
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002853static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002854 ResultBuilder &Results,
2855 bool NeedAt) {
2856 typedef CodeCompleteConsumer::Result Result;
2857
2858 // Since we have an interface or protocol, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002859 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002860
2861 if (LangOpts.ObjC2) {
2862 // @property
Douglas Gregor78a21012010-01-14 16:01:26 +00002863 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002864
2865 // @required
Douglas Gregor78a21012010-01-14 16:01:26 +00002866 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002867
2868 // @optional
Douglas Gregor78a21012010-01-14 16:01:26 +00002869 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002870 }
2871}
2872
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002873static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00002874 typedef CodeCompleteConsumer::Result Result;
2875 CodeCompletionString *Pattern = 0;
2876
2877 // @class name ;
2878 Pattern = new CodeCompletionString;
2879 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2880 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00002881 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00002882 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002883
Douglas Gregorf4c33342010-05-28 00:22:41 +00002884 if (Results.includeCodePatterns()) {
2885 // @interface name
2886 // FIXME: Could introduce the whole pattern, including superclasses and
2887 // such.
2888 Pattern = new CodeCompletionString;
2889 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2890 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2891 Pattern->AddPlaceholderChunk("class");
2892 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002893
Douglas Gregorf4c33342010-05-28 00:22:41 +00002894 // @protocol name
2895 Pattern = new CodeCompletionString;
2896 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2897 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2898 Pattern->AddPlaceholderChunk("protocol");
2899 Results.AddResult(Result(Pattern));
2900
2901 // @implementation name
2902 Pattern = new CodeCompletionString;
2903 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2904 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2905 Pattern->AddPlaceholderChunk("class");
2906 Results.AddResult(Result(Pattern));
2907 }
Douglas Gregorf1934162010-01-13 21:24:21 +00002908
2909 // @compatibility_alias name
2910 Pattern = new CodeCompletionString;
2911 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2912 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2913 Pattern->AddPlaceholderChunk("alias");
2914 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2915 Pattern->AddPlaceholderChunk("class");
Douglas Gregor78a21012010-01-14 16:01:26 +00002916 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002917}
2918
Douglas Gregorf48706c2009-12-07 09:27:33 +00002919void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2920 bool InInterface) {
2921 typedef CodeCompleteConsumer::Result Result;
2922 ResultBuilder Results(*this);
2923 Results.EnterNewScope();
Douglas Gregorf1934162010-01-13 21:24:21 +00002924 if (ObjCImpDecl)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002925 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00002926 else if (InInterface)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002927 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00002928 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002929 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00002930 Results.ExitScope();
2931 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2932}
2933
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002934static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002935 typedef CodeCompleteConsumer::Result Result;
2936 CodeCompletionString *Pattern = 0;
2937
2938 // @encode ( type-name )
2939 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002940 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002941 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2942 Pattern->AddPlaceholderChunk("type-name");
2943 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002944 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002945
2946 // @protocol ( protocol-name )
2947 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002948 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002949 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2950 Pattern->AddPlaceholderChunk("protocol-name");
2951 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002952 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002953
2954 // @selector ( selector )
2955 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002956 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002957 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2958 Pattern->AddPlaceholderChunk("selector");
2959 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00002960 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002961}
2962
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002963static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002964 typedef CodeCompleteConsumer::Result Result;
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002965 CodeCompletionString *Pattern = 0;
Douglas Gregorf1934162010-01-13 21:24:21 +00002966
Douglas Gregorf4c33342010-05-28 00:22:41 +00002967 if (Results.includeCodePatterns()) {
2968 // @try { statements } @catch ( declaration ) { statements } @finally
2969 // { statements }
2970 Pattern = new CodeCompletionString;
2971 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2972 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2973 Pattern->AddPlaceholderChunk("statements");
2974 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2975 Pattern->AddTextChunk("@catch");
2976 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2977 Pattern->AddPlaceholderChunk("parameter");
2978 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2979 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2980 Pattern->AddPlaceholderChunk("statements");
2981 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2982 Pattern->AddTextChunk("@finally");
2983 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2984 Pattern->AddPlaceholderChunk("statements");
2985 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2986 Results.AddResult(Result(Pattern));
2987 }
Douglas Gregorf1934162010-01-13 21:24:21 +00002988
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002989 // @throw
2990 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00002991 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor6a803932010-01-12 06:38:28 +00002992 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00002993 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor78a21012010-01-14 16:01:26 +00002994 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002995
Douglas Gregorf4c33342010-05-28 00:22:41 +00002996 if (Results.includeCodePatterns()) {
2997 // @synchronized ( expression ) { statements }
2998 Pattern = new CodeCompletionString;
2999 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3000 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3001 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3002 Pattern->AddPlaceholderChunk("expression");
3003 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3004 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3005 Pattern->AddPlaceholderChunk("statements");
3006 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3007 Results.AddResult(Result(Pattern));
3008 }
Douglas Gregorf1934162010-01-13 21:24:21 +00003009}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003010
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003011static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00003012 ResultBuilder &Results,
3013 bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003014 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor78a21012010-01-14 16:01:26 +00003015 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3016 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3017 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003018 if (LangOpts.ObjC2)
Douglas Gregor78a21012010-01-14 16:01:26 +00003019 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003020}
3021
3022void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3023 ResultBuilder Results(*this);
3024 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003025 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00003026 Results.ExitScope();
3027 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3028}
3029
3030void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003031 ResultBuilder Results(*this);
3032 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003033 AddObjCStatementResults(Results, false);
3034 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003035 Results.ExitScope();
3036 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3037}
3038
3039void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3040 ResultBuilder Results(*this);
3041 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003042 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003043 Results.ExitScope();
3044 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3045}
3046
Douglas Gregore6078da2009-11-19 00:14:45 +00003047/// \brief Determine whether the addition of the given flag to an Objective-C
3048/// property's attributes will cause a conflict.
3049static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3050 // Check if we've already added this flag.
3051 if (Attributes & NewFlag)
3052 return true;
3053
3054 Attributes |= NewFlag;
3055
3056 // Check for collisions with "readonly".
3057 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3058 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3059 ObjCDeclSpec::DQ_PR_assign |
3060 ObjCDeclSpec::DQ_PR_copy |
3061 ObjCDeclSpec::DQ_PR_retain)))
3062 return true;
3063
3064 // Check for more than one of { assign, copy, retain }.
3065 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3066 ObjCDeclSpec::DQ_PR_copy |
3067 ObjCDeclSpec::DQ_PR_retain);
3068 if (AssignCopyRetMask &&
3069 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3070 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3071 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3072 return true;
3073
3074 return false;
3075}
3076
Douglas Gregor36029f42009-11-18 23:08:07 +00003077void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00003078 if (!CodeCompleter)
3079 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00003080
Steve Naroff936354c2009-10-08 21:55:05 +00003081 unsigned Attributes = ODS.getPropertyAttributes();
3082
3083 typedef CodeCompleteConsumer::Result Result;
3084 ResultBuilder Results(*this);
3085 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00003086 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregor78a21012010-01-14 16:01:26 +00003087 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003088 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregor78a21012010-01-14 16:01:26 +00003089 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003090 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregor78a21012010-01-14 16:01:26 +00003091 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003092 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregor78a21012010-01-14 16:01:26 +00003093 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003094 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregor78a21012010-01-14 16:01:26 +00003095 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003096 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregor78a21012010-01-14 16:01:26 +00003097 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003098 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003099 CodeCompletionString *Setter = new CodeCompletionString;
3100 Setter->AddTypedTextChunk("setter");
3101 Setter->AddTextChunk(" = ");
3102 Setter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003103 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003104 }
Douglas Gregore6078da2009-11-19 00:14:45 +00003105 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003106 CodeCompletionString *Getter = new CodeCompletionString;
3107 Getter->AddTypedTextChunk("getter");
3108 Getter->AddTextChunk(" = ");
3109 Getter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003110 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003111 }
Steve Naroff936354c2009-10-08 21:55:05 +00003112 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003113 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00003114}
Steve Naroffeae65032009-11-07 02:08:14 +00003115
Douglas Gregorc8537c52009-11-19 07:41:15 +00003116/// \brief Descripts the kind of Objective-C method that we want to find
3117/// via code completion.
3118enum ObjCMethodKind {
3119 MK_Any, //< Any kind of method, provided it means other specified criteria.
3120 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3121 MK_OneArgSelector //< One-argument selector.
3122};
3123
3124static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3125 ObjCMethodKind WantKind,
3126 IdentifierInfo **SelIdents,
3127 unsigned NumSelIdents) {
3128 Selector Sel = Method->getSelector();
3129 if (NumSelIdents > Sel.getNumArgs())
3130 return false;
3131
3132 switch (WantKind) {
3133 case MK_Any: break;
3134 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3135 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3136 }
3137
3138 for (unsigned I = 0; I != NumSelIdents; ++I)
3139 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3140 return false;
3141
3142 return true;
3143}
3144
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003145/// \brief Add all of the Objective-C methods in the given Objective-C
3146/// container to the set of results.
3147///
3148/// The container will be a class, protocol, category, or implementation of
3149/// any of the above. This mether will recurse to include methods from
3150/// the superclasses of classes along with their categories, protocols, and
3151/// implementations.
3152///
3153/// \param Container the container in which we'll look to find methods.
3154///
3155/// \param WantInstance whether to add instance methods (only); if false, this
3156/// routine will add factory methods (only).
3157///
3158/// \param CurContext the context in which we're performing the lookup that
3159/// finds methods.
3160///
3161/// \param Results the structure into which we'll add results.
3162static void AddObjCMethods(ObjCContainerDecl *Container,
3163 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00003164 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003165 IdentifierInfo **SelIdents,
3166 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003167 DeclContext *CurContext,
3168 ResultBuilder &Results) {
3169 typedef CodeCompleteConsumer::Result Result;
3170 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3171 MEnd = Container->meth_end();
3172 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00003173 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3174 // Check whether the selector identifiers we've been given are a
3175 // subset of the identifiers for this particular method.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003176 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregor1b605f72009-11-19 01:08:35 +00003177 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003178
Douglas Gregor1b605f72009-11-19 01:08:35 +00003179 Result R = Result(*M, 0);
3180 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003181 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor1b605f72009-11-19 01:08:35 +00003182 Results.MaybeAddResult(R, CurContext);
3183 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003184 }
3185
3186 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3187 if (!IFace)
3188 return;
3189
3190 // Add methods in protocols.
3191 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3192 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3193 E = Protocols.end();
3194 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003195 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003196 CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003197
3198 // Add methods in categories.
3199 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3200 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00003201 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3202 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003203
3204 // Add a categories protocol methods.
3205 const ObjCList<ObjCProtocolDecl> &Protocols
3206 = CatDecl->getReferencedProtocols();
3207 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3208 E = Protocols.end();
3209 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003210 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3211 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003212
3213 // Add methods in category implementations.
3214 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003215 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3216 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003217 }
3218
3219 // Add methods in superclass.
3220 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003221 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3222 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003223
3224 // Add methods in our implementation, if any.
3225 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003226 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3227 NumSelIdents, CurContext, Results);
3228}
3229
3230
3231void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3232 DeclPtrTy *Methods,
3233 unsigned NumMethods) {
3234 typedef CodeCompleteConsumer::Result Result;
3235
3236 // Try to find the interface where getters might live.
3237 ObjCInterfaceDecl *Class
3238 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3239 if (!Class) {
3240 if (ObjCCategoryDecl *Category
3241 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3242 Class = Category->getClassInterface();
3243
3244 if (!Class)
3245 return;
3246 }
3247
3248 // Find all of the potential getters.
3249 ResultBuilder Results(*this);
3250 Results.EnterNewScope();
3251
3252 // FIXME: We need to do this because Objective-C methods don't get
3253 // pushed into DeclContexts early enough. Argh!
3254 for (unsigned I = 0; I != NumMethods; ++I) {
3255 if (ObjCMethodDecl *Method
3256 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3257 if (Method->isInstanceMethod() &&
3258 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3259 Result R = Result(Method, 0);
3260 R.AllParametersAreInformative = true;
3261 Results.MaybeAddResult(R, CurContext);
3262 }
3263 }
3264
3265 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3266 Results.ExitScope();
3267 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3268}
3269
3270void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3271 DeclPtrTy *Methods,
3272 unsigned NumMethods) {
3273 typedef CodeCompleteConsumer::Result Result;
3274
3275 // Try to find the interface where setters might live.
3276 ObjCInterfaceDecl *Class
3277 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3278 if (!Class) {
3279 if (ObjCCategoryDecl *Category
3280 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3281 Class = Category->getClassInterface();
3282
3283 if (!Class)
3284 return;
3285 }
3286
3287 // Find all of the potential getters.
3288 ResultBuilder Results(*this);
3289 Results.EnterNewScope();
3290
3291 // FIXME: We need to do this because Objective-C methods don't get
3292 // pushed into DeclContexts early enough. Argh!
3293 for (unsigned I = 0; I != NumMethods; ++I) {
3294 if (ObjCMethodDecl *Method
3295 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3296 if (Method->isInstanceMethod() &&
3297 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3298 Result R = Result(Method, 0);
3299 R.AllParametersAreInformative = true;
3300 Results.MaybeAddResult(R, CurContext);
3301 }
3302 }
3303
3304 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3305
3306 Results.ExitScope();
3307 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003308}
3309
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003310/// \brief When we have an expression with type "id", we may assume
3311/// that it has some more-specific class type based on knowledge of
3312/// common uses of Objective-C. This routine returns that class type,
3313/// or NULL if no better result could be determined.
3314static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3315 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3316 if (!Msg)
3317 return 0;
3318
3319 Selector Sel = Msg->getSelector();
3320 if (Sel.isNull())
3321 return 0;
3322
3323 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3324 if (!Id)
3325 return 0;
3326
3327 ObjCMethodDecl *Method = Msg->getMethodDecl();
3328 if (!Method)
3329 return 0;
3330
3331 // Determine the class that we're sending the message to.
Douglas Gregor9a129192010-04-21 00:45:42 +00003332 ObjCInterfaceDecl *IFace = 0;
3333 switch (Msg->getReceiverKind()) {
3334 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00003335 if (const ObjCObjectType *ObjType
3336 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3337 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00003338 break;
3339
3340 case ObjCMessageExpr::Instance: {
3341 QualType T = Msg->getInstanceReceiver()->getType();
3342 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3343 IFace = Ptr->getInterfaceDecl();
3344 break;
3345 }
3346
3347 case ObjCMessageExpr::SuperInstance:
3348 case ObjCMessageExpr::SuperClass:
3349 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003350 }
3351
3352 if (!IFace)
3353 return 0;
3354
3355 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3356 if (Method->isInstanceMethod())
3357 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3358 .Case("retain", IFace)
3359 .Case("autorelease", IFace)
3360 .Case("copy", IFace)
3361 .Case("copyWithZone", IFace)
3362 .Case("mutableCopy", IFace)
3363 .Case("mutableCopyWithZone", IFace)
3364 .Case("awakeFromCoder", IFace)
3365 .Case("replacementObjectFromCoder", IFace)
3366 .Case("class", IFace)
3367 .Case("classForCoder", IFace)
3368 .Case("superclass", Super)
3369 .Default(0);
3370
3371 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3372 .Case("new", IFace)
3373 .Case("alloc", IFace)
3374 .Case("allocWithZone", IFace)
3375 .Case("class", IFace)
3376 .Case("superclass", Super)
3377 .Default(0);
3378}
3379
Douglas Gregora817a192010-05-27 23:06:34 +00003380void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3381 typedef CodeCompleteConsumer::Result Result;
3382 ResultBuilder Results(*this);
3383
3384 // Find anything that looks like it could be a message receiver.
3385 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3386 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3387 Results.EnterNewScope();
3388 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
3389
3390 // If we are in an Objective-C method inside a class that has a superclass,
3391 // add "super" as an option.
3392 if (ObjCMethodDecl *Method = getCurMethodDecl())
3393 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3394 if (Iface->getSuperClass())
3395 Results.AddResult(Result("super"));
3396
3397 Results.ExitScope();
3398
3399 if (CodeCompleter->includeMacros())
3400 AddMacroResults(PP, Results);
3401 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3402
3403}
3404
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003405void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3406 IdentifierInfo **SelIdents,
3407 unsigned NumSelIdents) {
3408 ObjCInterfaceDecl *CDecl = 0;
3409 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3410 // Figure out which interface we're in.
3411 CDecl = CurMethod->getClassInterface();
3412 if (!CDecl)
3413 return;
3414
3415 // Find the superclass of this class.
3416 CDecl = CDecl->getSuperClass();
3417 if (!CDecl)
3418 return;
3419
3420 if (CurMethod->isInstanceMethod()) {
3421 // We are inside an instance method, which means that the message
3422 // send [super ...] is actually calling an instance method on the
3423 // current object. Build the super expression and handle this like
3424 // an instance method.
3425 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3426 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3427 OwningExprResult Super
3428 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3429 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3430 SelIdents, NumSelIdents);
3431 }
3432
3433 // Fall through to send to the superclass in CDecl.
3434 } else {
3435 // "super" may be the name of a type or variable. Figure out which
3436 // it is.
3437 IdentifierInfo *Super = &Context.Idents.get("super");
3438 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3439 LookupOrdinaryName);
3440 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3441 // "super" names an interface. Use it.
3442 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00003443 if (const ObjCObjectType *Iface
3444 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3445 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003446 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3447 // "super" names an unresolved type; we can't be more specific.
3448 } else {
3449 // Assume that "super" names some kind of value and parse that way.
3450 CXXScopeSpec SS;
3451 UnqualifiedId id;
3452 id.setIdentifier(Super, SuperLoc);
3453 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3454 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3455 SelIdents, NumSelIdents);
3456 }
3457
3458 // Fall through
3459 }
3460
3461 TypeTy *Receiver = 0;
3462 if (CDecl)
3463 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3464 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3465 NumSelIdents);
3466}
3467
3468void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003469 IdentifierInfo **SelIdents,
3470 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003471 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00003472 ObjCInterfaceDecl *CDecl = 0;
3473
Douglas Gregor8ce33212009-11-17 17:59:40 +00003474 // If the given name refers to an interface type, retrieve the
3475 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003476 if (Receiver) {
3477 QualType T = GetTypeFromParser(Receiver, 0);
3478 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00003479 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3480 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00003481 }
3482
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003483 // Add all of the factory methods in this Objective-C class, its protocols,
3484 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00003485 ResultBuilder Results(*this);
3486 Results.EnterNewScope();
Douglas Gregor6285f752010-04-06 16:40:00 +00003487
3488 if (CDecl)
3489 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3490 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003491 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00003492 // We're messaging "id" as a type; provide all class/factory methods.
3493
Douglas Gregord720daf2010-04-06 17:30:22 +00003494 // If we have an external source, load the entire class method
3495 // pool from the PCH file.
3496 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00003497 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3498 I != N; ++I) {
3499 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregord720daf2010-04-06 17:30:22 +00003500 if (Sel.isNull() || FactoryMethodPool.count(Sel) ||
3501 InstanceMethodPool.count(Sel))
3502 continue;
3503
3504 ReadMethodPool(Sel, /*isInstance=*/false);
3505 }
3506 }
3507
Douglas Gregor6285f752010-04-06 16:40:00 +00003508 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3509 M = FactoryMethodPool.begin(),
3510 MEnd = FactoryMethodPool.end();
3511 M != MEnd;
3512 ++M) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003513 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003514 MethList = MethList->Next) {
3515 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3516 NumSelIdents))
3517 continue;
3518
3519 Result R(MethList->Method, 0);
3520 R.StartParameter = NumSelIdents;
3521 R.AllParametersAreInformative = false;
3522 Results.MaybeAddResult(R, CurContext);
3523 }
3524 }
3525 }
3526
Steve Naroffeae65032009-11-07 02:08:14 +00003527 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003528 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003529}
3530
Douglas Gregor1b605f72009-11-19 01:08:35 +00003531void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3532 IdentifierInfo **SelIdents,
3533 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003534 typedef CodeCompleteConsumer::Result Result;
Steve Naroffeae65032009-11-07 02:08:14 +00003535
3536 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00003537
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003538 // If necessary, apply function/array conversion to the receiver.
3539 // C99 6.7.5.3p[7,8].
Douglas Gregorb92a1562010-02-03 00:27:59 +00003540 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003541 QualType ReceiverType = RecExpr->getType();
Steve Naroffeae65032009-11-07 02:08:14 +00003542
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003543 // Build the set of methods we can see.
3544 ResultBuilder Results(*this);
3545 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003546
3547 // If we're messaging an expression with type "id" or "Class", check
3548 // whether we know something special about the receiver that allows
3549 // us to assume a more-specific receiver type.
3550 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3551 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3552 ReceiverType = Context.getObjCObjectPointerType(
3553 Context.getObjCInterfaceType(IFace));
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003554
Douglas Gregora3329fa2009-11-18 00:06:18 +00003555 // Handle messages to Class. This really isn't a message to an instance
3556 // method, so we treat it the same way we would treat a message send to a
3557 // class method.
3558 if (ReceiverType->isObjCClassType() ||
3559 ReceiverType->isObjCQualifiedClassType()) {
3560 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3561 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003562 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3563 CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003564 }
3565 }
3566 // Handle messages to a qualified ID ("id<foo>").
3567 else if (const ObjCObjectPointerType *QualID
3568 = ReceiverType->getAsObjCQualifiedIdType()) {
3569 // Search protocols for instance methods.
3570 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3571 E = QualID->qual_end();
3572 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003573 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3574 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003575 }
3576 // Handle messages to a pointer to interface type.
3577 else if (const ObjCObjectPointerType *IFacePtr
3578 = ReceiverType->getAsObjCInterfacePointerType()) {
3579 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003580 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3581 NumSelIdents, CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003582
3583 // Search protocols for instance methods.
3584 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3585 E = IFacePtr->qual_end();
3586 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003587 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3588 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003589 }
Douglas Gregor6285f752010-04-06 16:40:00 +00003590 // Handle messages to "id".
3591 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003592 // We're messaging "id", so provide all instance methods we know
3593 // about as code-completion results.
3594
3595 // If we have an external source, load the entire class method
3596 // pool from the PCH file.
3597 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00003598 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3599 I != N; ++I) {
3600 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregord720daf2010-04-06 17:30:22 +00003601 if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
3602 FactoryMethodPool.count(Sel))
3603 continue;
3604
3605 ReadMethodPool(Sel, /*isInstance=*/true);
3606 }
3607 }
3608
Douglas Gregor6285f752010-04-06 16:40:00 +00003609 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3610 M = InstanceMethodPool.begin(),
3611 MEnd = InstanceMethodPool.end();
3612 M != MEnd;
3613 ++M) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003614 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003615 MethList = MethList->Next) {
3616 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3617 NumSelIdents))
3618 continue;
3619
3620 Result R(MethList->Method, 0);
3621 R.StartParameter = NumSelIdents;
3622 R.AllParametersAreInformative = false;
3623 Results.MaybeAddResult(R, CurContext);
3624 }
3625 }
3626 }
3627
Steve Naroffeae65032009-11-07 02:08:14 +00003628 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003629 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003630}
Douglas Gregorbaf69612009-11-18 04:19:12 +00003631
3632/// \brief Add all of the protocol declarations that we find in the given
3633/// (translation unit) context.
3634static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003635 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00003636 ResultBuilder &Results) {
3637 typedef CodeCompleteConsumer::Result Result;
3638
3639 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3640 DEnd = Ctx->decls_end();
3641 D != DEnd; ++D) {
3642 // Record any protocols we find.
3643 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003644 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003645 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003646
3647 // Record any forward-declared protocols we find.
3648 if (ObjCForwardProtocolDecl *Forward
3649 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3650 for (ObjCForwardProtocolDecl::protocol_iterator
3651 P = Forward->protocol_begin(),
3652 PEnd = Forward->protocol_end();
3653 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003654 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003655 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003656 }
3657 }
3658}
3659
3660void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3661 unsigned NumProtocols) {
3662 ResultBuilder Results(*this);
3663 Results.EnterNewScope();
3664
3665 // Tell the result set to ignore all of the protocols we have
3666 // already seen.
3667 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003668 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3669 Protocols[I].second))
Douglas Gregorbaf69612009-11-18 04:19:12 +00003670 Results.Ignore(Protocol);
3671
3672 // Add all protocols.
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003673 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3674 Results);
3675
3676 Results.ExitScope();
3677 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3678}
3679
3680void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3681 ResultBuilder Results(*this);
3682 Results.EnterNewScope();
3683
3684 // Add all protocols.
3685 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3686 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003687
3688 Results.ExitScope();
3689 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3690}
Douglas Gregor49c22a72009-11-18 16:26:39 +00003691
3692/// \brief Add all of the Objective-C interface declarations that we find in
3693/// the given (translation unit) context.
3694static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3695 bool OnlyForwardDeclarations,
3696 bool OnlyUnimplemented,
3697 ResultBuilder &Results) {
3698 typedef CodeCompleteConsumer::Result Result;
3699
3700 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3701 DEnd = Ctx->decls_end();
3702 D != DEnd; ++D) {
3703 // Record any interfaces we find.
3704 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3705 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3706 (!OnlyUnimplemented || !Class->getImplementation()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003707 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003708
3709 // Record any forward-declared interfaces we find.
3710 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3711 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3712 C != CEnd; ++C)
3713 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3714 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003715 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3716 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003717 }
3718 }
3719}
3720
3721void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3722 ResultBuilder Results(*this);
3723 Results.EnterNewScope();
3724
3725 // Add all classes.
3726 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3727 false, Results);
3728
3729 Results.ExitScope();
3730 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3731}
3732
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003733void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3734 SourceLocation ClassNameLoc) {
Douglas Gregor49c22a72009-11-18 16:26:39 +00003735 ResultBuilder Results(*this);
3736 Results.EnterNewScope();
3737
3738 // Make sure that we ignore the class we're currently defining.
3739 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003740 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003741 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00003742 Results.Ignore(CurClass);
3743
3744 // Add all classes.
3745 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3746 false, Results);
3747
3748 Results.ExitScope();
3749 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3750}
3751
3752void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3753 ResultBuilder Results(*this);
3754 Results.EnterNewScope();
3755
3756 // Add all unimplemented classes.
3757 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3758 true, Results);
3759
3760 Results.ExitScope();
3761 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3762}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003763
3764void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003765 IdentifierInfo *ClassName,
3766 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003767 typedef CodeCompleteConsumer::Result Result;
3768
3769 ResultBuilder Results(*this);
3770
3771 // Ignore any categories we find that have already been implemented by this
3772 // interface.
3773 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3774 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003775 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003776 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3777 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3778 Category = Category->getNextClassCategory())
3779 CategoryNames.insert(Category->getIdentifier());
3780
3781 // Add all of the categories we know about.
3782 Results.EnterNewScope();
3783 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3784 for (DeclContext::decl_iterator D = TU->decls_begin(),
3785 DEnd = TU->decls_end();
3786 D != DEnd; ++D)
3787 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3788 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003789 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003790 Results.ExitScope();
3791
3792 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3793}
3794
3795void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003796 IdentifierInfo *ClassName,
3797 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003798 typedef CodeCompleteConsumer::Result Result;
3799
3800 // Find the corresponding interface. If we couldn't find the interface, the
3801 // program itself is ill-formed. However, we'll try to be helpful still by
3802 // providing the list of all of the categories we know about.
3803 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003804 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003805 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3806 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003807 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003808
3809 ResultBuilder Results(*this);
3810
3811 // Add all of the categories that have have corresponding interface
3812 // declarations in this class and any of its superclasses, except for
3813 // already-implemented categories in the class itself.
3814 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3815 Results.EnterNewScope();
3816 bool IgnoreImplemented = true;
3817 while (Class) {
3818 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3819 Category = Category->getNextClassCategory())
3820 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3821 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003822 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003823
3824 Class = Class->getSuperClass();
3825 IgnoreImplemented = false;
3826 }
3827 Results.ExitScope();
3828
3829 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3830}
Douglas Gregor5d649882009-11-18 22:32:06 +00003831
Douglas Gregor52e78bd2009-11-18 22:56:13 +00003832void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor5d649882009-11-18 22:32:06 +00003833 typedef CodeCompleteConsumer::Result Result;
3834 ResultBuilder Results(*this);
3835
3836 // Figure out where this @synthesize lives.
3837 ObjCContainerDecl *Container
3838 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3839 if (!Container ||
3840 (!isa<ObjCImplementationDecl>(Container) &&
3841 !isa<ObjCCategoryImplDecl>(Container)))
3842 return;
3843
3844 // Ignore any properties that have already been implemented.
3845 for (DeclContext::decl_iterator D = Container->decls_begin(),
3846 DEnd = Container->decls_end();
3847 D != DEnd; ++D)
3848 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3849 Results.Ignore(PropertyImpl->getPropertyDecl());
3850
3851 // Add any properties that we find.
3852 Results.EnterNewScope();
3853 if (ObjCImplementationDecl *ClassImpl
3854 = dyn_cast<ObjCImplementationDecl>(Container))
3855 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3856 Results);
3857 else
3858 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3859 false, CurContext, Results);
3860 Results.ExitScope();
3861
3862 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3863}
3864
3865void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3866 IdentifierInfo *PropertyName,
3867 DeclPtrTy ObjCImpDecl) {
3868 typedef CodeCompleteConsumer::Result Result;
3869 ResultBuilder Results(*this);
3870
3871 // Figure out where this @synthesize lives.
3872 ObjCContainerDecl *Container
3873 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3874 if (!Container ||
3875 (!isa<ObjCImplementationDecl>(Container) &&
3876 !isa<ObjCCategoryImplDecl>(Container)))
3877 return;
3878
3879 // Figure out which interface we're looking into.
3880 ObjCInterfaceDecl *Class = 0;
3881 if (ObjCImplementationDecl *ClassImpl
3882 = dyn_cast<ObjCImplementationDecl>(Container))
3883 Class = ClassImpl->getClassInterface();
3884 else
3885 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3886 ->getClassInterface();
3887
3888 // Add all of the instance variables in this class and its superclasses.
3889 Results.EnterNewScope();
3890 for(; Class; Class = Class->getSuperClass()) {
3891 // FIXME: We could screen the type of each ivar for compatibility with
3892 // the property, but is that being too paternal?
3893 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3894 IVarEnd = Class->ivar_end();
3895 IVar != IVarEnd; ++IVar)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003896 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor5d649882009-11-18 22:32:06 +00003897 }
3898 Results.ExitScope();
3899
3900 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3901}
Douglas Gregor636a61e2010-04-07 00:21:17 +00003902
3903typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
3904
3905/// \brief Find all of the methods that reside in the given container
3906/// (and its superclasses, protocols, etc.) that meet the given
3907/// criteria. Insert those methods into the map of known methods,
3908/// indexed by selector so they can be easily found.
3909static void FindImplementableMethods(ASTContext &Context,
3910 ObjCContainerDecl *Container,
3911 bool WantInstanceMethods,
3912 QualType ReturnType,
3913 bool IsInImplementation,
3914 KnownMethodsMap &KnownMethods) {
3915 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
3916 // Recurse into protocols.
3917 const ObjCList<ObjCProtocolDecl> &Protocols
3918 = IFace->getReferencedProtocols();
3919 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3920 E = Protocols.end();
3921 I != E; ++I)
3922 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3923 IsInImplementation, KnownMethods);
3924
3925 // If we're not in the implementation of a class, also visit the
3926 // superclass.
3927 if (!IsInImplementation && IFace->getSuperClass())
3928 FindImplementableMethods(Context, IFace->getSuperClass(),
3929 WantInstanceMethods, ReturnType,
3930 IsInImplementation, KnownMethods);
3931
3932 // Add methods from any class extensions (but not from categories;
3933 // those should go into category implementations).
3934 for (ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
3935 Cat = Cat->getNextClassCategory()) {
3936 if (!Cat->IsClassExtension())
3937 continue;
3938
3939 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
3940 IsInImplementation, KnownMethods);
3941 }
3942 }
3943
3944 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
3945 // Recurse into protocols.
3946 const ObjCList<ObjCProtocolDecl> &Protocols
3947 = Category->getReferencedProtocols();
3948 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3949 E = Protocols.end();
3950 I != E; ++I)
3951 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3952 IsInImplementation, KnownMethods);
3953 }
3954
3955 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3956 // Recurse into protocols.
3957 const ObjCList<ObjCProtocolDecl> &Protocols
3958 = Protocol->getReferencedProtocols();
3959 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3960 E = Protocols.end();
3961 I != E; ++I)
3962 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3963 IsInImplementation, KnownMethods);
3964 }
3965
3966 // Add methods in this container. This operation occurs last because
3967 // we want the methods from this container to override any methods
3968 // we've previously seen with the same selector.
3969 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3970 MEnd = Container->meth_end();
3971 M != MEnd; ++M) {
3972 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3973 if (!ReturnType.isNull() &&
3974 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
3975 continue;
3976
3977 KnownMethods[(*M)->getSelector()] = *M;
3978 }
3979 }
3980}
3981
3982void Sema::CodeCompleteObjCMethodDecl(Scope *S,
3983 bool IsInstanceMethod,
3984 TypeTy *ReturnTy,
3985 DeclPtrTy IDecl) {
3986 // Determine the return type of the method we're declaring, if
3987 // provided.
3988 QualType ReturnType = GetTypeFromParser(ReturnTy);
3989
3990 // Determine where we should start searching for methods, and where we
3991 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
3992 bool IsInImplementation = false;
3993 if (Decl *D = IDecl.getAs<Decl>()) {
3994 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
3995 SearchDecl = Impl->getClassInterface();
3996 CurrentDecl = Impl;
3997 IsInImplementation = true;
3998 } else if (ObjCCategoryImplDecl *CatImpl
3999 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4000 SearchDecl = CatImpl->getCategoryDecl();
4001 CurrentDecl = CatImpl;
4002 IsInImplementation = true;
4003 } else {
4004 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4005 CurrentDecl = SearchDecl;
4006 }
4007 }
4008
4009 if (!SearchDecl && S) {
4010 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4011 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4012 CurrentDecl = SearchDecl;
4013 }
4014 }
4015
4016 if (!SearchDecl || !CurrentDecl) {
4017 HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
4018 return;
4019 }
4020
4021 // Find all of the methods that we could declare/implement here.
4022 KnownMethodsMap KnownMethods;
4023 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4024 ReturnType, IsInImplementation, KnownMethods);
4025
4026 // Erase any methods that have already been declared or
4027 // implemented here.
4028 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4029 MEnd = CurrentDecl->meth_end();
4030 M != MEnd; ++M) {
4031 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4032 continue;
4033
4034 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4035 if (Pos != KnownMethods.end())
4036 KnownMethods.erase(Pos);
4037 }
4038
4039 // Add declarations or definitions for each of the known methods.
4040 typedef CodeCompleteConsumer::Result Result;
4041 ResultBuilder Results(*this);
4042 Results.EnterNewScope();
4043 PrintingPolicy Policy(Context.PrintingPolicy);
4044 Policy.AnonymousTagLocations = false;
4045 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4046 MEnd = KnownMethods.end();
4047 M != MEnd; ++M) {
4048 ObjCMethodDecl *Method = M->second;
4049 CodeCompletionString *Pattern = new CodeCompletionString;
4050
4051 // If the result type was not already provided, add it to the
4052 // pattern as (type).
4053 if (ReturnType.isNull()) {
4054 std::string TypeStr;
4055 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4056 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4057 Pattern->AddTextChunk(TypeStr);
4058 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4059 }
4060
4061 Selector Sel = Method->getSelector();
4062
4063 // Add the first part of the selector to the pattern.
4064 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4065
4066 // Add parameters to the pattern.
4067 unsigned I = 0;
4068 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4069 PEnd = Method->param_end();
4070 P != PEnd; (void)++P, ++I) {
4071 // Add the part of the selector name.
4072 if (I == 0)
4073 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4074 else if (I < Sel.getNumArgs()) {
4075 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4076 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4077 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4078 } else
4079 break;
4080
4081 // Add the parameter type.
4082 std::string TypeStr;
4083 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4084 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4085 Pattern->AddTextChunk(TypeStr);
4086 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4087
4088 if (IdentifierInfo *Id = (*P)->getIdentifier())
4089 Pattern->AddTextChunk(Id->getName());
4090 }
4091
4092 if (Method->isVariadic()) {
4093 if (Method->param_size() > 0)
4094 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4095 Pattern->AddTextChunk("...");
4096 }
4097
Douglas Gregord37c59d2010-05-28 00:57:46 +00004098 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00004099 // We will be defining the method here, so add a compound statement.
4100 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4101 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4102 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4103 if (!Method->getResultType()->isVoidType()) {
4104 // If the result type is not void, add a return clause.
4105 Pattern->AddTextChunk("return");
4106 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4107 Pattern->AddPlaceholderChunk("expression");
4108 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4109 } else
4110 Pattern->AddPlaceholderChunk("statements");
4111
4112 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4113 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4114 }
4115
4116 Results.AddResult(Result(Pattern));
4117 }
4118
4119 Results.ExitScope();
4120
4121 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4122}