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