1 //===---------------- 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"
14 #include "Lookup.h"
15 #include "clang/Sema/CodeCompleteConsumer.h"
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include <list>
25 #include <map>
26 #include <vector>
27 
28 using namespace clang;
29 
30 namespace {
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 
51     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 
105     /// \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.
108     typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
109 
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;
117 
118     /// \brief Whether we should allow declarations as
119     /// nested-name-specifiers that would otherwise be filtered out.
120     bool AllowNestedNameSpecifiers;
121 
122     /// \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 
129     /// \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)
135       : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
136 
137     /// \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 
144     /// \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 
157     /// \brief Specify the preferred type.
158     void setPreferredType(QualType T) {
159       PreferredType = SemaRef.Context.getCanonicalType(T);
160     }
161 
162     /// \brief Specify whether nested-name-specifiers are allowed.
163     void allowNestedNameSpecifiers(bool Allow = true) {
164       AllowNestedNameSpecifiers = Allow;
165     }
166 
167     /// \brief Determine whether the given declaration is at all interesting
168     /// as a code-completion result.
169     ///
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;
175 
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 
185     /// \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).
188     ///
189     /// \param CurContext the result to add (if it is unique).
190     ///
191     /// \param R the context in which this result will be named.
192     void MaybeAddResult(Result R, DeclContext *CurContext = 0);
193 
194     /// \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.
202     ///
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);
207 
208     /// \brief Add a new non-declaration result to this result set.
209     void AddResult(Result R);
210 
211     /// \brief Enter into a new scope.
212     void EnterNewScope();
213 
214     /// \brief Exit from the current scope.
215     void ExitScope();
216 
217     /// \brief Ignore this declaration, if it is seen again.
218     void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
219 
220     /// \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     //@{
226     bool IsOrdinaryName(NamedDecl *ND) const;
227     bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
228     bool IsOrdinaryNonValueName(NamedDecl *ND) const;
229     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;
236     bool IsMember(NamedDecl *ND) const;
237     bool IsObjCIvar(NamedDecl *ND) const;
238     bool IsObjCMessageReceiver(NamedDecl *ND) const;
239     //@}
240   };
241 }
242 
243 class ResultBuilder::ShadowMapEntry::iterator {
244   llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
245   unsigned SingleDeclIndex;
246 
247 public:
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 
295     return *DeclOrIterator.get<const DeclIndexPair*>();
296   }
297 
298   pointer operator->() const {
299     return pointer(**this);
300   }
301 
302   friend bool operator==(const iterator &X, const iterator &Y) {
303     return X.DeclOrIterator.getOpaqueValue()
304                                   == Y.DeclOrIterator.getOpaqueValue() &&
305       X.SingleDeclIndex == Y.SingleDeclIndex;
306   }
307 
308   friend bool operator!=(const iterator &X, const iterator &Y) {
309     return !(X == Y);
310   }
311 };
312 
313 ResultBuilder::ShadowMapEntry::iterator
314 ResultBuilder::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 
324 ResultBuilder::ShadowMapEntry::iterator
325 ResultBuilder::ShadowMapEntry::end() const {
326   if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
327     return iterator();
328 
329   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
330 }
331 
332 /// \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.
345 static NestedNameSpecifier *
346 getRequiredQualification(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   }
373   return Result;
374 }
375 
376 bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
377                                       bool &AsNestedNameSpecifier) const {
378   AsNestedNameSpecifier = false;
379 
380   ND = ND->getUnderlyingDecl();
381   unsigned IDNS = ND->getIdentifierNamespace();
382 
383   // Skip unnamed entities.
384   if (!ND->getDeclName())
385     return false;
386 
387   // Friend declarations and declarations introduced due to friends are never
388   // added as results.
389   if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
390     return false;
391 
392   // Class template (partial) specializations are never added as results.
393   if (isa<ClassTemplateSpecializationDecl>(ND) ||
394       isa<ClassTemplatePartialSpecializationDecl>(ND))
395     return false;
396 
397   // Using declarations themselves are never added as results.
398   if (isa<UsingDecl>(ND))
399     return false;
400 
401   // Some declarations have reserved names that we don't want to ever show.
402   if (const IdentifierInfo *Id = ND->getIdentifier()) {
403     // __va_list_tag is a freak of nature. Find it and skip it.
404     if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
405       return false;
406 
407     // Filter out names reserved for the implementation (C99 7.1.3,
408     // C++ [lib.global.names]). Users don't need to see those.
409     //
410     // FIXME: Add predicate for this.
411     if (Id->getLength() >= 2) {
412       const char *Name = Id->getNameStart();
413       if (Name[0] == '_' &&
414           (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
415         return false;
416     }
417   }
418 
419   // C++ constructors are never found by name lookup.
420   if (isa<CXXConstructorDecl>(ND))
421     return false;
422 
423   // Filter out any unwanted results.
424   if (Filter && !(this->*Filter)(ND)) {
425     // Check whether it is interesting as a nested-name-specifier.
426     if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
427         IsNestedNameSpecifier(ND) &&
428         (Filter != &ResultBuilder::IsMember ||
429          (isa<CXXRecordDecl>(ND) &&
430           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
431       AsNestedNameSpecifier = true;
432       return true;
433     }
434 
435     return false;
436   }
437 
438   if (Filter == &ResultBuilder::IsNestedNameSpecifier)
439     AsNestedNameSpecifier = true;
440 
441   // ... then it must be interesting!
442   return true;
443 }
444 
445 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
446                                       NamedDecl *Hiding) {
447   // In C, there is no way to refer to a hidden name.
448   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
449   // name if we introduce the tag type.
450   if (!SemaRef.getLangOptions().CPlusPlus)
451     return true;
452 
453   DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
454 
455   // There is no way to qualify a name declared in a function or method.
456   if (HiddenCtx->isFunctionOrMethod())
457     return true;
458 
459   if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
460     return true;
461 
462   // We can refer to the result with the appropriate qualification. Do it.
463   R.Hidden = true;
464   R.QualifierIsInformative = false;
465 
466   if (!R.Qualifier)
467     R.Qualifier = getRequiredQualification(SemaRef.Context,
468                                            CurContext,
469                                            R.Declaration->getDeclContext());
470   return false;
471 }
472 
473 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
474   assert(!ShadowMaps.empty() && "Must enter into a results scope");
475 
476   if (R.Kind != Result::RK_Declaration) {
477     // For non-declaration results, just add the result.
478     Results.push_back(R);
479     return;
480   }
481 
482   // Look through using declarations.
483   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
484     MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
485     return;
486   }
487 
488   Decl *CanonDecl = R.Declaration->getCanonicalDecl();
489   unsigned IDNS = CanonDecl->getIdentifierNamespace();
490 
491   bool AsNestedNameSpecifier = false;
492   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
493     return;
494 
495   ShadowMap &SMap = ShadowMaps.back();
496   ShadowMapEntry::iterator I, IEnd;
497   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
498   if (NamePos != SMap.end()) {
499     I = NamePos->second.begin();
500     IEnd = NamePos->second.end();
501   }
502 
503   for (; I != IEnd; ++I) {
504     NamedDecl *ND = I->first;
505     unsigned Index = I->second;
506     if (ND->getCanonicalDecl() == CanonDecl) {
507       // This is a redeclaration. Always pick the newer declaration.
508       Results[Index].Declaration = R.Declaration;
509 
510       // We're done.
511       return;
512     }
513   }
514 
515   // This is a new declaration in this scope. However, check whether this
516   // declaration name is hidden by a similarly-named declaration in an outer
517   // scope.
518   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
519   --SMEnd;
520   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
521     ShadowMapEntry::iterator I, IEnd;
522     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
523     if (NamePos != SM->end()) {
524       I = NamePos->second.begin();
525       IEnd = NamePos->second.end();
526     }
527     for (; I != IEnd; ++I) {
528       // A tag declaration does not hide a non-tag declaration.
529       if (I->first->hasTagIdentifierNamespace() &&
530           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
531                    Decl::IDNS_ObjCProtocol)))
532         continue;
533 
534       // Protocols are in distinct namespaces from everything else.
535       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
536            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
537           I->first->getIdentifierNamespace() != IDNS)
538         continue;
539 
540       // The newly-added result is hidden by an entry in the shadow map.
541       if (CheckHiddenResult(R, CurContext, I->first))
542         return;
543 
544       break;
545     }
546   }
547 
548   // Make sure that any given declaration only shows up in the result set once.
549   if (!AllDeclsFound.insert(CanonDecl))
550     return;
551 
552   // If the filter is for nested-name-specifiers, then this result starts a
553   // nested-name-specifier.
554   if (AsNestedNameSpecifier) {
555     R.StartsNestedNameSpecifier = true;
556     R.Priority = CCP_NestedNameSpecifier;
557   }
558 
559   // If this result is supposed to have an informative qualifier, add one.
560   if (R.QualifierIsInformative && !R.Qualifier &&
561       !R.StartsNestedNameSpecifier) {
562     DeclContext *Ctx = R.Declaration->getDeclContext();
563     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
564       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
565     else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
566       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
567                              SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
568     else
569       R.QualifierIsInformative = false;
570   }
571 
572   // Insert this result into the set of results and into the current shadow
573   // map.
574   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
575   Results.push_back(R);
576 }
577 
578 enum SimplifiedTypeClass {
579   STC_Arithmetic,
580   STC_Array,
581   STC_Block,
582   STC_Function,
583   STC_ObjectiveC,
584   STC_Other,
585   STC_Pointer,
586   STC_Record,
587   STC_Void
588 };
589 
590 /// \brief A simplified classification of types used to determine whether two
591 /// types are "similar enough" when adjusting priorities.
592 static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
593   switch (T->getTypeClass()) {
594   case Type::Builtin:
595     switch (cast<BuiltinType>(T)->getKind()) {
596     case BuiltinType::Void:
597       return STC_Void;
598 
599     case BuiltinType::NullPtr:
600       return STC_Pointer;
601 
602     case BuiltinType::Overload:
603     case BuiltinType::Dependent:
604     case BuiltinType::UndeducedAuto:
605       return STC_Other;
606 
607     case BuiltinType::ObjCId:
608     case BuiltinType::ObjCClass:
609     case BuiltinType::ObjCSel:
610       return STC_ObjectiveC;
611 
612     default:
613       return STC_Arithmetic;
614     }
615     return STC_Other;
616 
617   case Type::Complex:
618     return STC_Arithmetic;
619 
620   case Type::Pointer:
621     return STC_Pointer;
622 
623   case Type::BlockPointer:
624     return STC_Block;
625 
626   case Type::LValueReference:
627   case Type::RValueReference:
628     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
629 
630   case Type::ConstantArray:
631   case Type::IncompleteArray:
632   case Type::VariableArray:
633   case Type::DependentSizedArray:
634     return STC_Array;
635 
636   case Type::DependentSizedExtVector:
637   case Type::Vector:
638   case Type::ExtVector:
639     return STC_Arithmetic;
640 
641   case Type::FunctionProto:
642   case Type::FunctionNoProto:
643     return STC_Function;
644 
645   case Type::Record:
646     return STC_Record;
647 
648   case Type::Enum:
649     return STC_Arithmetic;
650 
651   case Type::ObjCObject:
652   case Type::ObjCInterface:
653   case Type::ObjCObjectPointer:
654     return STC_ObjectiveC;
655 
656   default:
657     return STC_Other;
658   }
659 }
660 
661 /// \brief Get the type that a given expression will have if this declaration
662 /// is used as an expression in its "typical" code-completion form.
663 static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
664   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
665 
666   if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
667     return C.getTypeDeclType(Type);
668   if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
669     return C.getObjCInterfaceType(Iface);
670 
671   QualType T;
672   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
673     T = Function->getResultType();
674   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
675     T = Method->getResultType();
676   else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
677     T = FunTmpl->getTemplatedDecl()->getResultType();
678   else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
679     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
680   else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
681     T = Property->getType();
682   else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
683     T = Value->getType();
684   else
685     return QualType();
686 
687   return T.getNonReferenceType();
688 }
689 
690 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
691                               NamedDecl *Hiding, bool InBaseClass = false) {
692   if (R.Kind != Result::RK_Declaration) {
693     // For non-declaration results, just add the result.
694     Results.push_back(R);
695     return;
696   }
697 
698   // Look through using declarations.
699   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
700     AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
701     return;
702   }
703 
704   bool AsNestedNameSpecifier = false;
705   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
706     return;
707 
708   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
709     return;
710 
711   // Make sure that any given declaration only shows up in the result set once.
712   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
713     return;
714 
715   // If the filter is for nested-name-specifiers, then this result starts a
716   // nested-name-specifier.
717   if (AsNestedNameSpecifier) {
718     R.StartsNestedNameSpecifier = true;
719     R.Priority = CCP_NestedNameSpecifier;
720   }
721   else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
722            isa<CXXRecordDecl>(R.Declaration->getDeclContext()
723                                                   ->getLookupContext()))
724     R.QualifierIsInformative = true;
725 
726   // If this result is supposed to have an informative qualifier, add one.
727   if (R.QualifierIsInformative && !R.Qualifier &&
728       !R.StartsNestedNameSpecifier) {
729     DeclContext *Ctx = R.Declaration->getDeclContext();
730     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
731       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
732     else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
733       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
734                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
735     else
736       R.QualifierIsInformative = false;
737   }
738 
739   // Adjust the priority if this result comes from a base class.
740   if (InBaseClass)
741     R.Priority += CCD_InBaseClass;
742 
743   if (!PreferredType.isNull()) {
744     if (ValueDecl *Value = dyn_cast<ValueDecl>(R.Declaration)) {
745       CanQualType T = SemaRef.Context.getCanonicalType(
746                                      getDeclUsageType(SemaRef.Context, Value));
747       // Check for exactly-matching types (modulo qualifiers).
748       if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, T))
749         R.Priority /= CCF_ExactTypeMatch;
750       // Check for nearly-matching types, based on classification of each.
751       else if ((getSimplifiedTypeClass(PreferredType)
752                                                 == getSimplifiedTypeClass(T)) &&
753                !(PreferredType->isEnumeralType() && T->isEnumeralType()))
754         R.Priority /= CCF_SimilarTypeMatch;
755     }
756   }
757 
758   // Insert this result into the set of results.
759   Results.push_back(R);
760 }
761 
762 void ResultBuilder::AddResult(Result R) {
763   assert(R.Kind != Result::RK_Declaration &&
764           "Declaration results need more context");
765   Results.push_back(R);
766 }
767 
768 /// \brief Enter into a new scope.
769 void ResultBuilder::EnterNewScope() {
770   ShadowMaps.push_back(ShadowMap());
771 }
772 
773 /// \brief Exit from the current scope.
774 void ResultBuilder::ExitScope() {
775   for (ShadowMap::iterator E = ShadowMaps.back().begin(),
776                         EEnd = ShadowMaps.back().end();
777        E != EEnd;
778        ++E)
779     E->second.Destroy();
780 
781   ShadowMaps.pop_back();
782 }
783 
784 /// \brief Determines whether this given declaration will be found by
785 /// ordinary name lookup.
786 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
787   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
788 
789   unsigned IDNS = Decl::IDNS_Ordinary;
790   if (SemaRef.getLangOptions().CPlusPlus)
791     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
792   else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
793     return true;
794 
795   return ND->getIdentifierNamespace() & IDNS;
796 }
797 
798 /// \brief Determines whether this given declaration will be found by
799 /// ordinary name lookup but is not a type name.
800 bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
801   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
802   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
803     return false;
804 
805   unsigned IDNS = Decl::IDNS_Ordinary;
806   if (SemaRef.getLangOptions().CPlusPlus)
807     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
808   else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
809     return true;
810 
811   return ND->getIdentifierNamespace() & IDNS;
812 }
813 
814 /// \brief Determines whether this given declaration will be found by
815 /// ordinary name lookup.
816 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
817   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
818 
819   unsigned IDNS = Decl::IDNS_Ordinary;
820   if (SemaRef.getLangOptions().CPlusPlus)
821     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
822 
823   return (ND->getIdentifierNamespace() & IDNS) &&
824     !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
825     !isa<ObjCPropertyDecl>(ND);
826 }
827 
828 /// \brief Determines whether the given declaration is suitable as the
829 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
830 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
831   // Allow us to find class templates, too.
832   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
833     ND = ClassTemplate->getTemplatedDecl();
834 
835   return SemaRef.isAcceptableNestedNameSpecifier(ND);
836 }
837 
838 /// \brief Determines whether the given declaration is an enumeration.
839 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
840   return isa<EnumDecl>(ND);
841 }
842 
843 /// \brief Determines whether the given declaration is a class or struct.
844 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
845   // Allow us to find class templates, too.
846   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
847     ND = ClassTemplate->getTemplatedDecl();
848 
849   if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
850     return RD->getTagKind() == TTK_Class ||
851     RD->getTagKind() == TTK_Struct;
852 
853   return false;
854 }
855 
856 /// \brief Determines whether the given declaration is a union.
857 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
858   // Allow us to find class templates, too.
859   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
860     ND = ClassTemplate->getTemplatedDecl();
861 
862   if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
863     return RD->getTagKind() == TTK_Union;
864 
865   return false;
866 }
867 
868 /// \brief Determines whether the given declaration is a namespace.
869 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
870   return isa<NamespaceDecl>(ND);
871 }
872 
873 /// \brief Determines whether the given declaration is a namespace or
874 /// namespace alias.
875 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
876   return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
877 }
878 
879 /// \brief Determines whether the given declaration is a type.
880 bool ResultBuilder::IsType(NamedDecl *ND) const {
881   return isa<TypeDecl>(ND);
882 }
883 
884 /// \brief Determines which members of a class should be visible via
885 /// "." or "->".  Only value declarations, nested name specifiers, and
886 /// using declarations thereof should show up.
887 bool ResultBuilder::IsMember(NamedDecl *ND) const {
888   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
889     ND = Using->getTargetDecl();
890 
891   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
892     isa<ObjCPropertyDecl>(ND);
893 }
894 
895 static bool isObjCReceiverType(ASTContext &C, QualType T) {
896   T = C.getCanonicalType(T);
897   switch (T->getTypeClass()) {
898   case Type::ObjCObject:
899   case Type::ObjCInterface:
900   case Type::ObjCObjectPointer:
901     return true;
902 
903   case Type::Builtin:
904     switch (cast<BuiltinType>(T)->getKind()) {
905     case BuiltinType::ObjCId:
906     case BuiltinType::ObjCClass:
907     case BuiltinType::ObjCSel:
908       return true;
909 
910     default:
911       break;
912     }
913     return false;
914 
915   default:
916     break;
917   }
918 
919   if (!C.getLangOptions().CPlusPlus)
920     return false;
921 
922   // FIXME: We could perform more analysis here to determine whether a
923   // particular class type has any conversions to Objective-C types. For now,
924   // just accept all class types.
925   return T->isDependentType() || T->isRecordType();
926 }
927 
928 bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
929   QualType T = getDeclUsageType(SemaRef.Context, ND);
930   if (T.isNull())
931     return false;
932 
933   T = SemaRef.Context.getBaseElementType(T);
934   return isObjCReceiverType(SemaRef.Context, T);
935 }
936 
937 
938 /// \rief Determines whether the given declaration is an Objective-C
939 /// instance variable.
940 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
941   return isa<ObjCIvarDecl>(ND);
942 }
943 
944 namespace {
945   /// \brief Visible declaration consumer that adds a code-completion result
946   /// for each visible declaration.
947   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
948     ResultBuilder &Results;
949     DeclContext *CurContext;
950 
951   public:
952     CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
953       : Results(Results), CurContext(CurContext) { }
954 
955     virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
956       Results.AddResult(ND, CurContext, Hiding, InBaseClass);
957     }
958   };
959 }
960 
961 /// \brief Add type specifiers for the current language as keyword results.
962 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
963                                     ResultBuilder &Results) {
964   typedef CodeCompleteConsumer::Result Result;
965   Results.AddResult(Result("short", CCP_Type));
966   Results.AddResult(Result("long", CCP_Type));
967   Results.AddResult(Result("signed", CCP_Type));
968   Results.AddResult(Result("unsigned", CCP_Type));
969   Results.AddResult(Result("void", CCP_Type));
970   Results.AddResult(Result("char", CCP_Type));
971   Results.AddResult(Result("int", CCP_Type));
972   Results.AddResult(Result("float", CCP_Type));
973   Results.AddResult(Result("double", CCP_Type));
974   Results.AddResult(Result("enum", CCP_Type));
975   Results.AddResult(Result("struct", CCP_Type));
976   Results.AddResult(Result("union", CCP_Type));
977   Results.AddResult(Result("const", CCP_Type));
978   Results.AddResult(Result("volatile", CCP_Type));
979 
980   if (LangOpts.C99) {
981     // C99-specific
982     Results.AddResult(Result("_Complex", CCP_Type));
983     Results.AddResult(Result("_Imaginary", CCP_Type));
984     Results.AddResult(Result("_Bool", CCP_Type));
985     Results.AddResult(Result("restrict", CCP_Type));
986   }
987 
988   if (LangOpts.CPlusPlus) {
989     // C++-specific
990     Results.AddResult(Result("bool", CCP_Type));
991     Results.AddResult(Result("class", CCP_Type));
992     Results.AddResult(Result("wchar_t", CCP_Type));
993 
994     // typename qualified-id
995     CodeCompletionString *Pattern = new CodeCompletionString;
996     Pattern->AddTypedTextChunk("typename");
997     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
998     Pattern->AddPlaceholderChunk("qualifier");
999     Pattern->AddTextChunk("::");
1000     Pattern->AddPlaceholderChunk("name");
1001     Results.AddResult(Result(Pattern));
1002 
1003     if (LangOpts.CPlusPlus0x) {
1004       Results.AddResult(Result("auto", CCP_Type));
1005       Results.AddResult(Result("char16_t", CCP_Type));
1006       Results.AddResult(Result("char32_t", CCP_Type));
1007 
1008       CodeCompletionString *Pattern = new CodeCompletionString;
1009       Pattern->AddTypedTextChunk("decltype");
1010       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1011       Pattern->AddPlaceholderChunk("expression");
1012       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1013       Results.AddResult(Result(Pattern));
1014     }
1015   }
1016 
1017   // GNU extensions
1018   if (LangOpts.GNUMode) {
1019     // FIXME: Enable when we actually support decimal floating point.
1020     //    Results.AddResult(Result("_Decimal32"));
1021     //    Results.AddResult(Result("_Decimal64"));
1022     //    Results.AddResult(Result("_Decimal128"));
1023 
1024     CodeCompletionString *Pattern = new CodeCompletionString;
1025     Pattern->AddTypedTextChunk("typeof");
1026     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1027     Pattern->AddPlaceholderChunk("expression");
1028     Results.AddResult(Result(Pattern));
1029 
1030     Pattern = new CodeCompletionString;
1031     Pattern->AddTypedTextChunk("typeof");
1032     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1033     Pattern->AddPlaceholderChunk("type");
1034     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1035     Results.AddResult(Result(Pattern));
1036   }
1037 }
1038 
1039 static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
1040                                  const LangOptions &LangOpts,
1041                                  ResultBuilder &Results) {
1042   typedef CodeCompleteConsumer::Result Result;
1043   // Note: we don't suggest either "auto" or "register", because both
1044   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1045   // in C++0x as a type specifier.
1046   Results.AddResult(Result("extern"));
1047   Results.AddResult(Result("static"));
1048 }
1049 
1050 static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
1051                                   const LangOptions &LangOpts,
1052                                   ResultBuilder &Results) {
1053   typedef CodeCompleteConsumer::Result Result;
1054   switch (CCC) {
1055   case Action::CCC_Class:
1056   case Action::CCC_MemberTemplate:
1057     if (LangOpts.CPlusPlus) {
1058       Results.AddResult(Result("explicit"));
1059       Results.AddResult(Result("friend"));
1060       Results.AddResult(Result("mutable"));
1061       Results.AddResult(Result("virtual"));
1062     }
1063     // Fall through
1064 
1065   case Action::CCC_ObjCInterface:
1066   case Action::CCC_ObjCImplementation:
1067   case Action::CCC_Namespace:
1068   case Action::CCC_Template:
1069     if (LangOpts.CPlusPlus || LangOpts.C99)
1070       Results.AddResult(Result("inline"));
1071     break;
1072 
1073   case Action::CCC_ObjCInstanceVariableList:
1074   case Action::CCC_Expression:
1075   case Action::CCC_Statement:
1076   case Action::CCC_ForInit:
1077   case Action::CCC_Condition:
1078   case Action::CCC_RecoveryInFunction:
1079     break;
1080   }
1081 }
1082 
1083 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1084 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1085 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1086                                      ResultBuilder &Results,
1087                                      bool NeedAt);
1088 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1089                                          ResultBuilder &Results,
1090                                          bool NeedAt);
1091 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1092                                     ResultBuilder &Results,
1093                                     bool NeedAt);
1094 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1095 
1096 static void AddTypedefResult(ResultBuilder &Results) {
1097   CodeCompletionString *Pattern = new CodeCompletionString;
1098   Pattern->AddTypedTextChunk("typedef");
1099   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1100   Pattern->AddPlaceholderChunk("type");
1101   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1102   Pattern->AddPlaceholderChunk("name");
1103   Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1104 }
1105 
1106 static bool WantTypesInContext(Action::CodeCompletionContext CCC,
1107                                const LangOptions &LangOpts) {
1108   if (LangOpts.CPlusPlus)
1109     return true;
1110 
1111   switch (CCC) {
1112   case Action::CCC_Namespace:
1113   case Action::CCC_Class:
1114   case Action::CCC_ObjCInstanceVariableList:
1115   case Action::CCC_Template:
1116   case Action::CCC_MemberTemplate:
1117   case Action::CCC_Statement:
1118   case Action::CCC_RecoveryInFunction:
1119     return true;
1120 
1121   case Action::CCC_ObjCInterface:
1122   case Action::CCC_ObjCImplementation:
1123   case Action::CCC_Expression:
1124   case Action::CCC_Condition:
1125     return false;
1126 
1127   case Action::CCC_ForInit:
1128     return LangOpts.ObjC1 || LangOpts.C99;
1129   }
1130 
1131   return false;
1132 }
1133 
1134 /// \brief Add language constructs that show up for "ordinary" names.
1135 static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
1136                                    Scope *S,
1137                                    Sema &SemaRef,
1138                                    ResultBuilder &Results) {
1139   typedef CodeCompleteConsumer::Result Result;
1140   switch (CCC) {
1141   case Action::CCC_Namespace:
1142     if (SemaRef.getLangOptions().CPlusPlus) {
1143       CodeCompletionString *Pattern = 0;
1144 
1145       if (Results.includeCodePatterns()) {
1146         // namespace <identifier> { declarations }
1147         CodeCompletionString *Pattern = new CodeCompletionString;
1148         Pattern->AddTypedTextChunk("namespace");
1149         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1150         Pattern->AddPlaceholderChunk("identifier");
1151         Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1152         Pattern->AddPlaceholderChunk("declarations");
1153         Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1154         Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1155         Results.AddResult(Result(Pattern));
1156       }
1157 
1158       // namespace identifier = identifier ;
1159       Pattern = new CodeCompletionString;
1160       Pattern->AddTypedTextChunk("namespace");
1161       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1162       Pattern->AddPlaceholderChunk("name");
1163       Pattern->AddChunk(CodeCompletionString::CK_Equal);
1164       Pattern->AddPlaceholderChunk("namespace");
1165       Results.AddResult(Result(Pattern));
1166 
1167       // Using directives
1168       Pattern = new CodeCompletionString;
1169       Pattern->AddTypedTextChunk("using");
1170       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1171       Pattern->AddTextChunk("namespace");
1172       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1173       Pattern->AddPlaceholderChunk("identifier");
1174       Results.AddResult(Result(Pattern));
1175 
1176       // asm(string-literal)
1177       Pattern = new CodeCompletionString;
1178       Pattern->AddTypedTextChunk("asm");
1179       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1180       Pattern->AddPlaceholderChunk("string-literal");
1181       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1182       Results.AddResult(Result(Pattern));
1183 
1184       if (Results.includeCodePatterns()) {
1185         // Explicit template instantiation
1186         Pattern = new CodeCompletionString;
1187         Pattern->AddTypedTextChunk("template");
1188         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1189         Pattern->AddPlaceholderChunk("declaration");
1190         Results.AddResult(Result(Pattern));
1191       }
1192     }
1193 
1194     if (SemaRef.getLangOptions().ObjC1)
1195       AddObjCTopLevelResults(Results, true);
1196 
1197     AddTypedefResult(Results);
1198     // Fall through
1199 
1200   case Action::CCC_Class:
1201     if (SemaRef.getLangOptions().CPlusPlus) {
1202       // Using declaration
1203       CodeCompletionString *Pattern = new CodeCompletionString;
1204       Pattern->AddTypedTextChunk("using");
1205       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1206       Pattern->AddPlaceholderChunk("qualifier");
1207       Pattern->AddTextChunk("::");
1208       Pattern->AddPlaceholderChunk("name");
1209       Results.AddResult(Result(Pattern));
1210 
1211       // using typename qualifier::name (only in a dependent context)
1212       if (SemaRef.CurContext->isDependentContext()) {
1213         Pattern = new CodeCompletionString;
1214         Pattern->AddTypedTextChunk("using");
1215         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1216         Pattern->AddTextChunk("typename");
1217         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1218         Pattern->AddPlaceholderChunk("qualifier");
1219         Pattern->AddTextChunk("::");
1220         Pattern->AddPlaceholderChunk("name");
1221         Results.AddResult(Result(Pattern));
1222       }
1223 
1224       if (CCC == Action::CCC_Class) {
1225         AddTypedefResult(Results);
1226 
1227         // public:
1228         Pattern = new CodeCompletionString;
1229         Pattern->AddTypedTextChunk("public");
1230         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1231         Results.AddResult(Result(Pattern));
1232 
1233         // protected:
1234         Pattern = new CodeCompletionString;
1235         Pattern->AddTypedTextChunk("protected");
1236         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1237         Results.AddResult(Result(Pattern));
1238 
1239         // private:
1240         Pattern = new CodeCompletionString;
1241         Pattern->AddTypedTextChunk("private");
1242         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1243         Results.AddResult(Result(Pattern));
1244       }
1245     }
1246     // Fall through
1247 
1248   case Action::CCC_Template:
1249   case Action::CCC_MemberTemplate:
1250     if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1251       // template < parameters >
1252       CodeCompletionString *Pattern = new CodeCompletionString;
1253       Pattern->AddTypedTextChunk("template");
1254       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1255       Pattern->AddPlaceholderChunk("parameters");
1256       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1257       Results.AddResult(Result(Pattern));
1258     }
1259 
1260     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1261     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1262     break;
1263 
1264   case Action::CCC_ObjCInterface:
1265     AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1266     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1267     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1268     break;
1269 
1270   case Action::CCC_ObjCImplementation:
1271     AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1272     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1273     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1274     break;
1275 
1276   case Action::CCC_ObjCInstanceVariableList:
1277     AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
1278     break;
1279 
1280   case Action::CCC_RecoveryInFunction:
1281   case Action::CCC_Statement: {
1282     AddTypedefResult(Results);
1283 
1284     CodeCompletionString *Pattern = 0;
1285     if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1286       Pattern = new CodeCompletionString;
1287       Pattern->AddTypedTextChunk("try");
1288       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1289       Pattern->AddPlaceholderChunk("statements");
1290       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1291       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1292       Pattern->AddTextChunk("catch");
1293       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1294       Pattern->AddPlaceholderChunk("declaration");
1295       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1296       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1297       Pattern->AddPlaceholderChunk("statements");
1298       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1299       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1300       Results.AddResult(Result(Pattern));
1301     }
1302     if (SemaRef.getLangOptions().ObjC1)
1303       AddObjCStatementResults(Results, true);
1304 
1305     if (Results.includeCodePatterns()) {
1306       // if (condition) { statements }
1307       Pattern = new CodeCompletionString;
1308       Pattern->AddTypedTextChunk("if");
1309       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1310       if (SemaRef.getLangOptions().CPlusPlus)
1311         Pattern->AddPlaceholderChunk("condition");
1312       else
1313         Pattern->AddPlaceholderChunk("expression");
1314       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1315       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1316       Pattern->AddPlaceholderChunk("statements");
1317       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1318       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1319       Results.AddResult(Result(Pattern));
1320 
1321       // switch (condition) { }
1322       Pattern = new CodeCompletionString;
1323       Pattern->AddTypedTextChunk("switch");
1324       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1325       if (SemaRef.getLangOptions().CPlusPlus)
1326         Pattern->AddPlaceholderChunk("condition");
1327       else
1328         Pattern->AddPlaceholderChunk("expression");
1329       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1330       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1331       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1332       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1333       Results.AddResult(Result(Pattern));
1334     }
1335 
1336     // Switch-specific statements.
1337     if (!SemaRef.getSwitchStack().empty()) {
1338       // case expression:
1339       Pattern = new CodeCompletionString;
1340       Pattern->AddTypedTextChunk("case");
1341       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1342       Pattern->AddPlaceholderChunk("expression");
1343       Pattern->AddChunk(CodeCompletionString::CK_Colon);
1344       Results.AddResult(Result(Pattern));
1345 
1346       // default:
1347       Pattern = new CodeCompletionString;
1348       Pattern->AddTypedTextChunk("default");
1349       Pattern->AddChunk(CodeCompletionString::CK_Colon);
1350       Results.AddResult(Result(Pattern));
1351     }
1352 
1353     if (Results.includeCodePatterns()) {
1354       /// while (condition) { statements }
1355       Pattern = new CodeCompletionString;
1356       Pattern->AddTypedTextChunk("while");
1357       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1358       if (SemaRef.getLangOptions().CPlusPlus)
1359         Pattern->AddPlaceholderChunk("condition");
1360       else
1361         Pattern->AddPlaceholderChunk("expression");
1362       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1363       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1364       Pattern->AddPlaceholderChunk("statements");
1365       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1366       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1367       Results.AddResult(Result(Pattern));
1368 
1369       // do { statements } while ( expression );
1370       Pattern = new CodeCompletionString;
1371       Pattern->AddTypedTextChunk("do");
1372       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1373       Pattern->AddPlaceholderChunk("statements");
1374       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1375       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1376       Pattern->AddTextChunk("while");
1377       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1378       Pattern->AddPlaceholderChunk("expression");
1379       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1380       Results.AddResult(Result(Pattern));
1381 
1382       // for ( for-init-statement ; condition ; expression ) { statements }
1383       Pattern = new CodeCompletionString;
1384       Pattern->AddTypedTextChunk("for");
1385       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1386       if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1387         Pattern->AddPlaceholderChunk("init-statement");
1388       else
1389         Pattern->AddPlaceholderChunk("init-expression");
1390       Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1391       Pattern->AddPlaceholderChunk("condition");
1392       Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1393       Pattern->AddPlaceholderChunk("inc-expression");
1394       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1395       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1396       Pattern->AddPlaceholderChunk("statements");
1397       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1398       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1399       Results.AddResult(Result(Pattern));
1400     }
1401 
1402     if (S->getContinueParent()) {
1403       // continue ;
1404       Pattern = new CodeCompletionString;
1405       Pattern->AddTypedTextChunk("continue");
1406       Results.AddResult(Result(Pattern));
1407     }
1408 
1409     if (S->getBreakParent()) {
1410       // break ;
1411       Pattern = new CodeCompletionString;
1412       Pattern->AddTypedTextChunk("break");
1413       Results.AddResult(Result(Pattern));
1414     }
1415 
1416     // "return expression ;" or "return ;", depending on whether we
1417     // know the function is void or not.
1418     bool isVoid = false;
1419     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1420       isVoid = Function->getResultType()->isVoidType();
1421     else if (ObjCMethodDecl *Method
1422                                  = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1423       isVoid = Method->getResultType()->isVoidType();
1424     else if (SemaRef.getCurBlock() &&
1425              !SemaRef.getCurBlock()->ReturnType.isNull())
1426       isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1427     Pattern = new CodeCompletionString;
1428     Pattern->AddTypedTextChunk("return");
1429     if (!isVoid) {
1430       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1431       Pattern->AddPlaceholderChunk("expression");
1432     }
1433     Results.AddResult(Result(Pattern));
1434 
1435     // goto identifier ;
1436     Pattern = new CodeCompletionString;
1437     Pattern->AddTypedTextChunk("goto");
1438     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1439     Pattern->AddPlaceholderChunk("label");
1440     Results.AddResult(Result(Pattern));
1441 
1442     // Using directives
1443     Pattern = new CodeCompletionString;
1444     Pattern->AddTypedTextChunk("using");
1445     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1446     Pattern->AddTextChunk("namespace");
1447     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1448     Pattern->AddPlaceholderChunk("identifier");
1449     Results.AddResult(Result(Pattern));
1450   }
1451 
1452   // Fall through (for statement expressions).
1453   case Action::CCC_ForInit:
1454   case Action::CCC_Condition:
1455     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1456     // Fall through: conditions and statements can have expressions.
1457 
1458   case Action::CCC_Expression: {
1459     CodeCompletionString *Pattern = 0;
1460     if (SemaRef.getLangOptions().CPlusPlus) {
1461       // 'this', if we're in a non-static member function.
1462       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1463         if (!Method->isStatic())
1464           Results.AddResult(Result("this"));
1465 
1466       // true, false
1467       Results.AddResult(Result("true"));
1468       Results.AddResult(Result("false"));
1469 
1470       // dynamic_cast < type-id > ( expression )
1471       Pattern = new CodeCompletionString;
1472       Pattern->AddTypedTextChunk("dynamic_cast");
1473       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1474       Pattern->AddPlaceholderChunk("type");
1475       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1476       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1477       Pattern->AddPlaceholderChunk("expression");
1478       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1479       Results.AddResult(Result(Pattern));
1480 
1481       // static_cast < type-id > ( expression )
1482       Pattern = new CodeCompletionString;
1483       Pattern->AddTypedTextChunk("static_cast");
1484       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1485       Pattern->AddPlaceholderChunk("type");
1486       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1487       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1488       Pattern->AddPlaceholderChunk("expression");
1489       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1490       Results.AddResult(Result(Pattern));
1491 
1492       // reinterpret_cast < type-id > ( expression )
1493       Pattern = new CodeCompletionString;
1494       Pattern->AddTypedTextChunk("reinterpret_cast");
1495       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1496       Pattern->AddPlaceholderChunk("type");
1497       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1498       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1499       Pattern->AddPlaceholderChunk("expression");
1500       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1501       Results.AddResult(Result(Pattern));
1502 
1503       // const_cast < type-id > ( expression )
1504       Pattern = new CodeCompletionString;
1505       Pattern->AddTypedTextChunk("const_cast");
1506       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1507       Pattern->AddPlaceholderChunk("type");
1508       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1509       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1510       Pattern->AddPlaceholderChunk("expression");
1511       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1512       Results.AddResult(Result(Pattern));
1513 
1514       // typeid ( expression-or-type )
1515       Pattern = new CodeCompletionString;
1516       Pattern->AddTypedTextChunk("typeid");
1517       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1518       Pattern->AddPlaceholderChunk("expression-or-type");
1519       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1520       Results.AddResult(Result(Pattern));
1521 
1522       // new T ( ... )
1523       Pattern = new CodeCompletionString;
1524       Pattern->AddTypedTextChunk("new");
1525       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1526       Pattern->AddPlaceholderChunk("type");
1527       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1528       Pattern->AddPlaceholderChunk("expressions");
1529       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1530       Results.AddResult(Result(Pattern));
1531 
1532       // new T [ ] ( ... )
1533       Pattern = new CodeCompletionString;
1534       Pattern->AddTypedTextChunk("new");
1535       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1536       Pattern->AddPlaceholderChunk("type");
1537       Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1538       Pattern->AddPlaceholderChunk("size");
1539       Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1540       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1541       Pattern->AddPlaceholderChunk("expressions");
1542       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1543       Results.AddResult(Result(Pattern));
1544 
1545       // delete expression
1546       Pattern = new CodeCompletionString;
1547       Pattern->AddTypedTextChunk("delete");
1548       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1549       Pattern->AddPlaceholderChunk("expression");
1550       Results.AddResult(Result(Pattern));
1551 
1552       // delete [] expression
1553       Pattern = new CodeCompletionString;
1554       Pattern->AddTypedTextChunk("delete");
1555       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1556       Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1557       Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1558       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1559       Pattern->AddPlaceholderChunk("expression");
1560       Results.AddResult(Result(Pattern));
1561 
1562       // throw expression
1563       Pattern = new CodeCompletionString;
1564       Pattern->AddTypedTextChunk("throw");
1565       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566       Pattern->AddPlaceholderChunk("expression");
1567       Results.AddResult(Result(Pattern));
1568 
1569       // FIXME: Rethrow?
1570     }
1571 
1572     if (SemaRef.getLangOptions().ObjC1) {
1573       // Add "super", if we're in an Objective-C class with a superclass.
1574       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1575         // The interface can be NULL.
1576         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1577           if (ID->getSuperClass())
1578             Results.AddResult(Result("super"));
1579       }
1580 
1581       AddObjCExpressionResults(Results, true);
1582     }
1583 
1584     // sizeof expression
1585     Pattern = new CodeCompletionString;
1586     Pattern->AddTypedTextChunk("sizeof");
1587     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1588     Pattern->AddPlaceholderChunk("expression-or-type");
1589     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1590     Results.AddResult(Result(Pattern));
1591     break;
1592   }
1593   }
1594 
1595   if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1596     AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
1597 
1598   if (SemaRef.getLangOptions().CPlusPlus)
1599     Results.AddResult(Result("operator"));
1600 }
1601 
1602 /// \brief If the given declaration has an associated type, add it as a result
1603 /// type chunk.
1604 static void AddResultTypeChunk(ASTContext &Context,
1605                                NamedDecl *ND,
1606                                CodeCompletionString *Result) {
1607   if (!ND)
1608     return;
1609 
1610   // Determine the type of the declaration (if it has a type).
1611   QualType T;
1612   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1613     T = Function->getResultType();
1614   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1615     T = Method->getResultType();
1616   else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1617     T = FunTmpl->getTemplatedDecl()->getResultType();
1618   else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1619     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1620   else if (isa<UnresolvedUsingValueDecl>(ND)) {
1621     /* Do nothing: ignore unresolved using declarations*/
1622   } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1623     T = Value->getType();
1624   else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1625     T = Property->getType();
1626 
1627   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1628     return;
1629 
1630   PrintingPolicy Policy(Context.PrintingPolicy);
1631   Policy.AnonymousTagLocations = false;
1632 
1633   std::string TypeStr;
1634   T.getAsStringInternal(TypeStr, Policy);
1635   Result->AddResultTypeChunk(TypeStr);
1636 }
1637 
1638 /// \brief Add function parameter chunks to the given code completion string.
1639 static void AddFunctionParameterChunks(ASTContext &Context,
1640                                        FunctionDecl *Function,
1641                                        CodeCompletionString *Result) {
1642   typedef CodeCompletionString::Chunk Chunk;
1643 
1644   CodeCompletionString *CCStr = Result;
1645 
1646   for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1647     ParmVarDecl *Param = Function->getParamDecl(P);
1648 
1649     if (Param->hasDefaultArg()) {
1650       // When we see an optional default argument, put that argument and
1651       // the remaining default arguments into a new, optional string.
1652       CodeCompletionString *Opt = new CodeCompletionString;
1653       CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1654       CCStr = Opt;
1655     }
1656 
1657     if (P != 0)
1658       CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1659 
1660     // Format the placeholder string.
1661     std::string PlaceholderStr;
1662     if (Param->getIdentifier())
1663       PlaceholderStr = Param->getIdentifier()->getName();
1664 
1665     Param->getType().getAsStringInternal(PlaceholderStr,
1666                                          Context.PrintingPolicy);
1667 
1668     // Add the placeholder string.
1669     CCStr->AddPlaceholderChunk(PlaceholderStr);
1670   }
1671 
1672   if (const FunctionProtoType *Proto
1673         = Function->getType()->getAs<FunctionProtoType>())
1674     if (Proto->isVariadic())
1675       CCStr->AddPlaceholderChunk(", ...");
1676 }
1677 
1678 /// \brief Add template parameter chunks to the given code completion string.
1679 static void AddTemplateParameterChunks(ASTContext &Context,
1680                                        TemplateDecl *Template,
1681                                        CodeCompletionString *Result,
1682                                        unsigned MaxParameters = 0) {
1683   typedef CodeCompletionString::Chunk Chunk;
1684 
1685   CodeCompletionString *CCStr = Result;
1686   bool FirstParameter = true;
1687 
1688   TemplateParameterList *Params = Template->getTemplateParameters();
1689   TemplateParameterList::iterator PEnd = Params->end();
1690   if (MaxParameters)
1691     PEnd = Params->begin() + MaxParameters;
1692   for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1693     bool HasDefaultArg = false;
1694     std::string PlaceholderStr;
1695     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1696       if (TTP->wasDeclaredWithTypename())
1697         PlaceholderStr = "typename";
1698       else
1699         PlaceholderStr = "class";
1700 
1701       if (TTP->getIdentifier()) {
1702         PlaceholderStr += ' ';
1703         PlaceholderStr += TTP->getIdentifier()->getName();
1704       }
1705 
1706       HasDefaultArg = TTP->hasDefaultArgument();
1707     } else if (NonTypeTemplateParmDecl *NTTP
1708                = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1709       if (NTTP->getIdentifier())
1710         PlaceholderStr = NTTP->getIdentifier()->getName();
1711       NTTP->getType().getAsStringInternal(PlaceholderStr,
1712                                           Context.PrintingPolicy);
1713       HasDefaultArg = NTTP->hasDefaultArgument();
1714     } else {
1715       assert(isa<TemplateTemplateParmDecl>(*P));
1716       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1717 
1718       // Since putting the template argument list into the placeholder would
1719       // be very, very long, we just use an abbreviation.
1720       PlaceholderStr = "template<...> class";
1721       if (TTP->getIdentifier()) {
1722         PlaceholderStr += ' ';
1723         PlaceholderStr += TTP->getIdentifier()->getName();
1724       }
1725 
1726       HasDefaultArg = TTP->hasDefaultArgument();
1727     }
1728 
1729     if (HasDefaultArg) {
1730       // When we see an optional default argument, put that argument and
1731       // the remaining default arguments into a new, optional string.
1732       CodeCompletionString *Opt = new CodeCompletionString;
1733       CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1734       CCStr = Opt;
1735     }
1736 
1737     if (FirstParameter)
1738       FirstParameter = false;
1739     else
1740       CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1741 
1742     // Add the placeholder string.
1743     CCStr->AddPlaceholderChunk(PlaceholderStr);
1744   }
1745 }
1746 
1747 /// \brief Add a qualifier to the given code-completion string, if the
1748 /// provided nested-name-specifier is non-NULL.
1749 static void
1750 AddQualifierToCompletionString(CodeCompletionString *Result,
1751                                NestedNameSpecifier *Qualifier,
1752                                bool QualifierIsInformative,
1753                                ASTContext &Context) {
1754   if (!Qualifier)
1755     return;
1756 
1757   std::string PrintedNNS;
1758   {
1759     llvm::raw_string_ostream OS(PrintedNNS);
1760     Qualifier->print(OS, Context.PrintingPolicy);
1761   }
1762   if (QualifierIsInformative)
1763     Result->AddInformativeChunk(PrintedNNS);
1764   else
1765     Result->AddTextChunk(PrintedNNS);
1766 }
1767 
1768 static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1769                                                    FunctionDecl *Function) {
1770   const FunctionProtoType *Proto
1771     = Function->getType()->getAs<FunctionProtoType>();
1772   if (!Proto || !Proto->getTypeQuals())
1773     return;
1774 
1775   std::string QualsStr;
1776   if (Proto->getTypeQuals() & Qualifiers::Const)
1777     QualsStr += " const";
1778   if (Proto->getTypeQuals() & Qualifiers::Volatile)
1779     QualsStr += " volatile";
1780   if (Proto->getTypeQuals() & Qualifiers::Restrict)
1781     QualsStr += " restrict";
1782   Result->AddInformativeChunk(QualsStr);
1783 }
1784 
1785 /// \brief If possible, create a new code completion string for the given
1786 /// result.
1787 ///
1788 /// \returns Either a new, heap-allocated code completion string describing
1789 /// how to use this result, or NULL to indicate that the string or name of the
1790 /// result is all that is needed.
1791 CodeCompletionString *
1792 CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
1793   typedef CodeCompletionString::Chunk Chunk;
1794 
1795   if (Kind == RK_Pattern)
1796     return Pattern->Clone();
1797 
1798   CodeCompletionString *Result = new CodeCompletionString;
1799 
1800   if (Kind == RK_Keyword) {
1801     Result->AddTypedTextChunk(Keyword);
1802     return Result;
1803   }
1804 
1805   if (Kind == RK_Macro) {
1806     MacroInfo *MI = S.PP.getMacroInfo(Macro);
1807     assert(MI && "Not a macro?");
1808 
1809     Result->AddTypedTextChunk(Macro->getName());
1810 
1811     if (!MI->isFunctionLike())
1812       return Result;
1813 
1814     // Format a function-like macro with placeholders for the arguments.
1815     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1816     for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1817          A != AEnd; ++A) {
1818       if (A != MI->arg_begin())
1819         Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1820 
1821       if (!MI->isVariadic() || A != AEnd - 1) {
1822         // Non-variadic argument.
1823         Result->AddPlaceholderChunk((*A)->getName());
1824         continue;
1825       }
1826 
1827       // Variadic argument; cope with the different between GNU and C99
1828       // variadic macros, providing a single placeholder for the rest of the
1829       // arguments.
1830       if ((*A)->isStr("__VA_ARGS__"))
1831         Result->AddPlaceholderChunk("...");
1832       else {
1833         std::string Arg = (*A)->getName();
1834         Arg += "...";
1835         Result->AddPlaceholderChunk(Arg);
1836       }
1837     }
1838     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1839     return Result;
1840   }
1841 
1842   assert(Kind == RK_Declaration && "Missed a result kind?");
1843   NamedDecl *ND = Declaration;
1844 
1845   if (StartsNestedNameSpecifier) {
1846     Result->AddTypedTextChunk(ND->getNameAsString());
1847     Result->AddTextChunk("::");
1848     return Result;
1849   }
1850 
1851   AddResultTypeChunk(S.Context, ND, Result);
1852 
1853   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
1854     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1855                                    S.Context);
1856     Result->AddTypedTextChunk(Function->getNameAsString());
1857     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1858     AddFunctionParameterChunks(S.Context, Function, Result);
1859     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1860     AddFunctionTypeQualsToCompletionString(Result, Function);
1861     return Result;
1862   }
1863 
1864   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1865     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1866                                    S.Context);
1867     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
1868     Result->AddTypedTextChunk(Function->getNameAsString());
1869 
1870     // Figure out which template parameters are deduced (or have default
1871     // arguments).
1872     llvm::SmallVector<bool, 16> Deduced;
1873     S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1874     unsigned LastDeducibleArgument;
1875     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1876          --LastDeducibleArgument) {
1877       if (!Deduced[LastDeducibleArgument - 1]) {
1878         // C++0x: Figure out if the template argument has a default. If so,
1879         // the user doesn't need to type this argument.
1880         // FIXME: We need to abstract template parameters better!
1881         bool HasDefaultArg = false;
1882         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1883                                                                       LastDeducibleArgument - 1);
1884         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1885           HasDefaultArg = TTP->hasDefaultArgument();
1886         else if (NonTypeTemplateParmDecl *NTTP
1887                  = dyn_cast<NonTypeTemplateParmDecl>(Param))
1888           HasDefaultArg = NTTP->hasDefaultArgument();
1889         else {
1890           assert(isa<TemplateTemplateParmDecl>(Param));
1891           HasDefaultArg
1892             = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
1893         }
1894 
1895         if (!HasDefaultArg)
1896           break;
1897       }
1898     }
1899 
1900     if (LastDeducibleArgument) {
1901       // Some of the function template arguments cannot be deduced from a
1902       // function call, so we introduce an explicit template argument list
1903       // containing all of the arguments up to the first deducible argument.
1904       Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1905       AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1906                                  LastDeducibleArgument);
1907       Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1908     }
1909 
1910     // Add the function parameters
1911     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1912     AddFunctionParameterChunks(S.Context, Function, Result);
1913     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1914     AddFunctionTypeQualsToCompletionString(Result, Function);
1915     return Result;
1916   }
1917 
1918   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
1919     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1920                                    S.Context);
1921     Result->AddTypedTextChunk(Template->getNameAsString());
1922     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1923     AddTemplateParameterChunks(S.Context, Template, Result);
1924     Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1925     return Result;
1926   }
1927 
1928   if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
1929     Selector Sel = Method->getSelector();
1930     if (Sel.isUnarySelector()) {
1931       Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1932       return Result;
1933     }
1934 
1935     std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1936     SelName += ':';
1937     if (StartParameter == 0)
1938       Result->AddTypedTextChunk(SelName);
1939     else {
1940       Result->AddInformativeChunk(SelName);
1941 
1942       // If there is only one parameter, and we're past it, add an empty
1943       // typed-text chunk since there is nothing to type.
1944       if (Method->param_size() == 1)
1945         Result->AddTypedTextChunk("");
1946     }
1947     unsigned Idx = 0;
1948     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1949                                      PEnd = Method->param_end();
1950          P != PEnd; (void)++P, ++Idx) {
1951       if (Idx > 0) {
1952         std::string Keyword;
1953         if (Idx > StartParameter)
1954           Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1955         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1956           Keyword += II->getName().str();
1957         Keyword += ":";
1958         if (Idx < StartParameter || AllParametersAreInformative) {
1959           Result->AddInformativeChunk(Keyword);
1960         } else if (Idx == StartParameter)
1961           Result->AddTypedTextChunk(Keyword);
1962         else
1963           Result->AddTextChunk(Keyword);
1964       }
1965 
1966       // If we're before the starting parameter, skip the placeholder.
1967       if (Idx < StartParameter)
1968         continue;
1969 
1970       std::string Arg;
1971       (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1972       Arg = "(" + Arg + ")";
1973       if (IdentifierInfo *II = (*P)->getIdentifier())
1974         Arg += II->getName().str();
1975       if (AllParametersAreInformative)
1976         Result->AddInformativeChunk(Arg);
1977       else
1978         Result->AddPlaceholderChunk(Arg);
1979     }
1980 
1981     if (Method->isVariadic()) {
1982       if (AllParametersAreInformative)
1983         Result->AddInformativeChunk(", ...");
1984       else
1985         Result->AddPlaceholderChunk(", ...");
1986     }
1987 
1988     return Result;
1989   }
1990 
1991   if (Qualifier)
1992     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1993                                    S.Context);
1994 
1995   Result->AddTypedTextChunk(ND->getNameAsString());
1996   return Result;
1997 }
1998 
1999 CodeCompletionString *
2000 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2001                                                           unsigned CurrentArg,
2002                                                                Sema &S) const {
2003   typedef CodeCompletionString::Chunk Chunk;
2004 
2005   CodeCompletionString *Result = new CodeCompletionString;
2006   FunctionDecl *FDecl = getFunction();
2007   AddResultTypeChunk(S.Context, FDecl, Result);
2008   const FunctionProtoType *Proto
2009     = dyn_cast<FunctionProtoType>(getFunctionType());
2010   if (!FDecl && !Proto) {
2011     // Function without a prototype. Just give the return type and a
2012     // highlighted ellipsis.
2013     const FunctionType *FT = getFunctionType();
2014     Result->AddTextChunk(
2015             FT->getResultType().getAsString(S.Context.PrintingPolicy));
2016     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2017     Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2018     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2019     return Result;
2020   }
2021 
2022   if (FDecl)
2023     Result->AddTextChunk(FDecl->getNameAsString());
2024   else
2025     Result->AddTextChunk(
2026          Proto->getResultType().getAsString(S.Context.PrintingPolicy));
2027 
2028   Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2029   unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2030   for (unsigned I = 0; I != NumParams; ++I) {
2031     if (I)
2032       Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2033 
2034     std::string ArgString;
2035     QualType ArgType;
2036 
2037     if (FDecl) {
2038       ArgString = FDecl->getParamDecl(I)->getNameAsString();
2039       ArgType = FDecl->getParamDecl(I)->getOriginalType();
2040     } else {
2041       ArgType = Proto->getArgType(I);
2042     }
2043 
2044     ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2045 
2046     if (I == CurrentArg)
2047       Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
2048                              ArgString));
2049     else
2050       Result->AddTextChunk(ArgString);
2051   }
2052 
2053   if (Proto && Proto->isVariadic()) {
2054     Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2055     if (CurrentArg < NumParams)
2056       Result->AddTextChunk("...");
2057     else
2058       Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2059   }
2060   Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2061 
2062   return Result;
2063 }
2064 
2065 namespace {
2066   struct SortCodeCompleteResult {
2067     typedef CodeCompleteConsumer::Result Result;
2068 
2069     bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
2070       Selector XSel = X.getObjCSelector();
2071       Selector YSel = Y.getObjCSelector();
2072       if (!XSel.isNull() && !YSel.isNull()) {
2073         // We are comparing two selectors.
2074         unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2075         if (N == 0)
2076           ++N;
2077         for (unsigned I = 0; I != N; ++I) {
2078           IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2079           IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2080           if (!XId || !YId)
2081             return XId && !YId;
2082 
2083           switch (XId->getName().compare_lower(YId->getName())) {
2084           case -1: return true;
2085           case 1: return false;
2086           default: break;
2087           }
2088         }
2089 
2090         return XSel.getNumArgs() < YSel.getNumArgs();
2091       }
2092 
2093       // For non-selectors, order by kind.
2094       if (X.getNameKind() != Y.getNameKind())
2095         return X.getNameKind() < Y.getNameKind();
2096 
2097       // Order identifiers by comparison of their lowercased names.
2098       if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2099         return XId->getName().compare_lower(
2100                                      Y.getAsIdentifierInfo()->getName()) < 0;
2101 
2102       // Order overloaded operators by the order in which they appear
2103       // in our list of operators.
2104       if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2105         return XOp < Y.getCXXOverloadedOperator();
2106 
2107       // Order C++0x user-defined literal operators lexically by their
2108       // lowercased suffixes.
2109       if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2110         return XLit->getName().compare_lower(
2111                                   Y.getCXXLiteralIdentifier()->getName()) < 0;
2112 
2113       // The only stable ordering we have is to turn the name into a
2114       // string and then compare the lower-case strings. This is
2115       // inefficient, but thankfully does not happen too often.
2116       return llvm::StringRef(X.getAsString()).compare_lower(
2117                                                  Y.getAsString()) < 0;
2118     }
2119 
2120     /// \brief Retrieve the name that should be used to order a result.
2121     ///
2122     /// If the name needs to be constructed as a string, that string will be
2123     /// saved into Saved and the returned StringRef will refer to it.
2124     static llvm::StringRef getOrderedName(const Result &R,
2125                                           std::string &Saved) {
2126       switch (R.Kind) {
2127       case Result::RK_Keyword:
2128         return R.Keyword;
2129 
2130       case Result::RK_Pattern:
2131         return R.Pattern->getTypedText();
2132 
2133       case Result::RK_Macro:
2134         return R.Macro->getName();
2135 
2136       case Result::RK_Declaration:
2137         // Handle declarations below.
2138         break;
2139       }
2140 
2141       DeclarationName Name = R.Declaration->getDeclName();
2142 
2143       // If the name is a simple identifier (by far the common case), or a
2144       // zero-argument selector, just return a reference to that identifier.
2145       if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2146         return Id->getName();
2147       if (Name.isObjCZeroArgSelector())
2148         if (IdentifierInfo *Id
2149                           = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2150           return Id->getName();
2151 
2152       Saved = Name.getAsString();
2153       return Saved;
2154     }
2155 
2156     bool operator()(const Result &X, const Result &Y) const {
2157       std::string XSaved, YSaved;
2158       llvm::StringRef XStr = getOrderedName(X, XSaved);
2159       llvm::StringRef YStr = getOrderedName(Y, YSaved);
2160       int cmp = XStr.compare_lower(YStr);
2161       if (cmp)
2162         return cmp < 0;
2163 
2164       // Non-hidden names precede hidden names.
2165       if (X.Hidden != Y.Hidden)
2166         return !X.Hidden;
2167 
2168       // Non-nested-name-specifiers precede nested-name-specifiers.
2169       if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2170         return !X.StartsNestedNameSpecifier;
2171 
2172       return false;
2173     }
2174   };
2175 }
2176 
2177 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
2178   Results.EnterNewScope();
2179   for (Preprocessor::macro_iterator M = PP.macro_begin(),
2180                                  MEnd = PP.macro_end();
2181        M != MEnd; ++M)
2182     Results.AddResult(M->first);
2183   Results.ExitScope();
2184 }
2185 
2186 static void HandleCodeCompleteResults(Sema *S,
2187                                       CodeCompleteConsumer *CodeCompleter,
2188                                      CodeCompleteConsumer::Result *Results,
2189                                      unsigned NumResults) {
2190   std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2191 
2192   if (CodeCompleter)
2193     CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
2194 
2195   for (unsigned I = 0; I != NumResults; ++I)
2196     Results[I].Destroy();
2197 }
2198 
2199 void Sema::CodeCompleteOrdinaryName(Scope *S,
2200                                     CodeCompletionContext CompletionContext) {
2201   typedef CodeCompleteConsumer::Result Result;
2202   ResultBuilder Results(*this);
2203 
2204   // Determine how to filter results, e.g., so that the names of
2205   // values (functions, enumerators, function templates, etc.) are
2206   // only allowed where we can have an expression.
2207   switch (CompletionContext) {
2208   case CCC_Namespace:
2209   case CCC_Class:
2210   case CCC_ObjCInterface:
2211   case CCC_ObjCImplementation:
2212   case CCC_ObjCInstanceVariableList:
2213   case CCC_Template:
2214   case CCC_MemberTemplate:
2215     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2216     break;
2217 
2218   case CCC_Expression:
2219   case CCC_Statement:
2220   case CCC_ForInit:
2221   case CCC_Condition:
2222     if (WantTypesInContext(CompletionContext, getLangOptions()))
2223       Results.setFilter(&ResultBuilder::IsOrdinaryName);
2224     else
2225       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2226     break;
2227 
2228   case CCC_RecoveryInFunction:
2229     // Unfiltered
2230     break;
2231   }
2232 
2233   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2234   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2235 
2236   Results.EnterNewScope();
2237   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
2238   Results.ExitScope();
2239 
2240   if (CodeCompleter->includeMacros())
2241     AddMacroResults(PP, Results);
2242   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2243 }
2244 
2245 /// \brief Perform code-completion in an expression context when we know what
2246 /// type we're looking for.
2247 void Sema::CodeCompleteExpression(Scope *S, QualType T) {
2248   typedef CodeCompleteConsumer::Result Result;
2249   ResultBuilder Results(*this);
2250 
2251   if (WantTypesInContext(CCC_Expression, getLangOptions()))
2252     Results.setFilter(&ResultBuilder::IsOrdinaryName);
2253   else
2254     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2255   Results.setPreferredType(T.getNonReferenceType());
2256 
2257   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2258   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2259 
2260   Results.EnterNewScope();
2261   AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
2262   Results.ExitScope();
2263 
2264   if (CodeCompleter->includeMacros())
2265     AddMacroResults(PP, Results);
2266   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2267 }
2268 
2269 
2270 static void AddObjCProperties(ObjCContainerDecl *Container,
2271                               bool AllowCategories,
2272                               DeclContext *CurContext,
2273                               ResultBuilder &Results) {
2274   typedef CodeCompleteConsumer::Result Result;
2275 
2276   // Add properties in this container.
2277   for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2278                                      PEnd = Container->prop_end();
2279        P != PEnd;
2280        ++P)
2281     Results.MaybeAddResult(Result(*P, 0), CurContext);
2282 
2283   // Add properties in referenced protocols.
2284   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2285     for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2286                                           PEnd = Protocol->protocol_end();
2287          P != PEnd; ++P)
2288       AddObjCProperties(*P, AllowCategories, CurContext, Results);
2289   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
2290     if (AllowCategories) {
2291       // Look through categories.
2292       for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2293            Category; Category = Category->getNextClassCategory())
2294         AddObjCProperties(Category, AllowCategories, CurContext, Results);
2295     }
2296 
2297     // Look through protocols.
2298     for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2299                                               E = IFace->protocol_end();
2300          I != E; ++I)
2301       AddObjCProperties(*I, AllowCategories, CurContext, Results);
2302 
2303     // Look in the superclass.
2304     if (IFace->getSuperClass())
2305       AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2306                         Results);
2307   } else if (const ObjCCategoryDecl *Category
2308                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
2309     // Look through protocols.
2310     for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2311                                            PEnd = Category->protocol_end();
2312          P != PEnd; ++P)
2313       AddObjCProperties(*P, AllowCategories, CurContext, Results);
2314   }
2315 }
2316 
2317 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2318                                            SourceLocation OpLoc,
2319                                            bool IsArrow) {
2320   if (!BaseE || !CodeCompleter)
2321     return;
2322 
2323   typedef CodeCompleteConsumer::Result Result;
2324 
2325   Expr *Base = static_cast<Expr *>(BaseE);
2326   QualType BaseType = Base->getType();
2327 
2328   if (IsArrow) {
2329     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2330       BaseType = Ptr->getPointeeType();
2331     else if (BaseType->isObjCObjectPointerType())
2332     /*Do nothing*/ ;
2333     else
2334       return;
2335   }
2336 
2337   ResultBuilder Results(*this, &ResultBuilder::IsMember);
2338   Results.EnterNewScope();
2339   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2340     // Access to a C/C++ class, struct, or union.
2341     Results.allowNestedNameSpecifiers();
2342     CodeCompletionDeclConsumer Consumer(Results, CurContext);
2343     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
2344 
2345     if (getLangOptions().CPlusPlus) {
2346       if (!Results.empty()) {
2347         // The "template" keyword can follow "->" or "." in the grammar.
2348         // However, we only want to suggest the template keyword if something
2349         // is dependent.
2350         bool IsDependent = BaseType->isDependentType();
2351         if (!IsDependent) {
2352           for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2353             if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2354               IsDependent = Ctx->isDependentContext();
2355               break;
2356             }
2357         }
2358 
2359         if (IsDependent)
2360           Results.AddResult(Result("template"));
2361       }
2362     }
2363   } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2364     // Objective-C property reference.
2365 
2366     // Add property results based on our interface.
2367     const ObjCObjectPointerType *ObjCPtr
2368       = BaseType->getAsObjCInterfacePointerType();
2369     assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
2370     AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
2371 
2372     // Add properties from the protocols in a qualified interface.
2373     for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2374                                               E = ObjCPtr->qual_end();
2375          I != E; ++I)
2376       AddObjCProperties(*I, true, CurContext, Results);
2377   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2378              (!IsArrow && BaseType->isObjCObjectType())) {
2379     // Objective-C instance variable access.
2380     ObjCInterfaceDecl *Class = 0;
2381     if (const ObjCObjectPointerType *ObjCPtr
2382                                     = BaseType->getAs<ObjCObjectPointerType>())
2383       Class = ObjCPtr->getInterfaceDecl();
2384     else
2385       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
2386 
2387     // Add all ivars from this class and its superclasses.
2388     if (Class) {
2389       CodeCompletionDeclConsumer Consumer(Results, CurContext);
2390       Results.setFilter(&ResultBuilder::IsObjCIvar);
2391       LookupVisibleDecls(Class, LookupMemberName, Consumer);
2392     }
2393   }
2394 
2395   // FIXME: How do we cope with isa?
2396 
2397   Results.ExitScope();
2398 
2399   // Hand off the results found for code completion.
2400   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2401 }
2402 
2403 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2404   if (!CodeCompleter)
2405     return;
2406 
2407   typedef CodeCompleteConsumer::Result Result;
2408   ResultBuilder::LookupFilter Filter = 0;
2409   switch ((DeclSpec::TST)TagSpec) {
2410   case DeclSpec::TST_enum:
2411     Filter = &ResultBuilder::IsEnum;
2412     break;
2413 
2414   case DeclSpec::TST_union:
2415     Filter = &ResultBuilder::IsUnion;
2416     break;
2417 
2418   case DeclSpec::TST_struct:
2419   case DeclSpec::TST_class:
2420     Filter = &ResultBuilder::IsClassOrStruct;
2421     break;
2422 
2423   default:
2424     assert(false && "Unknown type specifier kind in CodeCompleteTag");
2425     return;
2426   }
2427 
2428   ResultBuilder Results(*this);
2429   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2430 
2431   // First pass: look for tags.
2432   Results.setFilter(Filter);
2433   LookupVisibleDecls(S, LookupTagName, Consumer);
2434 
2435   // Second pass: look for nested name specifiers.
2436   Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2437   LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2438 
2439   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2440 }
2441 
2442 void Sema::CodeCompleteCase(Scope *S) {
2443   if (getSwitchStack().empty() || !CodeCompleter)
2444     return;
2445 
2446   SwitchStmt *Switch = getSwitchStack().back();
2447   if (!Switch->getCond()->getType()->isEnumeralType())
2448     return;
2449 
2450   // Code-complete the cases of a switch statement over an enumeration type
2451   // by providing the list of
2452   EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2453 
2454   // Determine which enumerators we have already seen in the switch statement.
2455   // FIXME: Ideally, we would also be able to look *past* the code-completion
2456   // token, in case we are code-completing in the middle of the switch and not
2457   // at the end. However, we aren't able to do so at the moment.
2458   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
2459   NestedNameSpecifier *Qualifier = 0;
2460   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2461        SC = SC->getNextSwitchCase()) {
2462     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2463     if (!Case)
2464       continue;
2465 
2466     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2467     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2468       if (EnumConstantDecl *Enumerator
2469             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2470         // We look into the AST of the case statement to determine which
2471         // enumerator was named. Alternatively, we could compute the value of
2472         // the integral constant expression, then compare it against the
2473         // values of each enumerator. However, value-based approach would not
2474         // work as well with C++ templates where enumerators declared within a
2475         // template are type- and value-dependent.
2476         EnumeratorsSeen.insert(Enumerator);
2477 
2478         // If this is a qualified-id, keep track of the nested-name-specifier
2479         // so that we can reproduce it as part of code completion, e.g.,
2480         //
2481         //   switch (TagD.getKind()) {
2482         //     case TagDecl::TK_enum:
2483         //       break;
2484         //     case XXX
2485         //
2486         // At the XXX, our completions are TagDecl::TK_union,
2487         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2488         // TK_struct, and TK_class.
2489         Qualifier = DRE->getQualifier();
2490       }
2491   }
2492 
2493   if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2494     // If there are no prior enumerators in C++, check whether we have to
2495     // qualify the names of the enumerators that we suggest, because they
2496     // may not be visible in this scope.
2497     Qualifier = getRequiredQualification(Context, CurContext,
2498                                          Enum->getDeclContext());
2499 
2500     // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2501   }
2502 
2503   // Add any enumerators that have not yet been mentioned.
2504   ResultBuilder Results(*this);
2505   Results.EnterNewScope();
2506   for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2507                                   EEnd = Enum->enumerator_end();
2508        E != EEnd; ++E) {
2509     if (EnumeratorsSeen.count(*E))
2510       continue;
2511 
2512     Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2513                       CurContext, 0, false);
2514   }
2515   Results.ExitScope();
2516 
2517   if (CodeCompleter->includeMacros())
2518     AddMacroResults(PP, Results);
2519   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2520 }
2521 
2522 namespace {
2523   struct IsBetterOverloadCandidate {
2524     Sema &S;
2525     SourceLocation Loc;
2526 
2527   public:
2528     explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2529       : S(S), Loc(Loc) { }
2530 
2531     bool
2532     operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
2533       return S.isBetterOverloadCandidate(X, Y, Loc);
2534     }
2535   };
2536 }
2537 
2538 static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2539   if (NumArgs && !Args)
2540     return true;
2541 
2542   for (unsigned I = 0; I != NumArgs; ++I)
2543     if (!Args[I])
2544       return true;
2545 
2546   return false;
2547 }
2548 
2549 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2550                             ExprTy **ArgsIn, unsigned NumArgs) {
2551   if (!CodeCompleter)
2552     return;
2553 
2554   // When we're code-completing for a call, we fall back to ordinary
2555   // name code-completion whenever we can't produce specific
2556   // results. We may want to revisit this strategy in the future,
2557   // e.g., by merging the two kinds of results.
2558 
2559   Expr *Fn = (Expr *)FnIn;
2560   Expr **Args = (Expr **)ArgsIn;
2561 
2562   // Ignore type-dependent call expressions entirely.
2563   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
2564       Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2565     CodeCompleteOrdinaryName(S, CCC_Expression);
2566     return;
2567   }
2568 
2569   // Build an overload candidate set based on the functions we find.
2570   SourceLocation Loc = Fn->getExprLoc();
2571   OverloadCandidateSet CandidateSet(Loc);
2572 
2573   // FIXME: What if we're calling something that isn't a function declaration?
2574   // FIXME: What if we're calling a pseudo-destructor?
2575   // FIXME: What if we're calling a member function?
2576 
2577   typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2578   llvm::SmallVector<ResultCandidate, 8> Results;
2579 
2580   Expr *NakedFn = Fn->IgnoreParenCasts();
2581   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2582     AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2583                                 /*PartialOverloading=*/ true);
2584   else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2585     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
2586     if (FDecl) {
2587       if (!getLangOptions().CPlusPlus ||
2588           !FDecl->getType()->getAs<FunctionProtoType>())
2589         Results.push_back(ResultCandidate(FDecl));
2590       else
2591         // FIXME: access?
2592         AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2593                              Args, NumArgs, CandidateSet,
2594                              false, /*PartialOverloading*/true);
2595     }
2596   }
2597 
2598   QualType ParamType;
2599 
2600   if (!CandidateSet.empty()) {
2601     // Sort the overload candidate set by placing the best overloads first.
2602     std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
2603                      IsBetterOverloadCandidate(*this, Loc));
2604 
2605     // Add the remaining viable overload candidates as code-completion reslults.
2606     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2607                                      CandEnd = CandidateSet.end();
2608          Cand != CandEnd; ++Cand) {
2609       if (Cand->Viable)
2610         Results.push_back(ResultCandidate(Cand->Function));
2611     }
2612 
2613     // From the viable candidates, try to determine the type of this parameter.
2614     for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2615       if (const FunctionType *FType = Results[I].getFunctionType())
2616         if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2617           if (NumArgs < Proto->getNumArgs()) {
2618             if (ParamType.isNull())
2619               ParamType = Proto->getArgType(NumArgs);
2620             else if (!Context.hasSameUnqualifiedType(
2621                                             ParamType.getNonReferenceType(),
2622                            Proto->getArgType(NumArgs).getNonReferenceType())) {
2623               ParamType = QualType();
2624               break;
2625             }
2626           }
2627     }
2628   } else {
2629     // Try to determine the parameter type from the type of the expression
2630     // being called.
2631     QualType FunctionType = Fn->getType();
2632     if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2633       FunctionType = Ptr->getPointeeType();
2634     else if (const BlockPointerType *BlockPtr
2635                                     = FunctionType->getAs<BlockPointerType>())
2636       FunctionType = BlockPtr->getPointeeType();
2637     else if (const MemberPointerType *MemPtr
2638                                     = FunctionType->getAs<MemberPointerType>())
2639       FunctionType = MemPtr->getPointeeType();
2640 
2641     if (const FunctionProtoType *Proto
2642                                   = FunctionType->getAs<FunctionProtoType>()) {
2643       if (NumArgs < Proto->getNumArgs())
2644         ParamType = Proto->getArgType(NumArgs);
2645     }
2646   }
2647 
2648   if (ParamType.isNull())
2649     CodeCompleteOrdinaryName(S, CCC_Expression);
2650   else
2651     CodeCompleteExpression(S, ParamType);
2652 
2653   if (!Results.empty())
2654     CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2655                                              Results.size());
2656 }
2657 
2658 void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2659   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2660   if (!VD) {
2661     CodeCompleteOrdinaryName(S, CCC_Expression);
2662     return;
2663   }
2664 
2665   CodeCompleteExpression(S, VD->getType());
2666 }
2667 
2668 void Sema::CodeCompleteReturn(Scope *S) {
2669   QualType ResultType;
2670   if (isa<BlockDecl>(CurContext)) {
2671     if (BlockScopeInfo *BSI = getCurBlock())
2672       ResultType = BSI->ReturnType;
2673   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2674     ResultType = Function->getResultType();
2675   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2676     ResultType = Method->getResultType();
2677 
2678   if (ResultType.isNull())
2679     CodeCompleteOrdinaryName(S, CCC_Expression);
2680   else
2681     CodeCompleteExpression(S, ResultType);
2682 }
2683 
2684 void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2685   if (LHS)
2686     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2687   else
2688     CodeCompleteOrdinaryName(S, CCC_Expression);
2689 }
2690 
2691 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
2692                                    bool EnteringContext) {
2693   if (!SS.getScopeRep() || !CodeCompleter)
2694     return;
2695 
2696   DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2697   if (!Ctx)
2698     return;
2699 
2700   // Try to instantiate any non-dependent declaration contexts before
2701   // we look in them.
2702   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
2703     return;
2704 
2705   ResultBuilder Results(*this);
2706   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2707   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
2708 
2709   // The "template" keyword can follow "::" in the grammar, but only
2710   // put it into the grammar if the nested-name-specifier is dependent.
2711   NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2712   if (!Results.empty() && NNS->isDependent())
2713     Results.AddResult("template");
2714 
2715   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2716 }
2717 
2718 void Sema::CodeCompleteUsing(Scope *S) {
2719   if (!CodeCompleter)
2720     return;
2721 
2722   ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
2723   Results.EnterNewScope();
2724 
2725   // If we aren't in class scope, we could see the "namespace" keyword.
2726   if (!S->isClassScope())
2727     Results.AddResult(CodeCompleteConsumer::Result("namespace"));
2728 
2729   // After "using", we can see anything that would start a
2730   // nested-name-specifier.
2731   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2732   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2733   Results.ExitScope();
2734 
2735   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2736 }
2737 
2738 void Sema::CodeCompleteUsingDirective(Scope *S) {
2739   if (!CodeCompleter)
2740     return;
2741 
2742   // After "using namespace", we expect to see a namespace name or namespace
2743   // alias.
2744   ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2745   Results.EnterNewScope();
2746   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2747   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2748   Results.ExitScope();
2749   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2750 }
2751 
2752 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
2753   if (!CodeCompleter)
2754     return;
2755 
2756   ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2757   DeclContext *Ctx = (DeclContext *)S->getEntity();
2758   if (!S->getParent())
2759     Ctx = Context.getTranslationUnitDecl();
2760 
2761   if (Ctx && Ctx->isFileContext()) {
2762     // We only want to see those namespaces that have already been defined
2763     // within this scope, because its likely that the user is creating an
2764     // extended namespace declaration. Keep track of the most recent
2765     // definition of each namespace.
2766     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2767     for (DeclContext::specific_decl_iterator<NamespaceDecl>
2768          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2769          NS != NSEnd; ++NS)
2770       OrigToLatest[NS->getOriginalNamespace()] = *NS;
2771 
2772     // Add the most recent definition (or extended definition) of each
2773     // namespace to the list of results.
2774     Results.EnterNewScope();
2775     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2776          NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2777          NS != NSEnd; ++NS)
2778       Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2779                         CurContext, 0, false);
2780     Results.ExitScope();
2781   }
2782 
2783   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2784 }
2785 
2786 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
2787   if (!CodeCompleter)
2788     return;
2789 
2790   // After "namespace", we expect to see a namespace or alias.
2791   ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2792   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2793   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2794   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2795 }
2796 
2797 void Sema::CodeCompleteOperatorName(Scope *S) {
2798   if (!CodeCompleter)
2799     return;
2800 
2801   typedef CodeCompleteConsumer::Result Result;
2802   ResultBuilder Results(*this, &ResultBuilder::IsType);
2803   Results.EnterNewScope();
2804 
2805   // Add the names of overloadable operators.
2806 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
2807   if (std::strcmp(Spelling, "?"))                                                  \
2808     Results.AddResult(Result(Spelling));
2809 #include "clang/Basic/OperatorKinds.def"
2810 
2811   // Add any type names visible from the current scope
2812   Results.allowNestedNameSpecifiers();
2813   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2814   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2815 
2816   // Add any type specifiers
2817   AddTypeSpecifierResults(getLangOptions(), Results);
2818   Results.ExitScope();
2819 
2820   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2821 }
2822 
2823 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2824 // true or false.
2825 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
2826 static void AddObjCImplementationResults(const LangOptions &LangOpts,
2827                                          ResultBuilder &Results,
2828                                          bool NeedAt) {
2829   typedef CodeCompleteConsumer::Result Result;
2830   // Since we have an implementation, we can end it.
2831   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2832 
2833   CodeCompletionString *Pattern = 0;
2834   if (LangOpts.ObjC2) {
2835     // @dynamic
2836     Pattern = new CodeCompletionString;
2837     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2838     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2839     Pattern->AddPlaceholderChunk("property");
2840     Results.AddResult(Result(Pattern));
2841 
2842     // @synthesize
2843     Pattern = new CodeCompletionString;
2844     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2845     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2846     Pattern->AddPlaceholderChunk("property");
2847     Results.AddResult(Result(Pattern));
2848   }
2849 }
2850 
2851 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
2852                                     ResultBuilder &Results,
2853                                     bool NeedAt) {
2854   typedef CodeCompleteConsumer::Result Result;
2855 
2856   // Since we have an interface or protocol, we can end it.
2857   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2858 
2859   if (LangOpts.ObjC2) {
2860     // @property
2861     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
2862 
2863     // @required
2864     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
2865 
2866     // @optional
2867     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
2868   }
2869 }
2870 
2871 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
2872   typedef CodeCompleteConsumer::Result Result;
2873   CodeCompletionString *Pattern = 0;
2874 
2875   // @class name ;
2876   Pattern = new CodeCompletionString;
2877   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2878   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2879   Pattern->AddPlaceholderChunk("name");
2880   Results.AddResult(Result(Pattern));
2881 
2882   if (Results.includeCodePatterns()) {
2883     // @interface name
2884     // FIXME: Could introduce the whole pattern, including superclasses and
2885     // such.
2886     Pattern = new CodeCompletionString;
2887     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2888     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2889     Pattern->AddPlaceholderChunk("class");
2890     Results.AddResult(Result(Pattern));
2891 
2892     // @protocol name
2893     Pattern = new CodeCompletionString;
2894     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2895     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2896     Pattern->AddPlaceholderChunk("protocol");
2897     Results.AddResult(Result(Pattern));
2898 
2899     // @implementation name
2900     Pattern = new CodeCompletionString;
2901     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2902     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2903     Pattern->AddPlaceholderChunk("class");
2904     Results.AddResult(Result(Pattern));
2905   }
2906 
2907   // @compatibility_alias name
2908   Pattern = new CodeCompletionString;
2909   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2910   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2911   Pattern->AddPlaceholderChunk("alias");
2912   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2913   Pattern->AddPlaceholderChunk("class");
2914   Results.AddResult(Result(Pattern));
2915 }
2916 
2917 void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2918                                        bool InInterface) {
2919   typedef CodeCompleteConsumer::Result Result;
2920   ResultBuilder Results(*this);
2921   Results.EnterNewScope();
2922   if (ObjCImpDecl)
2923     AddObjCImplementationResults(getLangOptions(), Results, false);
2924   else if (InInterface)
2925     AddObjCInterfaceResults(getLangOptions(), Results, false);
2926   else
2927     AddObjCTopLevelResults(Results, false);
2928   Results.ExitScope();
2929   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2930 }
2931 
2932 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
2933   typedef CodeCompleteConsumer::Result Result;
2934   CodeCompletionString *Pattern = 0;
2935 
2936   // @encode ( type-name )
2937   Pattern = new CodeCompletionString;
2938   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
2939   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2940   Pattern->AddPlaceholderChunk("type-name");
2941   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2942   Results.AddResult(Result(Pattern));
2943 
2944   // @protocol ( protocol-name )
2945   Pattern = new CodeCompletionString;
2946   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2947   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2948   Pattern->AddPlaceholderChunk("protocol-name");
2949   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2950   Results.AddResult(Result(Pattern));
2951 
2952   // @selector ( selector )
2953   Pattern = new CodeCompletionString;
2954   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
2955   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2956   Pattern->AddPlaceholderChunk("selector");
2957   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2958   Results.AddResult(Result(Pattern));
2959 }
2960 
2961 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
2962   typedef CodeCompleteConsumer::Result Result;
2963   CodeCompletionString *Pattern = 0;
2964 
2965   if (Results.includeCodePatterns()) {
2966     // @try { statements } @catch ( declaration ) { statements } @finally
2967     //   { statements }
2968     Pattern = new CodeCompletionString;
2969     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2970     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2971     Pattern->AddPlaceholderChunk("statements");
2972     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2973     Pattern->AddTextChunk("@catch");
2974     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2975     Pattern->AddPlaceholderChunk("parameter");
2976     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2977     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2978     Pattern->AddPlaceholderChunk("statements");
2979     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2980     Pattern->AddTextChunk("@finally");
2981     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2982     Pattern->AddPlaceholderChunk("statements");
2983     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2984     Results.AddResult(Result(Pattern));
2985   }
2986 
2987   // @throw
2988   Pattern = new CodeCompletionString;
2989   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
2990   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2991   Pattern->AddPlaceholderChunk("expression");
2992   Results.AddResult(Result(Pattern));
2993 
2994   if (Results.includeCodePatterns()) {
2995     // @synchronized ( expression ) { statements }
2996     Pattern = new CodeCompletionString;
2997     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
2998     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2999     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3000     Pattern->AddPlaceholderChunk("expression");
3001     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3002     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3003     Pattern->AddPlaceholderChunk("statements");
3004     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3005     Results.AddResult(Result(Pattern));
3006   }
3007 }
3008 
3009 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
3010                                      ResultBuilder &Results,
3011                                      bool NeedAt) {
3012   typedef CodeCompleteConsumer::Result Result;
3013   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3014   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3015   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
3016   if (LangOpts.ObjC2)
3017     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
3018 }
3019 
3020 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3021   ResultBuilder Results(*this);
3022   Results.EnterNewScope();
3023   AddObjCVisibilityResults(getLangOptions(), Results, false);
3024   Results.ExitScope();
3025   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3026 }
3027 
3028 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
3029   ResultBuilder Results(*this);
3030   Results.EnterNewScope();
3031   AddObjCStatementResults(Results, false);
3032   AddObjCExpressionResults(Results, false);
3033   Results.ExitScope();
3034   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3035 }
3036 
3037 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3038   ResultBuilder Results(*this);
3039   Results.EnterNewScope();
3040   AddObjCExpressionResults(Results, false);
3041   Results.ExitScope();
3042   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3043 }
3044 
3045 /// \brief Determine whether the addition of the given flag to an Objective-C
3046 /// property's attributes will cause a conflict.
3047 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3048   // Check if we've already added this flag.
3049   if (Attributes & NewFlag)
3050     return true;
3051 
3052   Attributes |= NewFlag;
3053 
3054   // Check for collisions with "readonly".
3055   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3056       (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3057                      ObjCDeclSpec::DQ_PR_assign |
3058                      ObjCDeclSpec::DQ_PR_copy |
3059                      ObjCDeclSpec::DQ_PR_retain)))
3060     return true;
3061 
3062   // Check for more than one of { assign, copy, retain }.
3063   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3064                                              ObjCDeclSpec::DQ_PR_copy |
3065                                              ObjCDeclSpec::DQ_PR_retain);
3066   if (AssignCopyRetMask &&
3067       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3068       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3069       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3070     return true;
3071 
3072   return false;
3073 }
3074 
3075 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
3076   if (!CodeCompleter)
3077     return;
3078 
3079   unsigned Attributes = ODS.getPropertyAttributes();
3080 
3081   typedef CodeCompleteConsumer::Result Result;
3082   ResultBuilder Results(*this);
3083   Results.EnterNewScope();
3084   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
3085     Results.AddResult(CodeCompleteConsumer::Result("readonly"));
3086   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
3087     Results.AddResult(CodeCompleteConsumer::Result("assign"));
3088   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
3089     Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
3090   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
3091     Results.AddResult(CodeCompleteConsumer::Result("retain"));
3092   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
3093     Results.AddResult(CodeCompleteConsumer::Result("copy"));
3094   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
3095     Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
3096   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
3097     CodeCompletionString *Setter = new CodeCompletionString;
3098     Setter->AddTypedTextChunk("setter");
3099     Setter->AddTextChunk(" = ");
3100     Setter->AddPlaceholderChunk("method");
3101     Results.AddResult(CodeCompleteConsumer::Result(Setter));
3102   }
3103   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
3104     CodeCompletionString *Getter = new CodeCompletionString;
3105     Getter->AddTypedTextChunk("getter");
3106     Getter->AddTextChunk(" = ");
3107     Getter->AddPlaceholderChunk("method");
3108     Results.AddResult(CodeCompleteConsumer::Result(Getter));
3109   }
3110   Results.ExitScope();
3111   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3112 }
3113 
3114 /// \brief Descripts the kind of Objective-C method that we want to find
3115 /// via code completion.
3116 enum ObjCMethodKind {
3117   MK_Any, //< Any kind of method, provided it means other specified criteria.
3118   MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3119   MK_OneArgSelector //< One-argument selector.
3120 };
3121 
3122 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3123                                    ObjCMethodKind WantKind,
3124                                    IdentifierInfo **SelIdents,
3125                                    unsigned NumSelIdents) {
3126   Selector Sel = Method->getSelector();
3127   if (NumSelIdents > Sel.getNumArgs())
3128     return false;
3129 
3130   switch (WantKind) {
3131   case MK_Any:             break;
3132   case MK_ZeroArgSelector: return Sel.isUnarySelector();
3133   case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
3134   }
3135 
3136   for (unsigned I = 0; I != NumSelIdents; ++I)
3137     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3138       return false;
3139 
3140   return true;
3141 }
3142 
3143 /// \brief Add all of the Objective-C methods in the given Objective-C
3144 /// container to the set of results.
3145 ///
3146 /// The container will be a class, protocol, category, or implementation of
3147 /// any of the above. This mether will recurse to include methods from
3148 /// the superclasses of classes along with their categories, protocols, and
3149 /// implementations.
3150 ///
3151 /// \param Container the container in which we'll look to find methods.
3152 ///
3153 /// \param WantInstance whether to add instance methods (only); if false, this
3154 /// routine will add factory methods (only).
3155 ///
3156 /// \param CurContext the context in which we're performing the lookup that
3157 /// finds methods.
3158 ///
3159 /// \param Results the structure into which we'll add results.
3160 static void AddObjCMethods(ObjCContainerDecl *Container,
3161                            bool WantInstanceMethods,
3162                            ObjCMethodKind WantKind,
3163                            IdentifierInfo **SelIdents,
3164                            unsigned NumSelIdents,
3165                            DeclContext *CurContext,
3166                            ResultBuilder &Results) {
3167   typedef CodeCompleteConsumer::Result Result;
3168   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3169                                        MEnd = Container->meth_end();
3170        M != MEnd; ++M) {
3171     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3172       // Check whether the selector identifiers we've been given are a
3173       // subset of the identifiers for this particular method.
3174       if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
3175         continue;
3176 
3177       Result R = Result(*M, 0);
3178       R.StartParameter = NumSelIdents;
3179       R.AllParametersAreInformative = (WantKind != MK_Any);
3180       Results.MaybeAddResult(R, CurContext);
3181     }
3182   }
3183 
3184   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3185   if (!IFace)
3186     return;
3187 
3188   // Add methods in protocols.
3189   const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3190   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3191                                             E = Protocols.end();
3192        I != E; ++I)
3193     AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
3194                    CurContext, Results);
3195 
3196   // Add methods in categories.
3197   for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3198        CatDecl = CatDecl->getNextClassCategory()) {
3199     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3200                    NumSelIdents, CurContext, Results);
3201 
3202     // Add a categories protocol methods.
3203     const ObjCList<ObjCProtocolDecl> &Protocols
3204       = CatDecl->getReferencedProtocols();
3205     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3206                                               E = Protocols.end();
3207          I != E; ++I)
3208       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3209                      NumSelIdents, CurContext, Results);
3210 
3211     // Add methods in category implementations.
3212     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
3213       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3214                      NumSelIdents, CurContext, Results);
3215   }
3216 
3217   // Add methods in superclass.
3218   if (IFace->getSuperClass())
3219     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3220                    SelIdents, NumSelIdents, CurContext, Results);
3221 
3222   // Add methods in our implementation, if any.
3223   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
3224     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3225                    NumSelIdents, CurContext, Results);
3226 }
3227 
3228 
3229 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3230                                           DeclPtrTy *Methods,
3231                                           unsigned NumMethods) {
3232   typedef CodeCompleteConsumer::Result Result;
3233 
3234   // Try to find the interface where getters might live.
3235   ObjCInterfaceDecl *Class
3236     = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3237   if (!Class) {
3238     if (ObjCCategoryDecl *Category
3239           = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3240       Class = Category->getClassInterface();
3241 
3242     if (!Class)
3243       return;
3244   }
3245 
3246   // Find all of the potential getters.
3247   ResultBuilder Results(*this);
3248   Results.EnterNewScope();
3249 
3250   // FIXME: We need to do this because Objective-C methods don't get
3251   // pushed into DeclContexts early enough. Argh!
3252   for (unsigned I = 0; I != NumMethods; ++I) {
3253     if (ObjCMethodDecl *Method
3254             = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3255       if (Method->isInstanceMethod() &&
3256           isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3257         Result R = Result(Method, 0);
3258         R.AllParametersAreInformative = true;
3259         Results.MaybeAddResult(R, CurContext);
3260       }
3261   }
3262 
3263   AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3264   Results.ExitScope();
3265   HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3266 }
3267 
3268 void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3269                                           DeclPtrTy *Methods,
3270                                           unsigned NumMethods) {
3271   typedef CodeCompleteConsumer::Result Result;
3272 
3273   // Try to find the interface where setters might live.
3274   ObjCInterfaceDecl *Class
3275     = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3276   if (!Class) {
3277     if (ObjCCategoryDecl *Category
3278           = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3279       Class = Category->getClassInterface();
3280 
3281     if (!Class)
3282       return;
3283   }
3284 
3285   // Find all of the potential getters.
3286   ResultBuilder Results(*this);
3287   Results.EnterNewScope();
3288 
3289   // FIXME: We need to do this because Objective-C methods don't get
3290   // pushed into DeclContexts early enough. Argh!
3291   for (unsigned I = 0; I != NumMethods; ++I) {
3292     if (ObjCMethodDecl *Method
3293             = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3294       if (Method->isInstanceMethod() &&
3295           isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3296         Result R = Result(Method, 0);
3297         R.AllParametersAreInformative = true;
3298         Results.MaybeAddResult(R, CurContext);
3299       }
3300   }
3301 
3302   AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3303 
3304   Results.ExitScope();
3305   HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3306 }
3307 
3308 /// \brief When we have an expression with type "id", we may assume
3309 /// that it has some more-specific class type based on knowledge of
3310 /// common uses of Objective-C. This routine returns that class type,
3311 /// or NULL if no better result could be determined.
3312 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3313   ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3314   if (!Msg)
3315     return 0;
3316 
3317   Selector Sel = Msg->getSelector();
3318   if (Sel.isNull())
3319     return 0;
3320 
3321   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3322   if (!Id)
3323     return 0;
3324 
3325   ObjCMethodDecl *Method = Msg->getMethodDecl();
3326   if (!Method)
3327     return 0;
3328 
3329   // Determine the class that we're sending the message to.
3330   ObjCInterfaceDecl *IFace = 0;
3331   switch (Msg->getReceiverKind()) {
3332   case ObjCMessageExpr::Class:
3333     if (const ObjCObjectType *ObjType
3334                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3335       IFace = ObjType->getInterface();
3336     break;
3337 
3338   case ObjCMessageExpr::Instance: {
3339     QualType T = Msg->getInstanceReceiver()->getType();
3340     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3341       IFace = Ptr->getInterfaceDecl();
3342     break;
3343   }
3344 
3345   case ObjCMessageExpr::SuperInstance:
3346   case ObjCMessageExpr::SuperClass:
3347     break;
3348   }
3349 
3350   if (!IFace)
3351     return 0;
3352 
3353   ObjCInterfaceDecl *Super = IFace->getSuperClass();
3354   if (Method->isInstanceMethod())
3355     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3356       .Case("retain", IFace)
3357       .Case("autorelease", IFace)
3358       .Case("copy", IFace)
3359       .Case("copyWithZone", IFace)
3360       .Case("mutableCopy", IFace)
3361       .Case("mutableCopyWithZone", IFace)
3362       .Case("awakeFromCoder", IFace)
3363       .Case("replacementObjectFromCoder", IFace)
3364       .Case("class", IFace)
3365       .Case("classForCoder", IFace)
3366       .Case("superclass", Super)
3367       .Default(0);
3368 
3369   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3370     .Case("new", IFace)
3371     .Case("alloc", IFace)
3372     .Case("allocWithZone", IFace)
3373     .Case("class", IFace)
3374     .Case("superclass", Super)
3375     .Default(0);
3376 }
3377 
3378 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3379   typedef CodeCompleteConsumer::Result Result;
3380   ResultBuilder Results(*this);
3381 
3382   // Find anything that looks like it could be a message receiver.
3383   Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3384   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3385   Results.EnterNewScope();
3386   LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
3387 
3388   // If we are in an Objective-C method inside a class that has a superclass,
3389   // add "super" as an option.
3390   if (ObjCMethodDecl *Method = getCurMethodDecl())
3391     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3392       if (Iface->getSuperClass())
3393         Results.AddResult(Result("super"));
3394 
3395   Results.ExitScope();
3396 
3397   if (CodeCompleter->includeMacros())
3398     AddMacroResults(PP, Results);
3399   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3400 
3401 }
3402 
3403 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3404                                         IdentifierInfo **SelIdents,
3405                                         unsigned NumSelIdents) {
3406   ObjCInterfaceDecl *CDecl = 0;
3407   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3408     // Figure out which interface we're in.
3409     CDecl = CurMethod->getClassInterface();
3410     if (!CDecl)
3411       return;
3412 
3413     // Find the superclass of this class.
3414     CDecl = CDecl->getSuperClass();
3415     if (!CDecl)
3416       return;
3417 
3418     if (CurMethod->isInstanceMethod()) {
3419       // We are inside an instance method, which means that the message
3420       // send [super ...] is actually calling an instance method on the
3421       // current object. Build the super expression and handle this like
3422       // an instance method.
3423       QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3424       SuperTy = Context.getObjCObjectPointerType(SuperTy);
3425       OwningExprResult Super
3426         = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3427       return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3428                                              SelIdents, NumSelIdents);
3429     }
3430 
3431     // Fall through to send to the superclass in CDecl.
3432   } else {
3433     // "super" may be the name of a type or variable. Figure out which
3434     // it is.
3435     IdentifierInfo *Super = &Context.Idents.get("super");
3436     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3437                                      LookupOrdinaryName);
3438     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3439       // "super" names an interface. Use it.
3440     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
3441       if (const ObjCObjectType *Iface
3442             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3443         CDecl = Iface->getInterface();
3444     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3445       // "super" names an unresolved type; we can't be more specific.
3446     } else {
3447       // Assume that "super" names some kind of value and parse that way.
3448       CXXScopeSpec SS;
3449       UnqualifiedId id;
3450       id.setIdentifier(Super, SuperLoc);
3451       OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3452       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3453                                              SelIdents, NumSelIdents);
3454     }
3455 
3456     // Fall through
3457   }
3458 
3459   TypeTy *Receiver = 0;
3460   if (CDecl)
3461     Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3462   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3463                                       NumSelIdents);
3464 }
3465 
3466 void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
3467                                         IdentifierInfo **SelIdents,
3468                                         unsigned NumSelIdents) {
3469   typedef CodeCompleteConsumer::Result Result;
3470   ObjCInterfaceDecl *CDecl = 0;
3471 
3472   // If the given name refers to an interface type, retrieve the
3473   // corresponding declaration.
3474   if (Receiver) {
3475     QualType T = GetTypeFromParser(Receiver, 0);
3476     if (!T.isNull())
3477       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3478         CDecl = Interface->getInterface();
3479   }
3480 
3481   // Add all of the factory methods in this Objective-C class, its protocols,
3482   // superclasses, categories, implementation, etc.
3483   ResultBuilder Results(*this);
3484   Results.EnterNewScope();
3485 
3486   if (CDecl)
3487     AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3488                    Results);
3489   else {
3490     // We're messaging "id" as a type; provide all class/factory methods.
3491 
3492     // If we have an external source, load the entire class method
3493     // pool from the PCH file.
3494     if (ExternalSource) {
3495       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3496            I != N; ++I) {
3497         Selector Sel = ExternalSource->GetExternalSelector(I);
3498         if (Sel.isNull() || FactoryMethodPool.count(Sel) ||
3499             InstanceMethodPool.count(Sel))
3500           continue;
3501 
3502         ReadMethodPool(Sel, /*isInstance=*/false);
3503       }
3504     }
3505 
3506     for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3507            M = FactoryMethodPool.begin(),
3508            MEnd = FactoryMethodPool.end();
3509          M != MEnd;
3510          ++M) {
3511       for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
3512            MethList = MethList->Next) {
3513         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3514                                     NumSelIdents))
3515           continue;
3516 
3517         Result R(MethList->Method, 0);
3518         R.StartParameter = NumSelIdents;
3519         R.AllParametersAreInformative = false;
3520         Results.MaybeAddResult(R, CurContext);
3521       }
3522     }
3523   }
3524 
3525   Results.ExitScope();
3526   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3527 }
3528 
3529 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3530                                            IdentifierInfo **SelIdents,
3531                                            unsigned NumSelIdents) {
3532   typedef CodeCompleteConsumer::Result Result;
3533 
3534   Expr *RecExpr = static_cast<Expr *>(Receiver);
3535 
3536   // If necessary, apply function/array conversion to the receiver.
3537   // C99 6.7.5.3p[7,8].
3538   DefaultFunctionArrayLvalueConversion(RecExpr);
3539   QualType ReceiverType = RecExpr->getType();
3540 
3541   // Build the set of methods we can see.
3542   ResultBuilder Results(*this);
3543   Results.EnterNewScope();
3544 
3545   // If we're messaging an expression with type "id" or "Class", check
3546   // whether we know something special about the receiver that allows
3547   // us to assume a more-specific receiver type.
3548   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3549     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3550       ReceiverType = Context.getObjCObjectPointerType(
3551                                           Context.getObjCInterfaceType(IFace));
3552 
3553   // Handle messages to Class. This really isn't a message to an instance
3554   // method, so we treat it the same way we would treat a message send to a
3555   // class method.
3556   if (ReceiverType->isObjCClassType() ||
3557       ReceiverType->isObjCQualifiedClassType()) {
3558     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3559       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
3560         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3561                        CurContext, Results);
3562     }
3563   }
3564   // Handle messages to a qualified ID ("id<foo>").
3565   else if (const ObjCObjectPointerType *QualID
3566              = ReceiverType->getAsObjCQualifiedIdType()) {
3567     // Search protocols for instance methods.
3568     for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3569                                               E = QualID->qual_end();
3570          I != E; ++I)
3571       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3572                      Results);
3573   }
3574   // Handle messages to a pointer to interface type.
3575   else if (const ObjCObjectPointerType *IFacePtr
3576                               = ReceiverType->getAsObjCInterfacePointerType()) {
3577     // Search the class, its superclasses, etc., for instance methods.
3578     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3579                    NumSelIdents, CurContext, Results);
3580 
3581     // Search protocols for instance methods.
3582     for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3583          E = IFacePtr->qual_end();
3584          I != E; ++I)
3585       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3586                      Results);
3587   }
3588   // Handle messages to "id".
3589   else if (ReceiverType->isObjCIdType()) {
3590     // We're messaging "id", so provide all instance methods we know
3591     // about as code-completion results.
3592 
3593     // If we have an external source, load the entire class method
3594     // pool from the PCH file.
3595     if (ExternalSource) {
3596       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3597            I != N; ++I) {
3598         Selector Sel = ExternalSource->GetExternalSelector(I);
3599         if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
3600             FactoryMethodPool.count(Sel))
3601           continue;
3602 
3603         ReadMethodPool(Sel, /*isInstance=*/true);
3604       }
3605     }
3606 
3607     for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3608            M = InstanceMethodPool.begin(),
3609            MEnd = InstanceMethodPool.end();
3610          M != MEnd;
3611          ++M) {
3612       for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
3613            MethList = MethList->Next) {
3614         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3615                                     NumSelIdents))
3616           continue;
3617 
3618         Result R(MethList->Method, 0);
3619         R.StartParameter = NumSelIdents;
3620         R.AllParametersAreInformative = false;
3621         Results.MaybeAddResult(R, CurContext);
3622       }
3623     }
3624   }
3625 
3626   Results.ExitScope();
3627   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3628 }
3629 
3630 /// \brief Add all of the protocol declarations that we find in the given
3631 /// (translation unit) context.
3632 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
3633                                bool OnlyForwardDeclarations,
3634                                ResultBuilder &Results) {
3635   typedef CodeCompleteConsumer::Result Result;
3636 
3637   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3638                                DEnd = Ctx->decls_end();
3639        D != DEnd; ++D) {
3640     // Record any protocols we find.
3641     if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
3642       if (!OnlyForwardDeclarations || Proto->isForwardDecl())
3643         Results.AddResult(Result(Proto, 0), CurContext, 0, false);
3644 
3645     // Record any forward-declared protocols we find.
3646     if (ObjCForwardProtocolDecl *Forward
3647           = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3648       for (ObjCForwardProtocolDecl::protocol_iterator
3649              P = Forward->protocol_begin(),
3650              PEnd = Forward->protocol_end();
3651            P != PEnd; ++P)
3652         if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
3653           Results.AddResult(Result(*P, 0), CurContext, 0, false);
3654     }
3655   }
3656 }
3657 
3658 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3659                                               unsigned NumProtocols) {
3660   ResultBuilder Results(*this);
3661   Results.EnterNewScope();
3662 
3663   // Tell the result set to ignore all of the protocols we have
3664   // already seen.
3665   for (unsigned I = 0; I != NumProtocols; ++I)
3666     if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3667                                                     Protocols[I].second))
3668       Results.Ignore(Protocol);
3669 
3670   // Add all protocols.
3671   AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3672                      Results);
3673 
3674   Results.ExitScope();
3675   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3676 }
3677 
3678 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3679   ResultBuilder Results(*this);
3680   Results.EnterNewScope();
3681 
3682   // Add all protocols.
3683   AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3684                      Results);
3685 
3686   Results.ExitScope();
3687   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3688 }
3689 
3690 /// \brief Add all of the Objective-C interface declarations that we find in
3691 /// the given (translation unit) context.
3692 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3693                                 bool OnlyForwardDeclarations,
3694                                 bool OnlyUnimplemented,
3695                                 ResultBuilder &Results) {
3696   typedef CodeCompleteConsumer::Result Result;
3697 
3698   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3699                                DEnd = Ctx->decls_end();
3700        D != DEnd; ++D) {
3701     // Record any interfaces we find.
3702     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3703       if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3704           (!OnlyUnimplemented || !Class->getImplementation()))
3705         Results.AddResult(Result(Class, 0), CurContext, 0, false);
3706 
3707     // Record any forward-declared interfaces we find.
3708     if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3709       for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3710            C != CEnd; ++C)
3711         if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3712             (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3713           Results.AddResult(Result(C->getInterface(), 0), CurContext,
3714                             0, false);
3715     }
3716   }
3717 }
3718 
3719 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3720   ResultBuilder Results(*this);
3721   Results.EnterNewScope();
3722 
3723   // Add all classes.
3724   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3725                       false, Results);
3726 
3727   Results.ExitScope();
3728   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3729 }
3730 
3731 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3732                                       SourceLocation ClassNameLoc) {
3733   ResultBuilder Results(*this);
3734   Results.EnterNewScope();
3735 
3736   // Make sure that we ignore the class we're currently defining.
3737   NamedDecl *CurClass
3738     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
3739   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
3740     Results.Ignore(CurClass);
3741 
3742   // Add all classes.
3743   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3744                       false, Results);
3745 
3746   Results.ExitScope();
3747   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3748 }
3749 
3750 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3751   ResultBuilder Results(*this);
3752   Results.EnterNewScope();
3753 
3754   // Add all unimplemented classes.
3755   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3756                       true, Results);
3757 
3758   Results.ExitScope();
3759   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3760 }
3761 
3762 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
3763                                              IdentifierInfo *ClassName,
3764                                              SourceLocation ClassNameLoc) {
3765   typedef CodeCompleteConsumer::Result Result;
3766 
3767   ResultBuilder Results(*this);
3768 
3769   // Ignore any categories we find that have already been implemented by this
3770   // interface.
3771   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3772   NamedDecl *CurClass
3773     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
3774   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3775     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3776          Category = Category->getNextClassCategory())
3777       CategoryNames.insert(Category->getIdentifier());
3778 
3779   // Add all of the categories we know about.
3780   Results.EnterNewScope();
3781   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3782   for (DeclContext::decl_iterator D = TU->decls_begin(),
3783                                DEnd = TU->decls_end();
3784        D != DEnd; ++D)
3785     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3786       if (CategoryNames.insert(Category->getIdentifier()))
3787         Results.AddResult(Result(Category, 0), CurContext, 0, false);
3788   Results.ExitScope();
3789 
3790   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3791 }
3792 
3793 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
3794                                                   IdentifierInfo *ClassName,
3795                                                   SourceLocation ClassNameLoc) {
3796   typedef CodeCompleteConsumer::Result Result;
3797 
3798   // Find the corresponding interface. If we couldn't find the interface, the
3799   // program itself is ill-formed. However, we'll try to be helpful still by
3800   // providing the list of all of the categories we know about.
3801   NamedDecl *CurClass
3802     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
3803   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3804   if (!Class)
3805     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
3806 
3807   ResultBuilder Results(*this);
3808 
3809   // Add all of the categories that have have corresponding interface
3810   // declarations in this class and any of its superclasses, except for
3811   // already-implemented categories in the class itself.
3812   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3813   Results.EnterNewScope();
3814   bool IgnoreImplemented = true;
3815   while (Class) {
3816     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3817          Category = Category->getNextClassCategory())
3818       if ((!IgnoreImplemented || !Category->getImplementation()) &&
3819           CategoryNames.insert(Category->getIdentifier()))
3820         Results.AddResult(Result(Category, 0), CurContext, 0, false);
3821 
3822     Class = Class->getSuperClass();
3823     IgnoreImplemented = false;
3824   }
3825   Results.ExitScope();
3826 
3827   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3828 }
3829 
3830 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
3831   typedef CodeCompleteConsumer::Result Result;
3832   ResultBuilder Results(*this);
3833 
3834   // Figure out where this @synthesize lives.
3835   ObjCContainerDecl *Container
3836     = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3837   if (!Container ||
3838       (!isa<ObjCImplementationDecl>(Container) &&
3839        !isa<ObjCCategoryImplDecl>(Container)))
3840     return;
3841 
3842   // Ignore any properties that have already been implemented.
3843   for (DeclContext::decl_iterator D = Container->decls_begin(),
3844                                DEnd = Container->decls_end();
3845        D != DEnd; ++D)
3846     if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3847       Results.Ignore(PropertyImpl->getPropertyDecl());
3848 
3849   // Add any properties that we find.
3850   Results.EnterNewScope();
3851   if (ObjCImplementationDecl *ClassImpl
3852         = dyn_cast<ObjCImplementationDecl>(Container))
3853     AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3854                       Results);
3855   else
3856     AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3857                       false, CurContext, Results);
3858   Results.ExitScope();
3859 
3860   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3861 }
3862 
3863 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3864                                                   IdentifierInfo *PropertyName,
3865                                                   DeclPtrTy ObjCImpDecl) {
3866   typedef CodeCompleteConsumer::Result Result;
3867   ResultBuilder Results(*this);
3868 
3869   // Figure out where this @synthesize lives.
3870   ObjCContainerDecl *Container
3871     = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3872   if (!Container ||
3873       (!isa<ObjCImplementationDecl>(Container) &&
3874        !isa<ObjCCategoryImplDecl>(Container)))
3875     return;
3876 
3877   // Figure out which interface we're looking into.
3878   ObjCInterfaceDecl *Class = 0;
3879   if (ObjCImplementationDecl *ClassImpl
3880                                  = dyn_cast<ObjCImplementationDecl>(Container))
3881     Class = ClassImpl->getClassInterface();
3882   else
3883     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3884                                                           ->getClassInterface();
3885 
3886   // Add all of the instance variables in this class and its superclasses.
3887   Results.EnterNewScope();
3888   for(; Class; Class = Class->getSuperClass()) {
3889     // FIXME: We could screen the type of each ivar for compatibility with
3890     // the property, but is that being too paternal?
3891     for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3892                                        IVarEnd = Class->ivar_end();
3893          IVar != IVarEnd; ++IVar)
3894       Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
3895   }
3896   Results.ExitScope();
3897 
3898   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3899 }
3900 
3901 typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
3902 
3903 /// \brief Find all of the methods that reside in the given container
3904 /// (and its superclasses, protocols, etc.) that meet the given
3905 /// criteria. Insert those methods into the map of known methods,
3906 /// indexed by selector so they can be easily found.
3907 static void FindImplementableMethods(ASTContext &Context,
3908                                      ObjCContainerDecl *Container,
3909                                      bool WantInstanceMethods,
3910                                      QualType ReturnType,
3911                                      bool IsInImplementation,
3912                                      KnownMethodsMap &KnownMethods) {
3913   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
3914     // Recurse into protocols.
3915     const ObjCList<ObjCProtocolDecl> &Protocols
3916       = IFace->getReferencedProtocols();
3917     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3918            E = Protocols.end();
3919          I != E; ++I)
3920       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3921                                IsInImplementation, KnownMethods);
3922 
3923     // If we're not in the implementation of a class, also visit the
3924     // superclass.
3925     if (!IsInImplementation && IFace->getSuperClass())
3926       FindImplementableMethods(Context, IFace->getSuperClass(),
3927                                WantInstanceMethods, ReturnType,
3928                                IsInImplementation, KnownMethods);
3929 
3930     // Add methods from any class extensions (but not from categories;
3931     // those should go into category implementations).
3932     for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
3933          Cat = Cat->getNextClassExtension())
3934       FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
3935                                WantInstanceMethods, ReturnType,
3936                                IsInImplementation, KnownMethods);
3937   }
3938 
3939   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
3940     // Recurse into protocols.
3941     const ObjCList<ObjCProtocolDecl> &Protocols
3942       = Category->getReferencedProtocols();
3943     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3944            E = Protocols.end();
3945          I != E; ++I)
3946       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3947                                IsInImplementation, KnownMethods);
3948   }
3949 
3950   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3951     // Recurse into protocols.
3952     const ObjCList<ObjCProtocolDecl> &Protocols
3953       = Protocol->getReferencedProtocols();
3954     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3955            E = Protocols.end();
3956          I != E; ++I)
3957       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3958                                IsInImplementation, KnownMethods);
3959   }
3960 
3961   // Add methods in this container. This operation occurs last because
3962   // we want the methods from this container to override any methods
3963   // we've previously seen with the same selector.
3964   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3965                                        MEnd = Container->meth_end();
3966        M != MEnd; ++M) {
3967     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3968       if (!ReturnType.isNull() &&
3969           !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
3970         continue;
3971 
3972       KnownMethods[(*M)->getSelector()] = *M;
3973     }
3974   }
3975 }
3976 
3977 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
3978                                       bool IsInstanceMethod,
3979                                       TypeTy *ReturnTy,
3980                                       DeclPtrTy IDecl) {
3981   // Determine the return type of the method we're declaring, if
3982   // provided.
3983   QualType ReturnType = GetTypeFromParser(ReturnTy);
3984 
3985   // Determine where we should start searching for methods, and where we
3986   ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
3987   bool IsInImplementation = false;
3988   if (Decl *D = IDecl.getAs<Decl>()) {
3989     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
3990       SearchDecl = Impl->getClassInterface();
3991       CurrentDecl = Impl;
3992       IsInImplementation = true;
3993     } else if (ObjCCategoryImplDecl *CatImpl
3994                                        = dyn_cast<ObjCCategoryImplDecl>(D)) {
3995       SearchDecl = CatImpl->getCategoryDecl();
3996       CurrentDecl = CatImpl;
3997       IsInImplementation = true;
3998     } else {
3999       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4000       CurrentDecl = SearchDecl;
4001     }
4002   }
4003 
4004   if (!SearchDecl && S) {
4005     if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4006       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4007       CurrentDecl = SearchDecl;
4008     }
4009   }
4010 
4011   if (!SearchDecl || !CurrentDecl) {
4012     HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
4013     return;
4014   }
4015 
4016   // Find all of the methods that we could declare/implement here.
4017   KnownMethodsMap KnownMethods;
4018   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4019                            ReturnType, IsInImplementation, KnownMethods);
4020 
4021   // Erase any methods that have already been declared or
4022   // implemented here.
4023   for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4024                                        MEnd = CurrentDecl->meth_end();
4025        M != MEnd; ++M) {
4026     if ((*M)->isInstanceMethod() != IsInstanceMethod)
4027       continue;
4028 
4029     KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4030     if (Pos != KnownMethods.end())
4031       KnownMethods.erase(Pos);
4032   }
4033 
4034   // Add declarations or definitions for each of the known methods.
4035   typedef CodeCompleteConsumer::Result Result;
4036   ResultBuilder Results(*this);
4037   Results.EnterNewScope();
4038   PrintingPolicy Policy(Context.PrintingPolicy);
4039   Policy.AnonymousTagLocations = false;
4040   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4041                               MEnd = KnownMethods.end();
4042        M != MEnd; ++M) {
4043     ObjCMethodDecl *Method = M->second;
4044     CodeCompletionString *Pattern = new CodeCompletionString;
4045 
4046     // If the result type was not already provided, add it to the
4047     // pattern as (type).
4048     if (ReturnType.isNull()) {
4049       std::string TypeStr;
4050       Method->getResultType().getAsStringInternal(TypeStr, Policy);
4051       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4052       Pattern->AddTextChunk(TypeStr);
4053       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4054     }
4055 
4056     Selector Sel = Method->getSelector();
4057 
4058     // Add the first part of the selector to the pattern.
4059     Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4060 
4061     // Add parameters to the pattern.
4062     unsigned I = 0;
4063     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4064                                      PEnd = Method->param_end();
4065          P != PEnd; (void)++P, ++I) {
4066       // Add the part of the selector name.
4067       if (I == 0)
4068         Pattern->AddChunk(CodeCompletionString::CK_Colon);
4069       else if (I < Sel.getNumArgs()) {
4070         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4071         Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4072         Pattern->AddChunk(CodeCompletionString::CK_Colon);
4073       } else
4074         break;
4075 
4076       // Add the parameter type.
4077       std::string TypeStr;
4078       (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4079       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4080       Pattern->AddTextChunk(TypeStr);
4081       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4082 
4083       if (IdentifierInfo *Id = (*P)->getIdentifier())
4084         Pattern->AddTextChunk(Id->getName());
4085     }
4086 
4087     if (Method->isVariadic()) {
4088       if (Method->param_size() > 0)
4089         Pattern->AddChunk(CodeCompletionString::CK_Comma);
4090       Pattern->AddTextChunk("...");
4091     }
4092 
4093     if (IsInImplementation && Results.includeCodePatterns()) {
4094       // We will be defining the method here, so add a compound statement.
4095       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4096       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4097       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4098       if (!Method->getResultType()->isVoidType()) {
4099         // If the result type is not void, add a return clause.
4100         Pattern->AddTextChunk("return");
4101         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4102         Pattern->AddPlaceholderChunk("expression");
4103         Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4104       } else
4105         Pattern->AddPlaceholderChunk("statements");
4106 
4107       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4108       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4109     }
4110 
4111     Results.AddResult(Result(Pattern));
4112   }
4113 
4114   Results.ExitScope();
4115 
4116   HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4117 }
4118