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 "clang/Sema/SemaInternal.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/CodeCompleteConsumer.h"
22 #include "clang/Sema/ExternalSemaSource.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Overload.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include "llvm/ADT/Twine.h"
34 #include <list>
35 #include <map>
36 #include <vector>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 namespace {
42   /// \brief A container of code-completion results.
43   class ResultBuilder {
44   public:
45     /// \brief The type of a name-lookup filter, which can be provided to the
46     /// name-lookup routines to specify which declarations should be included in
47     /// the result set (when it returns true) and which declarations should be
48     /// filtered out (returns false).
49     typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
50 
51     typedef CodeCompletionResult Result;
52 
53   private:
54     /// \brief The actual results we have found.
55     std::vector<Result> Results;
56 
57     /// \brief A record of all of the declarations we have found and placed
58     /// into the result set, used to ensure that no declaration ever gets into
59     /// the result set twice.
60     llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
61 
62     typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
63 
64     /// \brief An entry in the shadow map, which is optimized to store
65     /// a single (declaration, index) mapping (the common case) but
66     /// can also store a list of (declaration, index) mappings.
67     class ShadowMapEntry {
68       typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
69 
70       /// \brief Contains either the solitary NamedDecl * or a vector
71       /// of (declaration, index) pairs.
72       llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
73 
74       /// \brief When the entry contains a single declaration, this is
75       /// the index associated with that entry.
76       unsigned SingleDeclIndex;
77 
78     public:
79       ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80 
81       void Add(const NamedDecl *ND, unsigned Index) {
82         if (DeclOrVector.isNull()) {
83           // 0 - > 1 elements: just set the single element information.
84           DeclOrVector = ND;
85           SingleDeclIndex = Index;
86           return;
87         }
88 
89         if (const NamedDecl *PrevND =
90                 DeclOrVector.dyn_cast<const NamedDecl *>()) {
91           // 1 -> 2 elements: create the vector of results and push in the
92           // existing declaration.
93           DeclIndexPairVector *Vec = new DeclIndexPairVector;
94           Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
95           DeclOrVector = Vec;
96         }
97 
98         // Add the new element to the end of the vector.
99         DeclOrVector.get<DeclIndexPairVector*>()->push_back(
100                                                     DeclIndexPair(ND, Index));
101       }
102 
103       void Destroy() {
104         if (DeclIndexPairVector *Vec
105               = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
106           delete Vec;
107           DeclOrVector = ((NamedDecl *)0);
108         }
109       }
110 
111       // Iteration.
112       class iterator;
113       iterator begin() const;
114       iterator end() const;
115     };
116 
117     /// \brief A mapping from declaration names to the declarations that have
118     /// this name within a particular scope and their index within the list of
119     /// results.
120     typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
121 
122     /// \brief The semantic analysis object for which results are being
123     /// produced.
124     Sema &SemaRef;
125 
126     /// \brief The allocator used to allocate new code-completion strings.
127     CodeCompletionAllocator &Allocator;
128 
129     CodeCompletionTUInfo &CCTUInfo;
130 
131     /// \brief If non-NULL, a filter function used to remove any code-completion
132     /// results that are not desirable.
133     LookupFilter Filter;
134 
135     /// \brief Whether we should allow declarations as
136     /// nested-name-specifiers that would otherwise be filtered out.
137     bool AllowNestedNameSpecifiers;
138 
139     /// \brief If set, the type that we would prefer our resulting value
140     /// declarations to have.
141     ///
142     /// Closely matching the preferred type gives a boost to a result's
143     /// priority.
144     CanQualType PreferredType;
145 
146     /// \brief A list of shadow maps, which is used to model name hiding at
147     /// different levels of, e.g., the inheritance hierarchy.
148     std::list<ShadowMap> ShadowMaps;
149 
150     /// \brief If we're potentially referring to a C++ member function, the set
151     /// of qualifiers applied to the object type.
152     Qualifiers ObjectTypeQualifiers;
153 
154     /// \brief Whether the \p ObjectTypeQualifiers field is active.
155     bool HasObjectTypeQualifiers;
156 
157     /// \brief The selector that we prefer.
158     Selector PreferredSelector;
159 
160     /// \brief The completion context in which we are gathering results.
161     CodeCompletionContext CompletionContext;
162 
163     /// \brief If we are in an instance method definition, the \@implementation
164     /// object.
165     ObjCImplementationDecl *ObjCImplementation;
166 
167     void AdjustResultPriorityForDecl(Result &R);
168 
169     void MaybeAddConstructorResults(Result R);
170 
171   public:
172     explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
173                            CodeCompletionTUInfo &CCTUInfo,
174                            const CodeCompletionContext &CompletionContext,
175                            LookupFilter Filter = 0)
176       : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
177         Filter(Filter),
178         AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
179         CompletionContext(CompletionContext),
180         ObjCImplementation(0)
181     {
182       // If this is an Objective-C instance method definition, dig out the
183       // corresponding implementation.
184       switch (CompletionContext.getKind()) {
185       case CodeCompletionContext::CCC_Expression:
186       case CodeCompletionContext::CCC_ObjCMessageReceiver:
187       case CodeCompletionContext::CCC_ParenthesizedExpression:
188       case CodeCompletionContext::CCC_Statement:
189       case CodeCompletionContext::CCC_Recovery:
190         if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
191           if (Method->isInstanceMethod())
192             if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
193               ObjCImplementation = Interface->getImplementation();
194         break;
195 
196       default:
197         break;
198       }
199     }
200 
201     /// \brief Determine the priority for a reference to the given declaration.
202     unsigned getBasePriority(const NamedDecl *D);
203 
204     /// \brief Whether we should include code patterns in the completion
205     /// results.
206     bool includeCodePatterns() const {
207       return SemaRef.CodeCompleter &&
208              SemaRef.CodeCompleter->includeCodePatterns();
209     }
210 
211     /// \brief Set the filter used for code-completion results.
212     void setFilter(LookupFilter Filter) {
213       this->Filter = Filter;
214     }
215 
216     Result *data() { return Results.empty()? 0 : &Results.front(); }
217     unsigned size() const { return Results.size(); }
218     bool empty() const { return Results.empty(); }
219 
220     /// \brief Specify the preferred type.
221     void setPreferredType(QualType T) {
222       PreferredType = SemaRef.Context.getCanonicalType(T);
223     }
224 
225     /// \brief Set the cv-qualifiers on the object type, for us in filtering
226     /// calls to member functions.
227     ///
228     /// When there are qualifiers in this set, they will be used to filter
229     /// out member functions that aren't available (because there will be a
230     /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231     /// match.
232     void setObjectTypeQualifiers(Qualifiers Quals) {
233       ObjectTypeQualifiers = Quals;
234       HasObjectTypeQualifiers = true;
235     }
236 
237     /// \brief Set the preferred selector.
238     ///
239     /// When an Objective-C method declaration result is added, and that
240     /// method's selector matches this preferred selector, we give that method
241     /// a slight priority boost.
242     void setPreferredSelector(Selector Sel) {
243       PreferredSelector = Sel;
244     }
245 
246     /// \brief Retrieve the code-completion context for which results are
247     /// being collected.
248     const CodeCompletionContext &getCompletionContext() const {
249       return CompletionContext;
250     }
251 
252     /// \brief Specify whether nested-name-specifiers are allowed.
253     void allowNestedNameSpecifiers(bool Allow = true) {
254       AllowNestedNameSpecifiers = Allow;
255     }
256 
257     /// \brief Return the semantic analysis object for which we are collecting
258     /// code completion results.
259     Sema &getSema() const { return SemaRef; }
260 
261     /// \brief Retrieve the allocator used to allocate code completion strings.
262     CodeCompletionAllocator &getAllocator() const { return Allocator; }
263 
264     CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
265 
266     /// \brief Determine whether the given declaration is at all interesting
267     /// as a code-completion result.
268     ///
269     /// \param ND the declaration that we are inspecting.
270     ///
271     /// \param AsNestedNameSpecifier will be set true if this declaration is
272     /// only interesting when it is a nested-name-specifier.
273     bool isInterestingDecl(const NamedDecl *ND,
274                            bool &AsNestedNameSpecifier) const;
275 
276     /// \brief Check whether the result is hidden by the Hiding declaration.
277     ///
278     /// \returns true if the result is hidden and cannot be found, false if
279     /// the hidden result could still be found. When false, \p R may be
280     /// modified to describe how the result can be found (e.g., via extra
281     /// qualification).
282     bool CheckHiddenResult(Result &R, DeclContext *CurContext,
283                            const NamedDecl *Hiding);
284 
285     /// \brief Add a new result to this result set (if it isn't already in one
286     /// of the shadow maps), or replace an existing result (for, e.g., a
287     /// redeclaration).
288     ///
289     /// \param R the result to add (if it is unique).
290     ///
291     /// \param CurContext the context in which this result will be named.
292     void MaybeAddResult(Result R, DeclContext *CurContext = 0);
293 
294     /// \brief Add a new result to this result set, where we already know
295     /// the hiding declation (if any).
296     ///
297     /// \param R the result to add (if it is unique).
298     ///
299     /// \param CurContext the context in which this result will be named.
300     ///
301     /// \param Hiding the declaration that hides the result.
302     ///
303     /// \param InBaseClass whether the result was found in a base
304     /// class of the searched context.
305     void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
306                    bool InBaseClass);
307 
308     /// \brief Add a new non-declaration result to this result set.
309     void AddResult(Result R);
310 
311     /// \brief Enter into a new scope.
312     void EnterNewScope();
313 
314     /// \brief Exit from the current scope.
315     void ExitScope();
316 
317     /// \brief Ignore this declaration, if it is seen again.
318     void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
319 
320     /// \name Name lookup predicates
321     ///
322     /// These predicates can be passed to the name lookup functions to filter the
323     /// results of name lookup. All of the predicates have the same type, so that
324     ///
325     //@{
326     bool IsOrdinaryName(const NamedDecl *ND) const;
327     bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
328     bool IsIntegralConstantValue(const NamedDecl *ND) const;
329     bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
330     bool IsNestedNameSpecifier(const NamedDecl *ND) const;
331     bool IsEnum(const NamedDecl *ND) const;
332     bool IsClassOrStruct(const NamedDecl *ND) const;
333     bool IsUnion(const NamedDecl *ND) const;
334     bool IsNamespace(const NamedDecl *ND) const;
335     bool IsNamespaceOrAlias(const NamedDecl *ND) const;
336     bool IsType(const NamedDecl *ND) const;
337     bool IsMember(const NamedDecl *ND) const;
338     bool IsObjCIvar(const NamedDecl *ND) const;
339     bool IsObjCMessageReceiver(const NamedDecl *ND) const;
340     bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
341     bool IsObjCCollection(const NamedDecl *ND) const;
342     bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
343     //@}
344   };
345 }
346 
347 class ResultBuilder::ShadowMapEntry::iterator {
348   llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
349   unsigned SingleDeclIndex;
350 
351 public:
352   typedef DeclIndexPair value_type;
353   typedef value_type reference;
354   typedef std::ptrdiff_t difference_type;
355   typedef std::input_iterator_tag iterator_category;
356 
357   class pointer {
358     DeclIndexPair Value;
359 
360   public:
361     pointer(const DeclIndexPair &Value) : Value(Value) { }
362 
363     const DeclIndexPair *operator->() const {
364       return &Value;
365     }
366   };
367 
368   iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
369 
370   iterator(const NamedDecl *SingleDecl, unsigned Index)
371     : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
372 
373   iterator(const DeclIndexPair *Iterator)
374     : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
375 
376   iterator &operator++() {
377     if (DeclOrIterator.is<const NamedDecl *>()) {
378       DeclOrIterator = (NamedDecl *)0;
379       SingleDeclIndex = 0;
380       return *this;
381     }
382 
383     const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
384     ++I;
385     DeclOrIterator = I;
386     return *this;
387   }
388 
389   /*iterator operator++(int) {
390     iterator tmp(*this);
391     ++(*this);
392     return tmp;
393   }*/
394 
395   reference operator*() const {
396     if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
397       return reference(ND, SingleDeclIndex);
398 
399     return *DeclOrIterator.get<const DeclIndexPair*>();
400   }
401 
402   pointer operator->() const {
403     return pointer(**this);
404   }
405 
406   friend bool operator==(const iterator &X, const iterator &Y) {
407     return X.DeclOrIterator.getOpaqueValue()
408                                   == Y.DeclOrIterator.getOpaqueValue() &&
409       X.SingleDeclIndex == Y.SingleDeclIndex;
410   }
411 
412   friend bool operator!=(const iterator &X, const iterator &Y) {
413     return !(X == Y);
414   }
415 };
416 
417 ResultBuilder::ShadowMapEntry::iterator
418 ResultBuilder::ShadowMapEntry::begin() const {
419   if (DeclOrVector.isNull())
420     return iterator();
421 
422   if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
423     return iterator(ND, SingleDeclIndex);
424 
425   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
426 }
427 
428 ResultBuilder::ShadowMapEntry::iterator
429 ResultBuilder::ShadowMapEntry::end() const {
430   if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
431     return iterator();
432 
433   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
434 }
435 
436 /// \brief Compute the qualification required to get from the current context
437 /// (\p CurContext) to the target context (\p TargetContext).
438 ///
439 /// \param Context the AST context in which the qualification will be used.
440 ///
441 /// \param CurContext the context where an entity is being named, which is
442 /// typically based on the current scope.
443 ///
444 /// \param TargetContext the context in which the named entity actually
445 /// resides.
446 ///
447 /// \returns a nested name specifier that refers into the target context, or
448 /// NULL if no qualification is needed.
449 static NestedNameSpecifier *
450 getRequiredQualification(ASTContext &Context,
451                          const DeclContext *CurContext,
452                          const DeclContext *TargetContext) {
453   SmallVector<const DeclContext *, 4> TargetParents;
454 
455   for (const DeclContext *CommonAncestor = TargetContext;
456        CommonAncestor && !CommonAncestor->Encloses(CurContext);
457        CommonAncestor = CommonAncestor->getLookupParent()) {
458     if (CommonAncestor->isTransparentContext() ||
459         CommonAncestor->isFunctionOrMethod())
460       continue;
461 
462     TargetParents.push_back(CommonAncestor);
463   }
464 
465   NestedNameSpecifier *Result = 0;
466   while (!TargetParents.empty()) {
467     const DeclContext *Parent = TargetParents.pop_back_val();
468 
469     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
470       if (!Namespace->getIdentifier())
471         continue;
472 
473       Result = NestedNameSpecifier::Create(Context, Result, Namespace);
474     }
475     else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
476       Result = NestedNameSpecifier::Create(Context, Result,
477                                            false,
478                                      Context.getTypeDeclType(TD).getTypePtr());
479   }
480   return Result;
481 }
482 
483 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
484                                       bool &AsNestedNameSpecifier) const {
485   AsNestedNameSpecifier = false;
486 
487   ND = ND->getUnderlyingDecl();
488   unsigned IDNS = ND->getIdentifierNamespace();
489 
490   // Skip unnamed entities.
491   if (!ND->getDeclName())
492     return false;
493 
494   // Friend declarations and declarations introduced due to friends are never
495   // added as results.
496   if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
497     return false;
498 
499   // Class template (partial) specializations are never added as results.
500   if (isa<ClassTemplateSpecializationDecl>(ND) ||
501       isa<ClassTemplatePartialSpecializationDecl>(ND))
502     return false;
503 
504   // Using declarations themselves are never added as results.
505   if (isa<UsingDecl>(ND))
506     return false;
507 
508   // Some declarations have reserved names that we don't want to ever show.
509   if (const IdentifierInfo *Id = ND->getIdentifier()) {
510     // __va_list_tag is a freak of nature. Find it and skip it.
511     if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
512       return false;
513 
514     // Filter out names reserved for the implementation (C99 7.1.3,
515     // C++ [lib.global.names]) if they come from a system header.
516     //
517     // FIXME: Add predicate for this.
518     if (Id->getLength() >= 2) {
519       const char *Name = Id->getNameStart();
520       if (Name[0] == '_' &&
521           (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
522           (ND->getLocation().isInvalid() ||
523            SemaRef.SourceMgr.isInSystemHeader(
524                           SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
525         return false;
526     }
527   }
528 
529   if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
530       ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
531        Filter != &ResultBuilder::IsNamespace &&
532        Filter != &ResultBuilder::IsNamespaceOrAlias &&
533        Filter != 0))
534     AsNestedNameSpecifier = true;
535 
536   // Filter out any unwanted results.
537   if (Filter && !(this->*Filter)(ND)) {
538     // Check whether it is interesting as a nested-name-specifier.
539     if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
540         IsNestedNameSpecifier(ND) &&
541         (Filter != &ResultBuilder::IsMember ||
542          (isa<CXXRecordDecl>(ND) &&
543           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
544       AsNestedNameSpecifier = true;
545       return true;
546     }
547 
548     return false;
549   }
550   // ... then it must be interesting!
551   return true;
552 }
553 
554 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
555                                       const NamedDecl *Hiding) {
556   // In C, there is no way to refer to a hidden name.
557   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
558   // name if we introduce the tag type.
559   if (!SemaRef.getLangOpts().CPlusPlus)
560     return true;
561 
562   const DeclContext *HiddenCtx =
563       R.Declaration->getDeclContext()->getRedeclContext();
564 
565   // There is no way to qualify a name declared in a function or method.
566   if (HiddenCtx->isFunctionOrMethod())
567     return true;
568 
569   if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
570     return true;
571 
572   // We can refer to the result with the appropriate qualification. Do it.
573   R.Hidden = true;
574   R.QualifierIsInformative = false;
575 
576   if (!R.Qualifier)
577     R.Qualifier = getRequiredQualification(SemaRef.Context,
578                                            CurContext,
579                                            R.Declaration->getDeclContext());
580   return false;
581 }
582 
583 /// \brief A simplified classification of types used to determine whether two
584 /// types are "similar enough" when adjusting priorities.
585 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
586   switch (T->getTypeClass()) {
587   case Type::Builtin:
588     switch (cast<BuiltinType>(T)->getKind()) {
589       case BuiltinType::Void:
590         return STC_Void;
591 
592       case BuiltinType::NullPtr:
593         return STC_Pointer;
594 
595       case BuiltinType::Overload:
596       case BuiltinType::Dependent:
597         return STC_Other;
598 
599       case BuiltinType::ObjCId:
600       case BuiltinType::ObjCClass:
601       case BuiltinType::ObjCSel:
602         return STC_ObjectiveC;
603 
604       default:
605         return STC_Arithmetic;
606     }
607 
608   case Type::Complex:
609     return STC_Arithmetic;
610 
611   case Type::Pointer:
612     return STC_Pointer;
613 
614   case Type::BlockPointer:
615     return STC_Block;
616 
617   case Type::LValueReference:
618   case Type::RValueReference:
619     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
620 
621   case Type::ConstantArray:
622   case Type::IncompleteArray:
623   case Type::VariableArray:
624   case Type::DependentSizedArray:
625     return STC_Array;
626 
627   case Type::DependentSizedExtVector:
628   case Type::Vector:
629   case Type::ExtVector:
630     return STC_Arithmetic;
631 
632   case Type::FunctionProto:
633   case Type::FunctionNoProto:
634     return STC_Function;
635 
636   case Type::Record:
637     return STC_Record;
638 
639   case Type::Enum:
640     return STC_Arithmetic;
641 
642   case Type::ObjCObject:
643   case Type::ObjCInterface:
644   case Type::ObjCObjectPointer:
645     return STC_ObjectiveC;
646 
647   default:
648     return STC_Other;
649   }
650 }
651 
652 /// \brief Get the type that a given expression will have if this declaration
653 /// is used as an expression in its "typical" code-completion form.
654 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
655   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
656 
657   if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
658     return C.getTypeDeclType(Type);
659   if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
660     return C.getObjCInterfaceType(Iface);
661 
662   QualType T;
663   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
664     T = Function->getCallResultType();
665   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
666     T = Method->getSendResultType();
667   else if (const FunctionTemplateDecl *FunTmpl =
668                dyn_cast<FunctionTemplateDecl>(ND))
669     T = FunTmpl->getTemplatedDecl()->getCallResultType();
670   else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
671     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
672   else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
673     T = Property->getType();
674   else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
675     T = Value->getType();
676   else
677     return QualType();
678 
679   // Dig through references, function pointers, and block pointers to
680   // get down to the likely type of an expression when the entity is
681   // used.
682   do {
683     if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
684       T = Ref->getPointeeType();
685       continue;
686     }
687 
688     if (const PointerType *Pointer = T->getAs<PointerType>()) {
689       if (Pointer->getPointeeType()->isFunctionType()) {
690         T = Pointer->getPointeeType();
691         continue;
692       }
693 
694       break;
695     }
696 
697     if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
698       T = Block->getPointeeType();
699       continue;
700     }
701 
702     if (const FunctionType *Function = T->getAs<FunctionType>()) {
703       T = Function->getResultType();
704       continue;
705     }
706 
707     break;
708   } while (true);
709 
710   return T;
711 }
712 
713 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
714   if (!ND)
715     return CCP_Unlikely;
716 
717   // Context-based decisions.
718   const DeclContext *LexicalDC = ND->getLexicalDeclContext();
719   if (LexicalDC->isFunctionOrMethod()) {
720     // _cmd is relatively rare
721     if (const ImplicitParamDecl *ImplicitParam =
722         dyn_cast<ImplicitParamDecl>(ND))
723       if (ImplicitParam->getIdentifier() &&
724           ImplicitParam->getIdentifier()->isStr("_cmd"))
725         return CCP_ObjC_cmd;
726 
727     return CCP_LocalDeclaration;
728   }
729 
730   const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
731   if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
732     return CCP_MemberDeclaration;
733 
734   // Content-based decisions.
735   if (isa<EnumConstantDecl>(ND))
736     return CCP_Constant;
737 
738   // Use CCP_Type for type declarations unless we're in a statement, Objective-C
739   // message receiver, or parenthesized expression context. There, it's as
740   // likely that the user will want to write a type as other declarations.
741   if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
742       !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
743         CompletionContext.getKind()
744           == CodeCompletionContext::CCC_ObjCMessageReceiver ||
745         CompletionContext.getKind()
746           == CodeCompletionContext::CCC_ParenthesizedExpression))
747     return CCP_Type;
748 
749   return CCP_Declaration;
750 }
751 
752 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
753   // If this is an Objective-C method declaration whose selector matches our
754   // preferred selector, give it a priority boost.
755   if (!PreferredSelector.isNull())
756     if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
757       if (PreferredSelector == Method->getSelector())
758         R.Priority += CCD_SelectorMatch;
759 
760   // If we have a preferred type, adjust the priority for results with exactly-
761   // matching or nearly-matching types.
762   if (!PreferredType.isNull()) {
763     QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
764     if (!T.isNull()) {
765       CanQualType TC = SemaRef.Context.getCanonicalType(T);
766       // Check for exactly-matching types (modulo qualifiers).
767       if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
768         R.Priority /= CCF_ExactTypeMatch;
769       // Check for nearly-matching types, based on classification of each.
770       else if ((getSimplifiedTypeClass(PreferredType)
771                                                == getSimplifiedTypeClass(TC)) &&
772                !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
773         R.Priority /= CCF_SimilarTypeMatch;
774     }
775   }
776 }
777 
778 void ResultBuilder::MaybeAddConstructorResults(Result R) {
779   if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
780       !CompletionContext.wantConstructorResults())
781     return;
782 
783   ASTContext &Context = SemaRef.Context;
784   const NamedDecl *D = R.Declaration;
785   const CXXRecordDecl *Record = 0;
786   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
787     Record = ClassTemplate->getTemplatedDecl();
788   else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
789     // Skip specializations and partial specializations.
790     if (isa<ClassTemplateSpecializationDecl>(Record))
791       return;
792   } else {
793     // There are no constructors here.
794     return;
795   }
796 
797   Record = Record->getDefinition();
798   if (!Record)
799     return;
800 
801 
802   QualType RecordTy = Context.getTypeDeclType(Record);
803   DeclarationName ConstructorName
804     = Context.DeclarationNames.getCXXConstructorName(
805                                            Context.getCanonicalType(RecordTy));
806   DeclContext::lookup_const_result Ctors = Record->lookup(ConstructorName);
807   for (DeclContext::lookup_const_iterator I = Ctors.begin(),
808                                           E = Ctors.end();
809        I != E; ++I) {
810     R.Declaration = *I;
811     R.CursorKind = getCursorKindForDecl(R.Declaration);
812     Results.push_back(R);
813   }
814 }
815 
816 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
817   assert(!ShadowMaps.empty() && "Must enter into a results scope");
818 
819   if (R.Kind != Result::RK_Declaration) {
820     // For non-declaration results, just add the result.
821     Results.push_back(R);
822     return;
823   }
824 
825   // Look through using declarations.
826   if (const UsingShadowDecl *Using =
827           dyn_cast<UsingShadowDecl>(R.Declaration)) {
828     MaybeAddResult(Result(Using->getTargetDecl(),
829                           getBasePriority(Using->getTargetDecl()),
830                           R.Qualifier),
831                    CurContext);
832     return;
833   }
834 
835   const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
836   unsigned IDNS = CanonDecl->getIdentifierNamespace();
837 
838   bool AsNestedNameSpecifier = false;
839   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
840     return;
841 
842   // C++ constructors are never found by name lookup.
843   if (isa<CXXConstructorDecl>(R.Declaration))
844     return;
845 
846   ShadowMap &SMap = ShadowMaps.back();
847   ShadowMapEntry::iterator I, IEnd;
848   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
849   if (NamePos != SMap.end()) {
850     I = NamePos->second.begin();
851     IEnd = NamePos->second.end();
852   }
853 
854   for (; I != IEnd; ++I) {
855     const NamedDecl *ND = I->first;
856     unsigned Index = I->second;
857     if (ND->getCanonicalDecl() == CanonDecl) {
858       // This is a redeclaration. Always pick the newer declaration.
859       Results[Index].Declaration = R.Declaration;
860 
861       // We're done.
862       return;
863     }
864   }
865 
866   // This is a new declaration in this scope. However, check whether this
867   // declaration name is hidden by a similarly-named declaration in an outer
868   // scope.
869   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
870   --SMEnd;
871   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
872     ShadowMapEntry::iterator I, IEnd;
873     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
874     if (NamePos != SM->end()) {
875       I = NamePos->second.begin();
876       IEnd = NamePos->second.end();
877     }
878     for (; I != IEnd; ++I) {
879       // A tag declaration does not hide a non-tag declaration.
880       if (I->first->hasTagIdentifierNamespace() &&
881           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
882                    Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
883         continue;
884 
885       // Protocols are in distinct namespaces from everything else.
886       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
887            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
888           I->first->getIdentifierNamespace() != IDNS)
889         continue;
890 
891       // The newly-added result is hidden by an entry in the shadow map.
892       if (CheckHiddenResult(R, CurContext, I->first))
893         return;
894 
895       break;
896     }
897   }
898 
899   // Make sure that any given declaration only shows up in the result set once.
900   if (!AllDeclsFound.insert(CanonDecl))
901     return;
902 
903   // If the filter is for nested-name-specifiers, then this result starts a
904   // nested-name-specifier.
905   if (AsNestedNameSpecifier) {
906     R.StartsNestedNameSpecifier = true;
907     R.Priority = CCP_NestedNameSpecifier;
908   } else
909       AdjustResultPriorityForDecl(R);
910 
911   // If this result is supposed to have an informative qualifier, add one.
912   if (R.QualifierIsInformative && !R.Qualifier &&
913       !R.StartsNestedNameSpecifier) {
914     const DeclContext *Ctx = R.Declaration->getDeclContext();
915     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
916       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
917     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
918       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
919                              SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
920     else
921       R.QualifierIsInformative = false;
922   }
923 
924   // Insert this result into the set of results and into the current shadow
925   // map.
926   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
927   Results.push_back(R);
928 
929   if (!AsNestedNameSpecifier)
930     MaybeAddConstructorResults(R);
931 }
932 
933 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
934                               NamedDecl *Hiding, bool InBaseClass = false) {
935   if (R.Kind != Result::RK_Declaration) {
936     // For non-declaration results, just add the result.
937     Results.push_back(R);
938     return;
939   }
940 
941   // Look through using declarations.
942   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
943     AddResult(Result(Using->getTargetDecl(),
944                      getBasePriority(Using->getTargetDecl()),
945                      R.Qualifier),
946               CurContext, Hiding);
947     return;
948   }
949 
950   bool AsNestedNameSpecifier = false;
951   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
952     return;
953 
954   // C++ constructors are never found by name lookup.
955   if (isa<CXXConstructorDecl>(R.Declaration))
956     return;
957 
958   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
959     return;
960 
961   // Make sure that any given declaration only shows up in the result set once.
962   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
963     return;
964 
965   // If the filter is for nested-name-specifiers, then this result starts a
966   // nested-name-specifier.
967   if (AsNestedNameSpecifier) {
968     R.StartsNestedNameSpecifier = true;
969     R.Priority = CCP_NestedNameSpecifier;
970   }
971   else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
972            isa<CXXRecordDecl>(R.Declaration->getDeclContext()
973                                                   ->getRedeclContext()))
974     R.QualifierIsInformative = true;
975 
976   // If this result is supposed to have an informative qualifier, add one.
977   if (R.QualifierIsInformative && !R.Qualifier &&
978       !R.StartsNestedNameSpecifier) {
979     const DeclContext *Ctx = R.Declaration->getDeclContext();
980     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
981       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
982     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
983       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
984                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
985     else
986       R.QualifierIsInformative = false;
987   }
988 
989   // Adjust the priority if this result comes from a base class.
990   if (InBaseClass)
991     R.Priority += CCD_InBaseClass;
992 
993   AdjustResultPriorityForDecl(R);
994 
995   if (HasObjectTypeQualifiers)
996     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
997       if (Method->isInstance()) {
998         Qualifiers MethodQuals
999                         = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1000         if (ObjectTypeQualifiers == MethodQuals)
1001           R.Priority += CCD_ObjectQualifierMatch;
1002         else if (ObjectTypeQualifiers - MethodQuals) {
1003           // The method cannot be invoked, because doing so would drop
1004           // qualifiers.
1005           return;
1006         }
1007       }
1008 
1009   // Insert this result into the set of results.
1010   Results.push_back(R);
1011 
1012   if (!AsNestedNameSpecifier)
1013     MaybeAddConstructorResults(R);
1014 }
1015 
1016 void ResultBuilder::AddResult(Result R) {
1017   assert(R.Kind != Result::RK_Declaration &&
1018           "Declaration results need more context");
1019   Results.push_back(R);
1020 }
1021 
1022 /// \brief Enter into a new scope.
1023 void ResultBuilder::EnterNewScope() {
1024   ShadowMaps.push_back(ShadowMap());
1025 }
1026 
1027 /// \brief Exit from the current scope.
1028 void ResultBuilder::ExitScope() {
1029   for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1030                         EEnd = ShadowMaps.back().end();
1031        E != EEnd;
1032        ++E)
1033     E->second.Destroy();
1034 
1035   ShadowMaps.pop_back();
1036 }
1037 
1038 /// \brief Determines whether this given declaration will be found by
1039 /// ordinary name lookup.
1040 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1041   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1042 
1043   // If name lookup finds a local extern declaration, then we are in a
1044   // context where it behaves like an ordinary name.
1045   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1046   if (SemaRef.getLangOpts().CPlusPlus)
1047     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1048   else if (SemaRef.getLangOpts().ObjC1) {
1049     if (isa<ObjCIvarDecl>(ND))
1050       return true;
1051   }
1052 
1053   return ND->getIdentifierNamespace() & IDNS;
1054 }
1055 
1056 /// \brief Determines whether this given declaration will be found by
1057 /// ordinary name lookup but is not a type name.
1058 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1059   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1060   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1061     return false;
1062 
1063   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1064   if (SemaRef.getLangOpts().CPlusPlus)
1065     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1066   else if (SemaRef.getLangOpts().ObjC1) {
1067     if (isa<ObjCIvarDecl>(ND))
1068       return true;
1069   }
1070 
1071   return ND->getIdentifierNamespace() & IDNS;
1072 }
1073 
1074 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1075   if (!IsOrdinaryNonTypeName(ND))
1076     return 0;
1077 
1078   if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1079     if (VD->getType()->isIntegralOrEnumerationType())
1080       return true;
1081 
1082   return false;
1083 }
1084 
1085 /// \brief Determines whether this given declaration will be found by
1086 /// ordinary name lookup.
1087 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1088   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1089 
1090   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1091   if (SemaRef.getLangOpts().CPlusPlus)
1092     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1093 
1094   return (ND->getIdentifierNamespace() & IDNS) &&
1095     !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1096     !isa<ObjCPropertyDecl>(ND);
1097 }
1098 
1099 /// \brief Determines whether the given declaration is suitable as the
1100 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1101 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1102   // Allow us to find class templates, too.
1103   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1104     ND = ClassTemplate->getTemplatedDecl();
1105 
1106   return SemaRef.isAcceptableNestedNameSpecifier(ND);
1107 }
1108 
1109 /// \brief Determines whether the given declaration is an enumeration.
1110 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1111   return isa<EnumDecl>(ND);
1112 }
1113 
1114 /// \brief Determines whether the given declaration is a class or struct.
1115 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1116   // Allow us to find class templates, too.
1117   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1118     ND = ClassTemplate->getTemplatedDecl();
1119 
1120   // For purposes of this check, interfaces match too.
1121   if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1122     return RD->getTagKind() == TTK_Class ||
1123     RD->getTagKind() == TTK_Struct ||
1124     RD->getTagKind() == TTK_Interface;
1125 
1126   return false;
1127 }
1128 
1129 /// \brief Determines whether the given declaration is a union.
1130 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1131   // Allow us to find class templates, too.
1132   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1133     ND = ClassTemplate->getTemplatedDecl();
1134 
1135   if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1136     return RD->getTagKind() == TTK_Union;
1137 
1138   return false;
1139 }
1140 
1141 /// \brief Determines whether the given declaration is a namespace.
1142 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1143   return isa<NamespaceDecl>(ND);
1144 }
1145 
1146 /// \brief Determines whether the given declaration is a namespace or
1147 /// namespace alias.
1148 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1149   return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1150 }
1151 
1152 /// \brief Determines whether the given declaration is a type.
1153 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1154   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1155     ND = Using->getTargetDecl();
1156 
1157   return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1158 }
1159 
1160 /// \brief Determines which members of a class should be visible via
1161 /// "." or "->".  Only value declarations, nested name specifiers, and
1162 /// using declarations thereof should show up.
1163 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1164   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1165     ND = Using->getTargetDecl();
1166 
1167   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1168     isa<ObjCPropertyDecl>(ND);
1169 }
1170 
1171 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1172   T = C.getCanonicalType(T);
1173   switch (T->getTypeClass()) {
1174   case Type::ObjCObject:
1175   case Type::ObjCInterface:
1176   case Type::ObjCObjectPointer:
1177     return true;
1178 
1179   case Type::Builtin:
1180     switch (cast<BuiltinType>(T)->getKind()) {
1181     case BuiltinType::ObjCId:
1182     case BuiltinType::ObjCClass:
1183     case BuiltinType::ObjCSel:
1184       return true;
1185 
1186     default:
1187       break;
1188     }
1189     return false;
1190 
1191   default:
1192     break;
1193   }
1194 
1195   if (!C.getLangOpts().CPlusPlus)
1196     return false;
1197 
1198   // FIXME: We could perform more analysis here to determine whether a
1199   // particular class type has any conversions to Objective-C types. For now,
1200   // just accept all class types.
1201   return T->isDependentType() || T->isRecordType();
1202 }
1203 
1204 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1205   QualType T = getDeclUsageType(SemaRef.Context, ND);
1206   if (T.isNull())
1207     return false;
1208 
1209   T = SemaRef.Context.getBaseElementType(T);
1210   return isObjCReceiverType(SemaRef.Context, T);
1211 }
1212 
1213 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1214   if (IsObjCMessageReceiver(ND))
1215     return true;
1216 
1217   const VarDecl *Var = dyn_cast<VarDecl>(ND);
1218   if (!Var)
1219     return false;
1220 
1221   return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1222 }
1223 
1224 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1225   if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1226       (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1227     return false;
1228 
1229   QualType T = getDeclUsageType(SemaRef.Context, ND);
1230   if (T.isNull())
1231     return false;
1232 
1233   T = SemaRef.Context.getBaseElementType(T);
1234   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1235          T->isObjCIdType() ||
1236          (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1237 }
1238 
1239 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1240   return false;
1241 }
1242 
1243 /// \brief Determines whether the given declaration is an Objective-C
1244 /// instance variable.
1245 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1246   return isa<ObjCIvarDecl>(ND);
1247 }
1248 
1249 namespace {
1250   /// \brief Visible declaration consumer that adds a code-completion result
1251   /// for each visible declaration.
1252   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1253     ResultBuilder &Results;
1254     DeclContext *CurContext;
1255 
1256   public:
1257     CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1258       : Results(Results), CurContext(CurContext) { }
1259 
1260     virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1261                            bool InBaseClass) {
1262       bool Accessible = true;
1263       if (Ctx)
1264         Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1265 
1266       ResultBuilder::Result Result(ND, Results.getBasePriority(ND), 0, false,
1267                                    Accessible);
1268       Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1269     }
1270   };
1271 }
1272 
1273 /// \brief Add type specifiers for the current language as keyword results.
1274 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1275                                     ResultBuilder &Results) {
1276   typedef CodeCompletionResult Result;
1277   Results.AddResult(Result("short", CCP_Type));
1278   Results.AddResult(Result("long", CCP_Type));
1279   Results.AddResult(Result("signed", CCP_Type));
1280   Results.AddResult(Result("unsigned", CCP_Type));
1281   Results.AddResult(Result("void", CCP_Type));
1282   Results.AddResult(Result("char", CCP_Type));
1283   Results.AddResult(Result("int", CCP_Type));
1284   Results.AddResult(Result("float", CCP_Type));
1285   Results.AddResult(Result("double", CCP_Type));
1286   Results.AddResult(Result("enum", CCP_Type));
1287   Results.AddResult(Result("struct", CCP_Type));
1288   Results.AddResult(Result("union", CCP_Type));
1289   Results.AddResult(Result("const", CCP_Type));
1290   Results.AddResult(Result("volatile", CCP_Type));
1291 
1292   if (LangOpts.C99) {
1293     // C99-specific
1294     Results.AddResult(Result("_Complex", CCP_Type));
1295     Results.AddResult(Result("_Imaginary", CCP_Type));
1296     Results.AddResult(Result("_Bool", CCP_Type));
1297     Results.AddResult(Result("restrict", CCP_Type));
1298   }
1299 
1300   CodeCompletionBuilder Builder(Results.getAllocator(),
1301                                 Results.getCodeCompletionTUInfo());
1302   if (LangOpts.CPlusPlus) {
1303     // C++-specific
1304     Results.AddResult(Result("bool", CCP_Type +
1305                              (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1306     Results.AddResult(Result("class", CCP_Type));
1307     Results.AddResult(Result("wchar_t", CCP_Type));
1308 
1309     // typename qualified-id
1310     Builder.AddTypedTextChunk("typename");
1311     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1312     Builder.AddPlaceholderChunk("qualifier");
1313     Builder.AddTextChunk("::");
1314     Builder.AddPlaceholderChunk("name");
1315     Results.AddResult(Result(Builder.TakeString()));
1316 
1317     if (LangOpts.CPlusPlus11) {
1318       Results.AddResult(Result("auto", CCP_Type));
1319       Results.AddResult(Result("char16_t", CCP_Type));
1320       Results.AddResult(Result("char32_t", CCP_Type));
1321 
1322       Builder.AddTypedTextChunk("decltype");
1323       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1324       Builder.AddPlaceholderChunk("expression");
1325       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1326       Results.AddResult(Result(Builder.TakeString()));
1327     }
1328   }
1329 
1330   // GNU extensions
1331   if (LangOpts.GNUMode) {
1332     // FIXME: Enable when we actually support decimal floating point.
1333     //    Results.AddResult(Result("_Decimal32"));
1334     //    Results.AddResult(Result("_Decimal64"));
1335     //    Results.AddResult(Result("_Decimal128"));
1336 
1337     Builder.AddTypedTextChunk("typeof");
1338     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1339     Builder.AddPlaceholderChunk("expression");
1340     Results.AddResult(Result(Builder.TakeString()));
1341 
1342     Builder.AddTypedTextChunk("typeof");
1343     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1344     Builder.AddPlaceholderChunk("type");
1345     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1346     Results.AddResult(Result(Builder.TakeString()));
1347   }
1348 }
1349 
1350 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1351                                  const LangOptions &LangOpts,
1352                                  ResultBuilder &Results) {
1353   typedef CodeCompletionResult Result;
1354   // Note: we don't suggest either "auto" or "register", because both
1355   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1356   // in C++0x as a type specifier.
1357   Results.AddResult(Result("extern"));
1358   Results.AddResult(Result("static"));
1359 }
1360 
1361 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1362                                   const LangOptions &LangOpts,
1363                                   ResultBuilder &Results) {
1364   typedef CodeCompletionResult Result;
1365   switch (CCC) {
1366   case Sema::PCC_Class:
1367   case Sema::PCC_MemberTemplate:
1368     if (LangOpts.CPlusPlus) {
1369       Results.AddResult(Result("explicit"));
1370       Results.AddResult(Result("friend"));
1371       Results.AddResult(Result("mutable"));
1372       Results.AddResult(Result("virtual"));
1373     }
1374     // Fall through
1375 
1376   case Sema::PCC_ObjCInterface:
1377   case Sema::PCC_ObjCImplementation:
1378   case Sema::PCC_Namespace:
1379   case Sema::PCC_Template:
1380     if (LangOpts.CPlusPlus || LangOpts.C99)
1381       Results.AddResult(Result("inline"));
1382     break;
1383 
1384   case Sema::PCC_ObjCInstanceVariableList:
1385   case Sema::PCC_Expression:
1386   case Sema::PCC_Statement:
1387   case Sema::PCC_ForInit:
1388   case Sema::PCC_Condition:
1389   case Sema::PCC_RecoveryInFunction:
1390   case Sema::PCC_Type:
1391   case Sema::PCC_ParenthesizedExpression:
1392   case Sema::PCC_LocalDeclarationSpecifiers:
1393     break;
1394   }
1395 }
1396 
1397 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1398 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1399 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1400                                      ResultBuilder &Results,
1401                                      bool NeedAt);
1402 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1403                                          ResultBuilder &Results,
1404                                          bool NeedAt);
1405 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1406                                     ResultBuilder &Results,
1407                                     bool NeedAt);
1408 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1409 
1410 static void AddTypedefResult(ResultBuilder &Results) {
1411   CodeCompletionBuilder Builder(Results.getAllocator(),
1412                                 Results.getCodeCompletionTUInfo());
1413   Builder.AddTypedTextChunk("typedef");
1414   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1415   Builder.AddPlaceholderChunk("type");
1416   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1417   Builder.AddPlaceholderChunk("name");
1418   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1419 }
1420 
1421 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1422                                const LangOptions &LangOpts) {
1423   switch (CCC) {
1424   case Sema::PCC_Namespace:
1425   case Sema::PCC_Class:
1426   case Sema::PCC_ObjCInstanceVariableList:
1427   case Sema::PCC_Template:
1428   case Sema::PCC_MemberTemplate:
1429   case Sema::PCC_Statement:
1430   case Sema::PCC_RecoveryInFunction:
1431   case Sema::PCC_Type:
1432   case Sema::PCC_ParenthesizedExpression:
1433   case Sema::PCC_LocalDeclarationSpecifiers:
1434     return true;
1435 
1436   case Sema::PCC_Expression:
1437   case Sema::PCC_Condition:
1438     return LangOpts.CPlusPlus;
1439 
1440   case Sema::PCC_ObjCInterface:
1441   case Sema::PCC_ObjCImplementation:
1442     return false;
1443 
1444   case Sema::PCC_ForInit:
1445     return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1446   }
1447 
1448   llvm_unreachable("Invalid ParserCompletionContext!");
1449 }
1450 
1451 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1452                                                   const Preprocessor &PP) {
1453   PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1454   Policy.AnonymousTagLocations = false;
1455   Policy.SuppressStrongLifetime = true;
1456   Policy.SuppressUnwrittenScope = true;
1457   return Policy;
1458 }
1459 
1460 /// \brief Retrieve a printing policy suitable for code completion.
1461 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1462   return getCompletionPrintingPolicy(S.Context, S.PP);
1463 }
1464 
1465 /// \brief Retrieve the string representation of the given type as a string
1466 /// that has the appropriate lifetime for code completion.
1467 ///
1468 /// This routine provides a fast path where we provide constant strings for
1469 /// common type names.
1470 static const char *GetCompletionTypeString(QualType T,
1471                                            ASTContext &Context,
1472                                            const PrintingPolicy &Policy,
1473                                            CodeCompletionAllocator &Allocator) {
1474   if (!T.getLocalQualifiers()) {
1475     // Built-in type names are constant strings.
1476     if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1477       return BT->getNameAsCString(Policy);
1478 
1479     // Anonymous tag types are constant strings.
1480     if (const TagType *TagT = dyn_cast<TagType>(T))
1481       if (TagDecl *Tag = TagT->getDecl())
1482         if (!Tag->hasNameForLinkage()) {
1483           switch (Tag->getTagKind()) {
1484           case TTK_Struct: return "struct <anonymous>";
1485           case TTK_Interface: return "__interface <anonymous>";
1486           case TTK_Class:  return "class <anonymous>";
1487           case TTK_Union:  return "union <anonymous>";
1488           case TTK_Enum:   return "enum <anonymous>";
1489           }
1490         }
1491   }
1492 
1493   // Slow path: format the type as a string.
1494   std::string Result;
1495   T.getAsStringInternal(Result, Policy);
1496   return Allocator.CopyString(Result);
1497 }
1498 
1499 /// \brief Add a completion for "this", if we're in a member function.
1500 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1501   QualType ThisTy = S.getCurrentThisType();
1502   if (ThisTy.isNull())
1503     return;
1504 
1505   CodeCompletionAllocator &Allocator = Results.getAllocator();
1506   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1507   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1508   Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1509                                                      S.Context,
1510                                                      Policy,
1511                                                      Allocator));
1512   Builder.AddTypedTextChunk("this");
1513   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1514 }
1515 
1516 /// \brief Add language constructs that show up for "ordinary" names.
1517 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1518                                    Scope *S,
1519                                    Sema &SemaRef,
1520                                    ResultBuilder &Results) {
1521   CodeCompletionAllocator &Allocator = Results.getAllocator();
1522   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1523   PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
1524 
1525   typedef CodeCompletionResult Result;
1526   switch (CCC) {
1527   case Sema::PCC_Namespace:
1528     if (SemaRef.getLangOpts().CPlusPlus) {
1529       if (Results.includeCodePatterns()) {
1530         // namespace <identifier> { declarations }
1531         Builder.AddTypedTextChunk("namespace");
1532         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1533         Builder.AddPlaceholderChunk("identifier");
1534         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1535         Builder.AddPlaceholderChunk("declarations");
1536         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1537         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1538         Results.AddResult(Result(Builder.TakeString()));
1539       }
1540 
1541       // namespace identifier = identifier ;
1542       Builder.AddTypedTextChunk("namespace");
1543       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1544       Builder.AddPlaceholderChunk("name");
1545       Builder.AddChunk(CodeCompletionString::CK_Equal);
1546       Builder.AddPlaceholderChunk("namespace");
1547       Results.AddResult(Result(Builder.TakeString()));
1548 
1549       // Using directives
1550       Builder.AddTypedTextChunk("using");
1551       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1552       Builder.AddTextChunk("namespace");
1553       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1554       Builder.AddPlaceholderChunk("identifier");
1555       Results.AddResult(Result(Builder.TakeString()));
1556 
1557       // asm(string-literal)
1558       Builder.AddTypedTextChunk("asm");
1559       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1560       Builder.AddPlaceholderChunk("string-literal");
1561       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1562       Results.AddResult(Result(Builder.TakeString()));
1563 
1564       if (Results.includeCodePatterns()) {
1565         // Explicit template instantiation
1566         Builder.AddTypedTextChunk("template");
1567         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1568         Builder.AddPlaceholderChunk("declaration");
1569         Results.AddResult(Result(Builder.TakeString()));
1570       }
1571     }
1572 
1573     if (SemaRef.getLangOpts().ObjC1)
1574       AddObjCTopLevelResults(Results, true);
1575 
1576     AddTypedefResult(Results);
1577     // Fall through
1578 
1579   case Sema::PCC_Class:
1580     if (SemaRef.getLangOpts().CPlusPlus) {
1581       // Using declaration
1582       Builder.AddTypedTextChunk("using");
1583       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1584       Builder.AddPlaceholderChunk("qualifier");
1585       Builder.AddTextChunk("::");
1586       Builder.AddPlaceholderChunk("name");
1587       Results.AddResult(Result(Builder.TakeString()));
1588 
1589       // using typename qualifier::name (only in a dependent context)
1590       if (SemaRef.CurContext->isDependentContext()) {
1591         Builder.AddTypedTextChunk("using");
1592         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1593         Builder.AddTextChunk("typename");
1594         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1595         Builder.AddPlaceholderChunk("qualifier");
1596         Builder.AddTextChunk("::");
1597         Builder.AddPlaceholderChunk("name");
1598         Results.AddResult(Result(Builder.TakeString()));
1599       }
1600 
1601       if (CCC == Sema::PCC_Class) {
1602         AddTypedefResult(Results);
1603 
1604         // public:
1605         Builder.AddTypedTextChunk("public");
1606         if (Results.includeCodePatterns())
1607           Builder.AddChunk(CodeCompletionString::CK_Colon);
1608         Results.AddResult(Result(Builder.TakeString()));
1609 
1610         // protected:
1611         Builder.AddTypedTextChunk("protected");
1612         if (Results.includeCodePatterns())
1613           Builder.AddChunk(CodeCompletionString::CK_Colon);
1614         Results.AddResult(Result(Builder.TakeString()));
1615 
1616         // private:
1617         Builder.AddTypedTextChunk("private");
1618         if (Results.includeCodePatterns())
1619           Builder.AddChunk(CodeCompletionString::CK_Colon);
1620         Results.AddResult(Result(Builder.TakeString()));
1621       }
1622     }
1623     // Fall through
1624 
1625   case Sema::PCC_Template:
1626   case Sema::PCC_MemberTemplate:
1627     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1628       // template < parameters >
1629       Builder.AddTypedTextChunk("template");
1630       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1631       Builder.AddPlaceholderChunk("parameters");
1632       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1633       Results.AddResult(Result(Builder.TakeString()));
1634     }
1635 
1636     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1637     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1638     break;
1639 
1640   case Sema::PCC_ObjCInterface:
1641     AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1642     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1643     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1644     break;
1645 
1646   case Sema::PCC_ObjCImplementation:
1647     AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1648     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1649     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1650     break;
1651 
1652   case Sema::PCC_ObjCInstanceVariableList:
1653     AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1654     break;
1655 
1656   case Sema::PCC_RecoveryInFunction:
1657   case Sema::PCC_Statement: {
1658     AddTypedefResult(Results);
1659 
1660     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1661         SemaRef.getLangOpts().CXXExceptions) {
1662       Builder.AddTypedTextChunk("try");
1663       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1664       Builder.AddPlaceholderChunk("statements");
1665       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1666       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1667       Builder.AddTextChunk("catch");
1668       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1669       Builder.AddPlaceholderChunk("declaration");
1670       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1671       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1672       Builder.AddPlaceholderChunk("statements");
1673       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1674       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1675       Results.AddResult(Result(Builder.TakeString()));
1676     }
1677     if (SemaRef.getLangOpts().ObjC1)
1678       AddObjCStatementResults(Results, true);
1679 
1680     if (Results.includeCodePatterns()) {
1681       // if (condition) { statements }
1682       Builder.AddTypedTextChunk("if");
1683       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1684       if (SemaRef.getLangOpts().CPlusPlus)
1685         Builder.AddPlaceholderChunk("condition");
1686       else
1687         Builder.AddPlaceholderChunk("expression");
1688       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1689       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1690       Builder.AddPlaceholderChunk("statements");
1691       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1692       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1693       Results.AddResult(Result(Builder.TakeString()));
1694 
1695       // switch (condition) { }
1696       Builder.AddTypedTextChunk("switch");
1697       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1698       if (SemaRef.getLangOpts().CPlusPlus)
1699         Builder.AddPlaceholderChunk("condition");
1700       else
1701         Builder.AddPlaceholderChunk("expression");
1702       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1703       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1704       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1705       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1706       Results.AddResult(Result(Builder.TakeString()));
1707     }
1708 
1709     // Switch-specific statements.
1710     if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1711       // case expression:
1712       Builder.AddTypedTextChunk("case");
1713       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1714       Builder.AddPlaceholderChunk("expression");
1715       Builder.AddChunk(CodeCompletionString::CK_Colon);
1716       Results.AddResult(Result(Builder.TakeString()));
1717 
1718       // default:
1719       Builder.AddTypedTextChunk("default");
1720       Builder.AddChunk(CodeCompletionString::CK_Colon);
1721       Results.AddResult(Result(Builder.TakeString()));
1722     }
1723 
1724     if (Results.includeCodePatterns()) {
1725       /// while (condition) { statements }
1726       Builder.AddTypedTextChunk("while");
1727       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1728       if (SemaRef.getLangOpts().CPlusPlus)
1729         Builder.AddPlaceholderChunk("condition");
1730       else
1731         Builder.AddPlaceholderChunk("expression");
1732       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1733       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1734       Builder.AddPlaceholderChunk("statements");
1735       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1736       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1737       Results.AddResult(Result(Builder.TakeString()));
1738 
1739       // do { statements } while ( expression );
1740       Builder.AddTypedTextChunk("do");
1741       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1742       Builder.AddPlaceholderChunk("statements");
1743       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1744       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1745       Builder.AddTextChunk("while");
1746       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1747       Builder.AddPlaceholderChunk("expression");
1748       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1749       Results.AddResult(Result(Builder.TakeString()));
1750 
1751       // for ( for-init-statement ; condition ; expression ) { statements }
1752       Builder.AddTypedTextChunk("for");
1753       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1754       if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1755         Builder.AddPlaceholderChunk("init-statement");
1756       else
1757         Builder.AddPlaceholderChunk("init-expression");
1758       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1759       Builder.AddPlaceholderChunk("condition");
1760       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1761       Builder.AddPlaceholderChunk("inc-expression");
1762       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1763       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1764       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1765       Builder.AddPlaceholderChunk("statements");
1766       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1767       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1768       Results.AddResult(Result(Builder.TakeString()));
1769     }
1770 
1771     if (S->getContinueParent()) {
1772       // continue ;
1773       Builder.AddTypedTextChunk("continue");
1774       Results.AddResult(Result(Builder.TakeString()));
1775     }
1776 
1777     if (S->getBreakParent()) {
1778       // break ;
1779       Builder.AddTypedTextChunk("break");
1780       Results.AddResult(Result(Builder.TakeString()));
1781     }
1782 
1783     // "return expression ;" or "return ;", depending on whether we
1784     // know the function is void or not.
1785     bool isVoid = false;
1786     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1787       isVoid = Function->getResultType()->isVoidType();
1788     else if (ObjCMethodDecl *Method
1789                                  = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1790       isVoid = Method->getResultType()->isVoidType();
1791     else if (SemaRef.getCurBlock() &&
1792              !SemaRef.getCurBlock()->ReturnType.isNull())
1793       isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1794     Builder.AddTypedTextChunk("return");
1795     if (!isVoid) {
1796       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1797       Builder.AddPlaceholderChunk("expression");
1798     }
1799     Results.AddResult(Result(Builder.TakeString()));
1800 
1801     // goto identifier ;
1802     Builder.AddTypedTextChunk("goto");
1803     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1804     Builder.AddPlaceholderChunk("label");
1805     Results.AddResult(Result(Builder.TakeString()));
1806 
1807     // Using directives
1808     Builder.AddTypedTextChunk("using");
1809     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1810     Builder.AddTextChunk("namespace");
1811     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1812     Builder.AddPlaceholderChunk("identifier");
1813     Results.AddResult(Result(Builder.TakeString()));
1814   }
1815 
1816   // Fall through (for statement expressions).
1817   case Sema::PCC_ForInit:
1818   case Sema::PCC_Condition:
1819     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1820     // Fall through: conditions and statements can have expressions.
1821 
1822   case Sema::PCC_ParenthesizedExpression:
1823     if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1824         CCC == Sema::PCC_ParenthesizedExpression) {
1825       // (__bridge <type>)<expression>
1826       Builder.AddTypedTextChunk("__bridge");
1827       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1828       Builder.AddPlaceholderChunk("type");
1829       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1830       Builder.AddPlaceholderChunk("expression");
1831       Results.AddResult(Result(Builder.TakeString()));
1832 
1833       // (__bridge_transfer <Objective-C type>)<expression>
1834       Builder.AddTypedTextChunk("__bridge_transfer");
1835       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1836       Builder.AddPlaceholderChunk("Objective-C type");
1837       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1838       Builder.AddPlaceholderChunk("expression");
1839       Results.AddResult(Result(Builder.TakeString()));
1840 
1841       // (__bridge_retained <CF type>)<expression>
1842       Builder.AddTypedTextChunk("__bridge_retained");
1843       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1844       Builder.AddPlaceholderChunk("CF type");
1845       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1846       Builder.AddPlaceholderChunk("expression");
1847       Results.AddResult(Result(Builder.TakeString()));
1848     }
1849     // Fall through
1850 
1851   case Sema::PCC_Expression: {
1852     if (SemaRef.getLangOpts().CPlusPlus) {
1853       // 'this', if we're in a non-static member function.
1854       addThisCompletion(SemaRef, Results);
1855 
1856       // true
1857       Builder.AddResultTypeChunk("bool");
1858       Builder.AddTypedTextChunk("true");
1859       Results.AddResult(Result(Builder.TakeString()));
1860 
1861       // false
1862       Builder.AddResultTypeChunk("bool");
1863       Builder.AddTypedTextChunk("false");
1864       Results.AddResult(Result(Builder.TakeString()));
1865 
1866       if (SemaRef.getLangOpts().RTTI) {
1867         // dynamic_cast < type-id > ( expression )
1868         Builder.AddTypedTextChunk("dynamic_cast");
1869         Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1870         Builder.AddPlaceholderChunk("type");
1871         Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1872         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1873         Builder.AddPlaceholderChunk("expression");
1874         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1875         Results.AddResult(Result(Builder.TakeString()));
1876       }
1877 
1878       // static_cast < type-id > ( expression )
1879       Builder.AddTypedTextChunk("static_cast");
1880       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1881       Builder.AddPlaceholderChunk("type");
1882       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1883       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1884       Builder.AddPlaceholderChunk("expression");
1885       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1886       Results.AddResult(Result(Builder.TakeString()));
1887 
1888       // reinterpret_cast < type-id > ( expression )
1889       Builder.AddTypedTextChunk("reinterpret_cast");
1890       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1891       Builder.AddPlaceholderChunk("type");
1892       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1893       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1894       Builder.AddPlaceholderChunk("expression");
1895       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1896       Results.AddResult(Result(Builder.TakeString()));
1897 
1898       // const_cast < type-id > ( expression )
1899       Builder.AddTypedTextChunk("const_cast");
1900       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1901       Builder.AddPlaceholderChunk("type");
1902       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1903       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1904       Builder.AddPlaceholderChunk("expression");
1905       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1906       Results.AddResult(Result(Builder.TakeString()));
1907 
1908       if (SemaRef.getLangOpts().RTTI) {
1909         // typeid ( expression-or-type )
1910         Builder.AddResultTypeChunk("std::type_info");
1911         Builder.AddTypedTextChunk("typeid");
1912         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1913         Builder.AddPlaceholderChunk("expression-or-type");
1914         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1915         Results.AddResult(Result(Builder.TakeString()));
1916       }
1917 
1918       // new T ( ... )
1919       Builder.AddTypedTextChunk("new");
1920       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1921       Builder.AddPlaceholderChunk("type");
1922       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1923       Builder.AddPlaceholderChunk("expressions");
1924       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1925       Results.AddResult(Result(Builder.TakeString()));
1926 
1927       // new T [ ] ( ... )
1928       Builder.AddTypedTextChunk("new");
1929       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1930       Builder.AddPlaceholderChunk("type");
1931       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1932       Builder.AddPlaceholderChunk("size");
1933       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1934       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935       Builder.AddPlaceholderChunk("expressions");
1936       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937       Results.AddResult(Result(Builder.TakeString()));
1938 
1939       // delete expression
1940       Builder.AddResultTypeChunk("void");
1941       Builder.AddTypedTextChunk("delete");
1942       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1943       Builder.AddPlaceholderChunk("expression");
1944       Results.AddResult(Result(Builder.TakeString()));
1945 
1946       // delete [] expression
1947       Builder.AddResultTypeChunk("void");
1948       Builder.AddTypedTextChunk("delete");
1949       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1950       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1951       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1952       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1953       Builder.AddPlaceholderChunk("expression");
1954       Results.AddResult(Result(Builder.TakeString()));
1955 
1956       if (SemaRef.getLangOpts().CXXExceptions) {
1957         // throw expression
1958         Builder.AddResultTypeChunk("void");
1959         Builder.AddTypedTextChunk("throw");
1960         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1961         Builder.AddPlaceholderChunk("expression");
1962         Results.AddResult(Result(Builder.TakeString()));
1963       }
1964 
1965       // FIXME: Rethrow?
1966 
1967       if (SemaRef.getLangOpts().CPlusPlus11) {
1968         // nullptr
1969         Builder.AddResultTypeChunk("std::nullptr_t");
1970         Builder.AddTypedTextChunk("nullptr");
1971         Results.AddResult(Result(Builder.TakeString()));
1972 
1973         // alignof
1974         Builder.AddResultTypeChunk("size_t");
1975         Builder.AddTypedTextChunk("alignof");
1976         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1977         Builder.AddPlaceholderChunk("type");
1978         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1979         Results.AddResult(Result(Builder.TakeString()));
1980 
1981         // noexcept
1982         Builder.AddResultTypeChunk("bool");
1983         Builder.AddTypedTextChunk("noexcept");
1984         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1985         Builder.AddPlaceholderChunk("expression");
1986         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1987         Results.AddResult(Result(Builder.TakeString()));
1988 
1989         // sizeof... expression
1990         Builder.AddResultTypeChunk("size_t");
1991         Builder.AddTypedTextChunk("sizeof...");
1992         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1993         Builder.AddPlaceholderChunk("parameter-pack");
1994         Builder.AddChunk(CodeCompletionString::CK_RightParen);
1995         Results.AddResult(Result(Builder.TakeString()));
1996       }
1997     }
1998 
1999     if (SemaRef.getLangOpts().ObjC1) {
2000       // Add "super", if we're in an Objective-C class with a superclass.
2001       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2002         // The interface can be NULL.
2003         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2004           if (ID->getSuperClass()) {
2005             std::string SuperType;
2006             SuperType = ID->getSuperClass()->getNameAsString();
2007             if (Method->isInstanceMethod())
2008               SuperType += " *";
2009 
2010             Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2011             Builder.AddTypedTextChunk("super");
2012             Results.AddResult(Result(Builder.TakeString()));
2013           }
2014       }
2015 
2016       AddObjCExpressionResults(Results, true);
2017     }
2018 
2019     if (SemaRef.getLangOpts().C11) {
2020       // _Alignof
2021       Builder.AddResultTypeChunk("size_t");
2022       if (SemaRef.getASTContext().Idents.get("alignof").hasMacroDefinition())
2023         Builder.AddTypedTextChunk("alignof");
2024       else
2025         Builder.AddTypedTextChunk("_Alignof");
2026       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2027       Builder.AddPlaceholderChunk("type");
2028       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2029       Results.AddResult(Result(Builder.TakeString()));
2030     }
2031 
2032     // sizeof expression
2033     Builder.AddResultTypeChunk("size_t");
2034     Builder.AddTypedTextChunk("sizeof");
2035     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2036     Builder.AddPlaceholderChunk("expression-or-type");
2037     Builder.AddChunk(CodeCompletionString::CK_RightParen);
2038     Results.AddResult(Result(Builder.TakeString()));
2039     break;
2040   }
2041 
2042   case Sema::PCC_Type:
2043   case Sema::PCC_LocalDeclarationSpecifiers:
2044     break;
2045   }
2046 
2047   if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2048     AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2049 
2050   if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2051     Results.AddResult(Result("operator"));
2052 }
2053 
2054 /// \brief If the given declaration has an associated type, add it as a result
2055 /// type chunk.
2056 static void AddResultTypeChunk(ASTContext &Context,
2057                                const PrintingPolicy &Policy,
2058                                const NamedDecl *ND,
2059                                CodeCompletionBuilder &Result) {
2060   if (!ND)
2061     return;
2062 
2063   // Skip constructors and conversion functions, which have their return types
2064   // built into their names.
2065   if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2066     return;
2067 
2068   // Determine the type of the declaration (if it has a type).
2069   QualType T;
2070   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
2071     T = Function->getResultType();
2072   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
2073     T = Method->getResultType();
2074   else if (const FunctionTemplateDecl *FunTmpl =
2075                dyn_cast<FunctionTemplateDecl>(ND))
2076     T = FunTmpl->getTemplatedDecl()->getResultType();
2077   else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2078     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2079   else if (isa<UnresolvedUsingValueDecl>(ND)) {
2080     /* Do nothing: ignore unresolved using declarations*/
2081   } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2082     T = Value->getType();
2083   } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
2084     T = Property->getType();
2085 
2086   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2087     return;
2088 
2089   Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2090                                                     Result.getAllocator()));
2091 }
2092 
2093 static void MaybeAddSentinel(ASTContext &Context,
2094                              const NamedDecl *FunctionOrMethod,
2095                              CodeCompletionBuilder &Result) {
2096   if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2097     if (Sentinel->getSentinel() == 0) {
2098       if (Context.getLangOpts().ObjC1 &&
2099           Context.Idents.get("nil").hasMacroDefinition())
2100         Result.AddTextChunk(", nil");
2101       else if (Context.Idents.get("NULL").hasMacroDefinition())
2102         Result.AddTextChunk(", NULL");
2103       else
2104         Result.AddTextChunk(", (void*)0");
2105     }
2106 }
2107 
2108 static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2109   std::string Result;
2110   if (ObjCQuals & Decl::OBJC_TQ_In)
2111     Result += "in ";
2112   else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2113     Result += "inout ";
2114   else if (ObjCQuals & Decl::OBJC_TQ_Out)
2115     Result += "out ";
2116   if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2117     Result += "bycopy ";
2118   else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2119     Result += "byref ";
2120   if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2121     Result += "oneway ";
2122   return Result;
2123 }
2124 
2125 static std::string FormatFunctionParameter(ASTContext &Context,
2126                                            const PrintingPolicy &Policy,
2127                                            const ParmVarDecl *Param,
2128                                            bool SuppressName = false,
2129                                            bool SuppressBlock = false) {
2130   bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2131   if (Param->getType()->isDependentType() ||
2132       !Param->getType()->isBlockPointerType()) {
2133     // The argument for a dependent or non-block parameter is a placeholder
2134     // containing that parameter's type.
2135     std::string Result;
2136 
2137     if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2138       Result = Param->getIdentifier()->getName();
2139 
2140     Param->getType().getAsStringInternal(Result, Policy);
2141 
2142     if (ObjCMethodParam) {
2143       Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2144              + Result + ")";
2145       if (Param->getIdentifier() && !SuppressName)
2146         Result += Param->getIdentifier()->getName();
2147     }
2148     return Result;
2149   }
2150 
2151   // The argument for a block pointer parameter is a block literal with
2152   // the appropriate type.
2153   FunctionTypeLoc Block;
2154   FunctionProtoTypeLoc BlockProto;
2155   TypeLoc TL;
2156   if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2157     TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2158     while (true) {
2159       // Look through typedefs.
2160       if (!SuppressBlock) {
2161         if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2162           if (TypeSourceInfo *InnerTSInfo =
2163                   TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2164             TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2165             continue;
2166           }
2167         }
2168 
2169         // Look through qualified types
2170         if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2171           TL = QualifiedTL.getUnqualifiedLoc();
2172           continue;
2173         }
2174       }
2175 
2176       // Try to get the function prototype behind the block pointer type,
2177       // then we're done.
2178       if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2179         TL = BlockPtr.getPointeeLoc().IgnoreParens();
2180         Block = TL.getAs<FunctionTypeLoc>();
2181         BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2182       }
2183       break;
2184     }
2185   }
2186 
2187   if (!Block) {
2188     // We were unable to find a FunctionProtoTypeLoc with parameter names
2189     // for the block; just use the parameter type as a placeholder.
2190     std::string Result;
2191     if (!ObjCMethodParam && Param->getIdentifier())
2192       Result = Param->getIdentifier()->getName();
2193 
2194     Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
2195 
2196     if (ObjCMethodParam) {
2197       Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2198              + Result + ")";
2199       if (Param->getIdentifier())
2200         Result += Param->getIdentifier()->getName();
2201     }
2202 
2203     return Result;
2204   }
2205 
2206   // We have the function prototype behind the block pointer type, as it was
2207   // written in the source.
2208   std::string Result;
2209   QualType ResultType = Block.getTypePtr()->getResultType();
2210   if (!ResultType->isVoidType() || SuppressBlock)
2211     ResultType.getAsStringInternal(Result, Policy);
2212 
2213   // Format the parameter list.
2214   std::string Params;
2215   if (!BlockProto || Block.getNumParams() == 0) {
2216     if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2217       Params = "(...)";
2218     else
2219       Params = "(void)";
2220   } else {
2221     Params += "(";
2222     for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2223       if (I)
2224         Params += ", ";
2225       Params += FormatFunctionParameter(Context, Policy, Block.getParam(I),
2226                                         /*SuppressName=*/false,
2227                                         /*SuppressBlock=*/true);
2228 
2229       if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2230         Params += ", ...";
2231     }
2232     Params += ")";
2233   }
2234 
2235   if (SuppressBlock) {
2236     // Format as a parameter.
2237     Result = Result + " (^";
2238     if (Param->getIdentifier())
2239       Result += Param->getIdentifier()->getName();
2240     Result += ")";
2241     Result += Params;
2242   } else {
2243     // Format as a block literal argument.
2244     Result = '^' + Result;
2245     Result += Params;
2246 
2247     if (Param->getIdentifier())
2248       Result += Param->getIdentifier()->getName();
2249   }
2250 
2251   return Result;
2252 }
2253 
2254 /// \brief Add function parameter chunks to the given code completion string.
2255 static void AddFunctionParameterChunks(ASTContext &Context,
2256                                        const PrintingPolicy &Policy,
2257                                        const FunctionDecl *Function,
2258                                        CodeCompletionBuilder &Result,
2259                                        unsigned Start = 0,
2260                                        bool InOptional = false) {
2261   bool FirstParameter = true;
2262 
2263   for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2264     const ParmVarDecl *Param = Function->getParamDecl(P);
2265 
2266     if (Param->hasDefaultArg() && !InOptional) {
2267       // When we see an optional default argument, put that argument and
2268       // the remaining default arguments into a new, optional string.
2269       CodeCompletionBuilder Opt(Result.getAllocator(),
2270                                 Result.getCodeCompletionTUInfo());
2271       if (!FirstParameter)
2272         Opt.AddChunk(CodeCompletionString::CK_Comma);
2273       AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
2274       Result.AddOptionalChunk(Opt.TakeString());
2275       break;
2276     }
2277 
2278     if (FirstParameter)
2279       FirstParameter = false;
2280     else
2281       Result.AddChunk(CodeCompletionString::CK_Comma);
2282 
2283     InOptional = false;
2284 
2285     // Format the placeholder string.
2286     std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2287                                                          Param);
2288 
2289     if (Function->isVariadic() && P == N - 1)
2290       PlaceholderStr += ", ...";
2291 
2292     // Add the placeholder string.
2293     Result.AddPlaceholderChunk(
2294                              Result.getAllocator().CopyString(PlaceholderStr));
2295   }
2296 
2297   if (const FunctionProtoType *Proto
2298         = Function->getType()->getAs<FunctionProtoType>())
2299     if (Proto->isVariadic()) {
2300       if (Proto->getNumParams() == 0)
2301         Result.AddPlaceholderChunk("...");
2302 
2303       MaybeAddSentinel(Context, Function, Result);
2304     }
2305 }
2306 
2307 /// \brief Add template parameter chunks to the given code completion string.
2308 static void AddTemplateParameterChunks(ASTContext &Context,
2309                                        const PrintingPolicy &Policy,
2310                                        const TemplateDecl *Template,
2311                                        CodeCompletionBuilder &Result,
2312                                        unsigned MaxParameters = 0,
2313                                        unsigned Start = 0,
2314                                        bool InDefaultArg = false) {
2315   bool FirstParameter = true;
2316 
2317   TemplateParameterList *Params = Template->getTemplateParameters();
2318   TemplateParameterList::iterator PEnd = Params->end();
2319   if (MaxParameters)
2320     PEnd = Params->begin() + MaxParameters;
2321   for (TemplateParameterList::iterator P = Params->begin() + Start;
2322        P != PEnd; ++P) {
2323     bool HasDefaultArg = false;
2324     std::string PlaceholderStr;
2325     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2326       if (TTP->wasDeclaredWithTypename())
2327         PlaceholderStr = "typename";
2328       else
2329         PlaceholderStr = "class";
2330 
2331       if (TTP->getIdentifier()) {
2332         PlaceholderStr += ' ';
2333         PlaceholderStr += TTP->getIdentifier()->getName();
2334       }
2335 
2336       HasDefaultArg = TTP->hasDefaultArgument();
2337     } else if (NonTypeTemplateParmDecl *NTTP
2338                                     = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2339       if (NTTP->getIdentifier())
2340         PlaceholderStr = NTTP->getIdentifier()->getName();
2341       NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2342       HasDefaultArg = NTTP->hasDefaultArgument();
2343     } else {
2344       assert(isa<TemplateTemplateParmDecl>(*P));
2345       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2346 
2347       // Since putting the template argument list into the placeholder would
2348       // be very, very long, we just use an abbreviation.
2349       PlaceholderStr = "template<...> class";
2350       if (TTP->getIdentifier()) {
2351         PlaceholderStr += ' ';
2352         PlaceholderStr += TTP->getIdentifier()->getName();
2353       }
2354 
2355       HasDefaultArg = TTP->hasDefaultArgument();
2356     }
2357 
2358     if (HasDefaultArg && !InDefaultArg) {
2359       // When we see an optional default argument, put that argument and
2360       // the remaining default arguments into a new, optional string.
2361       CodeCompletionBuilder Opt(Result.getAllocator(),
2362                                 Result.getCodeCompletionTUInfo());
2363       if (!FirstParameter)
2364         Opt.AddChunk(CodeCompletionString::CK_Comma);
2365       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2366                                  P - Params->begin(), true);
2367       Result.AddOptionalChunk(Opt.TakeString());
2368       break;
2369     }
2370 
2371     InDefaultArg = false;
2372 
2373     if (FirstParameter)
2374       FirstParameter = false;
2375     else
2376       Result.AddChunk(CodeCompletionString::CK_Comma);
2377 
2378     // Add the placeholder string.
2379     Result.AddPlaceholderChunk(
2380                               Result.getAllocator().CopyString(PlaceholderStr));
2381   }
2382 }
2383 
2384 /// \brief Add a qualifier to the given code-completion string, if the
2385 /// provided nested-name-specifier is non-NULL.
2386 static void
2387 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2388                                NestedNameSpecifier *Qualifier,
2389                                bool QualifierIsInformative,
2390                                ASTContext &Context,
2391                                const PrintingPolicy &Policy) {
2392   if (!Qualifier)
2393     return;
2394 
2395   std::string PrintedNNS;
2396   {
2397     llvm::raw_string_ostream OS(PrintedNNS);
2398     Qualifier->print(OS, Policy);
2399   }
2400   if (QualifierIsInformative)
2401     Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2402   else
2403     Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2404 }
2405 
2406 static void
2407 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2408                                        const FunctionDecl *Function) {
2409   const FunctionProtoType *Proto
2410     = Function->getType()->getAs<FunctionProtoType>();
2411   if (!Proto || !Proto->getTypeQuals())
2412     return;
2413 
2414   // FIXME: Add ref-qualifier!
2415 
2416   // Handle single qualifiers without copying
2417   if (Proto->getTypeQuals() == Qualifiers::Const) {
2418     Result.AddInformativeChunk(" const");
2419     return;
2420   }
2421 
2422   if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2423     Result.AddInformativeChunk(" volatile");
2424     return;
2425   }
2426 
2427   if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2428     Result.AddInformativeChunk(" restrict");
2429     return;
2430   }
2431 
2432   // Handle multiple qualifiers.
2433   std::string QualsStr;
2434   if (Proto->isConst())
2435     QualsStr += " const";
2436   if (Proto->isVolatile())
2437     QualsStr += " volatile";
2438   if (Proto->isRestrict())
2439     QualsStr += " restrict";
2440   Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2441 }
2442 
2443 /// \brief Add the name of the given declaration
2444 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2445                               const NamedDecl *ND,
2446                               CodeCompletionBuilder &Result) {
2447   DeclarationName Name = ND->getDeclName();
2448   if (!Name)
2449     return;
2450 
2451   switch (Name.getNameKind()) {
2452     case DeclarationName::CXXOperatorName: {
2453       const char *OperatorName = 0;
2454       switch (Name.getCXXOverloadedOperator()) {
2455       case OO_None:
2456       case OO_Conditional:
2457       case NUM_OVERLOADED_OPERATORS:
2458         OperatorName = "operator";
2459         break;
2460 
2461 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2462       case OO_##Name: OperatorName = "operator" Spelling; break;
2463 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2464 #include "clang/Basic/OperatorKinds.def"
2465 
2466       case OO_New:          OperatorName = "operator new"; break;
2467       case OO_Delete:       OperatorName = "operator delete"; break;
2468       case OO_Array_New:    OperatorName = "operator new[]"; break;
2469       case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2470       case OO_Call:         OperatorName = "operator()"; break;
2471       case OO_Subscript:    OperatorName = "operator[]"; break;
2472       }
2473       Result.AddTypedTextChunk(OperatorName);
2474       break;
2475     }
2476 
2477   case DeclarationName::Identifier:
2478   case DeclarationName::CXXConversionFunctionName:
2479   case DeclarationName::CXXDestructorName:
2480   case DeclarationName::CXXLiteralOperatorName:
2481     Result.AddTypedTextChunk(
2482                       Result.getAllocator().CopyString(ND->getNameAsString()));
2483     break;
2484 
2485   case DeclarationName::CXXUsingDirective:
2486   case DeclarationName::ObjCZeroArgSelector:
2487   case DeclarationName::ObjCOneArgSelector:
2488   case DeclarationName::ObjCMultiArgSelector:
2489     break;
2490 
2491   case DeclarationName::CXXConstructorName: {
2492     CXXRecordDecl *Record = 0;
2493     QualType Ty = Name.getCXXNameType();
2494     if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2495       Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2496     else if (const InjectedClassNameType *InjectedTy
2497                                         = Ty->getAs<InjectedClassNameType>())
2498       Record = InjectedTy->getDecl();
2499     else {
2500       Result.AddTypedTextChunk(
2501                       Result.getAllocator().CopyString(ND->getNameAsString()));
2502       break;
2503     }
2504 
2505     Result.AddTypedTextChunk(
2506                   Result.getAllocator().CopyString(Record->getNameAsString()));
2507     if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2508       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2509       AddTemplateParameterChunks(Context, Policy, Template, Result);
2510       Result.AddChunk(CodeCompletionString::CK_RightAngle);
2511     }
2512     break;
2513   }
2514   }
2515 }
2516 
2517 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2518                                          CodeCompletionAllocator &Allocator,
2519                                          CodeCompletionTUInfo &CCTUInfo,
2520                                          bool IncludeBriefComments) {
2521   return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo,
2522                                     IncludeBriefComments);
2523 }
2524 
2525 /// \brief If possible, create a new code completion string for the given
2526 /// result.
2527 ///
2528 /// \returns Either a new, heap-allocated code completion string describing
2529 /// how to use this result, or NULL to indicate that the string or name of the
2530 /// result is all that is needed.
2531 CodeCompletionString *
2532 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2533                                                  Preprocessor &PP,
2534                                            CodeCompletionAllocator &Allocator,
2535                                            CodeCompletionTUInfo &CCTUInfo,
2536                                            bool IncludeBriefComments) {
2537   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2538 
2539   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2540   if (Kind == RK_Pattern) {
2541     Pattern->Priority = Priority;
2542     Pattern->Availability = Availability;
2543 
2544     if (Declaration) {
2545       Result.addParentContext(Declaration->getDeclContext());
2546       Pattern->ParentName = Result.getParentName();
2547       // Provide code completion comment for self.GetterName where
2548       // GetterName is the getter method for a property with name
2549       // different from the property name (declared via a property
2550       // getter attribute.
2551       const NamedDecl *ND = Declaration;
2552       if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2553         if (M->isPropertyAccessor())
2554           if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2555             if (PDecl->getGetterName() == M->getSelector() &&
2556                 PDecl->getIdentifier() != M->getIdentifier()) {
2557               if (const RawComment *RC =
2558                     Ctx.getRawCommentForAnyRedecl(M)) {
2559                 Result.addBriefComment(RC->getBriefText(Ctx));
2560                 Pattern->BriefComment = Result.getBriefComment();
2561               }
2562               else if (const RawComment *RC =
2563                          Ctx.getRawCommentForAnyRedecl(PDecl)) {
2564                 Result.addBriefComment(RC->getBriefText(Ctx));
2565                 Pattern->BriefComment = Result.getBriefComment();
2566               }
2567             }
2568     }
2569 
2570     return Pattern;
2571   }
2572 
2573   if (Kind == RK_Keyword) {
2574     Result.AddTypedTextChunk(Keyword);
2575     return Result.TakeString();
2576   }
2577 
2578   if (Kind == RK_Macro) {
2579     const MacroDirective *MD = PP.getMacroDirectiveHistory(Macro);
2580     assert(MD && "Not a macro?");
2581     const MacroInfo *MI = MD->getMacroInfo();
2582 
2583     Result.AddTypedTextChunk(
2584                             Result.getAllocator().CopyString(Macro->getName()));
2585 
2586     if (!MI->isFunctionLike())
2587       return Result.TakeString();
2588 
2589     // Format a function-like macro with placeholders for the arguments.
2590     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2591     MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2592 
2593     // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2594     if (MI->isC99Varargs()) {
2595       --AEnd;
2596 
2597       if (A == AEnd) {
2598         Result.AddPlaceholderChunk("...");
2599       }
2600     }
2601 
2602     for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
2603       if (A != MI->arg_begin())
2604         Result.AddChunk(CodeCompletionString::CK_Comma);
2605 
2606       if (MI->isVariadic() && (A+1) == AEnd) {
2607         SmallString<32> Arg = (*A)->getName();
2608         if (MI->isC99Varargs())
2609           Arg += ", ...";
2610         else
2611           Arg += "...";
2612         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2613         break;
2614       }
2615 
2616       // Non-variadic macros are simple.
2617       Result.AddPlaceholderChunk(
2618                           Result.getAllocator().CopyString((*A)->getName()));
2619     }
2620     Result.AddChunk(CodeCompletionString::CK_RightParen);
2621     return Result.TakeString();
2622   }
2623 
2624   assert(Kind == RK_Declaration && "Missed a result kind?");
2625   const NamedDecl *ND = Declaration;
2626   Result.addParentContext(ND->getDeclContext());
2627 
2628   if (IncludeBriefComments) {
2629     // Add documentation comment, if it exists.
2630     if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2631       Result.addBriefComment(RC->getBriefText(Ctx));
2632     }
2633     else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2634       if (OMD->isPropertyAccessor())
2635         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2636           if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2637             Result.addBriefComment(RC->getBriefText(Ctx));
2638   }
2639 
2640   if (StartsNestedNameSpecifier) {
2641     Result.AddTypedTextChunk(
2642                       Result.getAllocator().CopyString(ND->getNameAsString()));
2643     Result.AddTextChunk("::");
2644     return Result.TakeString();
2645   }
2646 
2647   for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2648     if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2649       Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2650     }
2651   }
2652 
2653   AddResultTypeChunk(Ctx, Policy, ND, Result);
2654 
2655   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2656     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2657                                    Ctx, Policy);
2658     AddTypedNameChunk(Ctx, Policy, ND, Result);
2659     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2660     AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2661     Result.AddChunk(CodeCompletionString::CK_RightParen);
2662     AddFunctionTypeQualsToCompletionString(Result, Function);
2663     return Result.TakeString();
2664   }
2665 
2666   if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2667     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2668                                    Ctx, Policy);
2669     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2670     AddTypedNameChunk(Ctx, Policy, Function, Result);
2671 
2672     // Figure out which template parameters are deduced (or have default
2673     // arguments).
2674     llvm::SmallBitVector Deduced;
2675     Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2676     unsigned LastDeducibleArgument;
2677     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2678          --LastDeducibleArgument) {
2679       if (!Deduced[LastDeducibleArgument - 1]) {
2680         // C++0x: Figure out if the template argument has a default. If so,
2681         // the user doesn't need to type this argument.
2682         // FIXME: We need to abstract template parameters better!
2683         bool HasDefaultArg = false;
2684         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2685                                                     LastDeducibleArgument - 1);
2686         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2687           HasDefaultArg = TTP->hasDefaultArgument();
2688         else if (NonTypeTemplateParmDecl *NTTP
2689                  = dyn_cast<NonTypeTemplateParmDecl>(Param))
2690           HasDefaultArg = NTTP->hasDefaultArgument();
2691         else {
2692           assert(isa<TemplateTemplateParmDecl>(Param));
2693           HasDefaultArg
2694             = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2695         }
2696 
2697         if (!HasDefaultArg)
2698           break;
2699       }
2700     }
2701 
2702     if (LastDeducibleArgument) {
2703       // Some of the function template arguments cannot be deduced from a
2704       // function call, so we introduce an explicit template argument list
2705       // containing all of the arguments up to the first deducible argument.
2706       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2707       AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2708                                  LastDeducibleArgument);
2709       Result.AddChunk(CodeCompletionString::CK_RightAngle);
2710     }
2711 
2712     // Add the function parameters
2713     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2714     AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2715     Result.AddChunk(CodeCompletionString::CK_RightParen);
2716     AddFunctionTypeQualsToCompletionString(Result, Function);
2717     return Result.TakeString();
2718   }
2719 
2720   if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2721     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2722                                    Ctx, Policy);
2723     Result.AddTypedTextChunk(
2724                 Result.getAllocator().CopyString(Template->getNameAsString()));
2725     Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2726     AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2727     Result.AddChunk(CodeCompletionString::CK_RightAngle);
2728     return Result.TakeString();
2729   }
2730 
2731   if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2732     Selector Sel = Method->getSelector();
2733     if (Sel.isUnarySelector()) {
2734       Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2735                                   Sel.getNameForSlot(0)));
2736       return Result.TakeString();
2737     }
2738 
2739     std::string SelName = Sel.getNameForSlot(0).str();
2740     SelName += ':';
2741     if (StartParameter == 0)
2742       Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2743     else {
2744       Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2745 
2746       // If there is only one parameter, and we're past it, add an empty
2747       // typed-text chunk since there is nothing to type.
2748       if (Method->param_size() == 1)
2749         Result.AddTypedTextChunk("");
2750     }
2751     unsigned Idx = 0;
2752     for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2753                                            PEnd = Method->param_end();
2754          P != PEnd; (void)++P, ++Idx) {
2755       if (Idx > 0) {
2756         std::string Keyword;
2757         if (Idx > StartParameter)
2758           Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2759         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2760           Keyword += II->getName();
2761         Keyword += ":";
2762         if (Idx < StartParameter || AllParametersAreInformative)
2763           Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2764         else
2765           Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2766       }
2767 
2768       // If we're before the starting parameter, skip the placeholder.
2769       if (Idx < StartParameter)
2770         continue;
2771 
2772       std::string Arg;
2773 
2774       if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2775         Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
2776       else {
2777         (*P)->getType().getAsStringInternal(Arg, Policy);
2778         Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2779             + Arg + ")";
2780         if (IdentifierInfo *II = (*P)->getIdentifier())
2781           if (DeclaringEntity || AllParametersAreInformative)
2782             Arg += II->getName();
2783       }
2784 
2785       if (Method->isVariadic() && (P + 1) == PEnd)
2786         Arg += ", ...";
2787 
2788       if (DeclaringEntity)
2789         Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2790       else if (AllParametersAreInformative)
2791         Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2792       else
2793         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2794     }
2795 
2796     if (Method->isVariadic()) {
2797       if (Method->param_size() == 0) {
2798         if (DeclaringEntity)
2799           Result.AddTextChunk(", ...");
2800         else if (AllParametersAreInformative)
2801           Result.AddInformativeChunk(", ...");
2802         else
2803           Result.AddPlaceholderChunk(", ...");
2804       }
2805 
2806       MaybeAddSentinel(Ctx, Method, Result);
2807     }
2808 
2809     return Result.TakeString();
2810   }
2811 
2812   if (Qualifier)
2813     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2814                                    Ctx, Policy);
2815 
2816   Result.AddTypedTextChunk(
2817                        Result.getAllocator().CopyString(ND->getNameAsString()));
2818   return Result.TakeString();
2819 }
2820 
2821 CodeCompletionString *
2822 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2823                                                           unsigned CurrentArg,
2824                                                                Sema &S,
2825                                      CodeCompletionAllocator &Allocator,
2826                                      CodeCompletionTUInfo &CCTUInfo) const {
2827   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2828 
2829   // FIXME: Set priority, availability appropriately.
2830   CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
2831   FunctionDecl *FDecl = getFunction();
2832   AddResultTypeChunk(S.Context, Policy, FDecl, Result);
2833   const FunctionProtoType *Proto
2834     = dyn_cast<FunctionProtoType>(getFunctionType());
2835   if (!FDecl && !Proto) {
2836     // Function without a prototype. Just give the return type and a
2837     // highlighted ellipsis.
2838     const FunctionType *FT = getFunctionType();
2839     Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2840                                                 S.Context, Policy,
2841                                                 Result.getAllocator()));
2842     Result.AddChunk(CodeCompletionString::CK_LeftParen);
2843     Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2844     Result.AddChunk(CodeCompletionString::CK_RightParen);
2845     return Result.TakeString();
2846   }
2847 
2848   if (FDecl)
2849     Result.AddTextChunk(
2850                     Result.getAllocator().CopyString(FDecl->getNameAsString()));
2851   else
2852     Result.AddTextChunk(
2853          Result.getAllocator().CopyString(
2854                                   Proto->getResultType().getAsString(Policy)));
2855 
2856   Result.AddChunk(CodeCompletionString::CK_LeftParen);
2857   unsigned NumParams = FDecl ? FDecl->getNumParams() : Proto->getNumParams();
2858   for (unsigned I = 0; I != NumParams; ++I) {
2859     if (I)
2860       Result.AddChunk(CodeCompletionString::CK_Comma);
2861 
2862     std::string ArgString;
2863     QualType ArgType;
2864 
2865     if (FDecl) {
2866       ArgString = FDecl->getParamDecl(I)->getNameAsString();
2867       ArgType = FDecl->getParamDecl(I)->getOriginalType();
2868     } else {
2869       ArgType = Proto->getParamType(I);
2870     }
2871 
2872     ArgType.getAsStringInternal(ArgString, Policy);
2873 
2874     if (I == CurrentArg)
2875       Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
2876                       Result.getAllocator().CopyString(ArgString));
2877     else
2878       Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
2879   }
2880 
2881   if (Proto && Proto->isVariadic()) {
2882     Result.AddChunk(CodeCompletionString::CK_Comma);
2883     if (CurrentArg < NumParams)
2884       Result.AddTextChunk("...");
2885     else
2886       Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2887   }
2888   Result.AddChunk(CodeCompletionString::CK_RightParen);
2889 
2890   return Result.TakeString();
2891 }
2892 
2893 unsigned clang::getMacroUsagePriority(StringRef MacroName,
2894                                       const LangOptions &LangOpts,
2895                                       bool PreferredTypeIsPointer) {
2896   unsigned Priority = CCP_Macro;
2897 
2898   // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2899   if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2900       MacroName.equals("Nil")) {
2901     Priority = CCP_Constant;
2902     if (PreferredTypeIsPointer)
2903       Priority = Priority / CCF_SimilarTypeMatch;
2904   }
2905   // Treat "YES", "NO", "true", and "false" as constants.
2906   else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2907            MacroName.equals("true") || MacroName.equals("false"))
2908     Priority = CCP_Constant;
2909   // Treat "bool" as a type.
2910   else if (MacroName.equals("bool"))
2911     Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2912 
2913 
2914   return Priority;
2915 }
2916 
2917 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
2918   if (!D)
2919     return CXCursor_UnexposedDecl;
2920 
2921   switch (D->getKind()) {
2922     case Decl::Enum:               return CXCursor_EnumDecl;
2923     case Decl::EnumConstant:       return CXCursor_EnumConstantDecl;
2924     case Decl::Field:              return CXCursor_FieldDecl;
2925     case Decl::Function:
2926       return CXCursor_FunctionDecl;
2927     case Decl::ObjCCategory:       return CXCursor_ObjCCategoryDecl;
2928     case Decl::ObjCCategoryImpl:   return CXCursor_ObjCCategoryImplDecl;
2929     case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2930 
2931     case Decl::ObjCInterface:      return CXCursor_ObjCInterfaceDecl;
2932     case Decl::ObjCIvar:           return CXCursor_ObjCIvarDecl;
2933     case Decl::ObjCMethod:
2934       return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2935       ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2936     case Decl::CXXMethod:          return CXCursor_CXXMethod;
2937     case Decl::CXXConstructor:     return CXCursor_Constructor;
2938     case Decl::CXXDestructor:      return CXCursor_Destructor;
2939     case Decl::CXXConversion:      return CXCursor_ConversionFunction;
2940     case Decl::ObjCProperty:       return CXCursor_ObjCPropertyDecl;
2941     case Decl::ObjCProtocol:       return CXCursor_ObjCProtocolDecl;
2942     case Decl::ParmVar:            return CXCursor_ParmDecl;
2943     case Decl::Typedef:            return CXCursor_TypedefDecl;
2944     case Decl::TypeAlias:          return CXCursor_TypeAliasDecl;
2945     case Decl::Var:                return CXCursor_VarDecl;
2946     case Decl::Namespace:          return CXCursor_Namespace;
2947     case Decl::NamespaceAlias:     return CXCursor_NamespaceAlias;
2948     case Decl::TemplateTypeParm:   return CXCursor_TemplateTypeParameter;
2949     case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2950     case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2951     case Decl::FunctionTemplate:   return CXCursor_FunctionTemplate;
2952     case Decl::ClassTemplate:      return CXCursor_ClassTemplate;
2953     case Decl::AccessSpec:         return CXCursor_CXXAccessSpecifier;
2954     case Decl::ClassTemplatePartialSpecialization:
2955       return CXCursor_ClassTemplatePartialSpecialization;
2956     case Decl::UsingDirective:     return CXCursor_UsingDirective;
2957     case Decl::TranslationUnit:    return CXCursor_TranslationUnit;
2958 
2959     case Decl::Using:
2960     case Decl::UnresolvedUsingValue:
2961     case Decl::UnresolvedUsingTypename:
2962       return CXCursor_UsingDeclaration;
2963 
2964     case Decl::ObjCPropertyImpl:
2965       switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2966       case ObjCPropertyImplDecl::Dynamic:
2967         return CXCursor_ObjCDynamicDecl;
2968 
2969       case ObjCPropertyImplDecl::Synthesize:
2970         return CXCursor_ObjCSynthesizeDecl;
2971       }
2972 
2973       case Decl::Import:
2974         return CXCursor_ModuleImportDecl;
2975 
2976     default:
2977       if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2978         switch (TD->getTagKind()) {
2979           case TTK_Interface:  // fall through
2980           case TTK_Struct: return CXCursor_StructDecl;
2981           case TTK_Class:  return CXCursor_ClassDecl;
2982           case TTK_Union:  return CXCursor_UnionDecl;
2983           case TTK_Enum:   return CXCursor_EnumDecl;
2984         }
2985       }
2986   }
2987 
2988   return CXCursor_UnexposedDecl;
2989 }
2990 
2991 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2992                             bool IncludeUndefined,
2993                             bool TargetTypeIsPointer = false) {
2994   typedef CodeCompletionResult Result;
2995 
2996   Results.EnterNewScope();
2997 
2998   for (Preprocessor::macro_iterator M = PP.macro_begin(),
2999                                  MEnd = PP.macro_end();
3000        M != MEnd; ++M) {
3001     if (IncludeUndefined || M->first->hasMacroDefinition())
3002       Results.AddResult(Result(M->first,
3003                              getMacroUsagePriority(M->first->getName(),
3004                                                    PP.getLangOpts(),
3005                                                    TargetTypeIsPointer)));
3006   }
3007 
3008   Results.ExitScope();
3009 
3010 }
3011 
3012 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3013                                      ResultBuilder &Results) {
3014   typedef CodeCompletionResult Result;
3015 
3016   Results.EnterNewScope();
3017 
3018   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3019   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3020   if (LangOpts.C99 || LangOpts.CPlusPlus11)
3021     Results.AddResult(Result("__func__", CCP_Constant));
3022   Results.ExitScope();
3023 }
3024 
3025 static void HandleCodeCompleteResults(Sema *S,
3026                                       CodeCompleteConsumer *CodeCompleter,
3027                                       CodeCompletionContext Context,
3028                                       CodeCompletionResult *Results,
3029                                       unsigned NumResults) {
3030   if (CodeCompleter)
3031     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3032 }
3033 
3034 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3035                                             Sema::ParserCompletionContext PCC) {
3036   switch (PCC) {
3037   case Sema::PCC_Namespace:
3038     return CodeCompletionContext::CCC_TopLevel;
3039 
3040   case Sema::PCC_Class:
3041     return CodeCompletionContext::CCC_ClassStructUnion;
3042 
3043   case Sema::PCC_ObjCInterface:
3044     return CodeCompletionContext::CCC_ObjCInterface;
3045 
3046   case Sema::PCC_ObjCImplementation:
3047     return CodeCompletionContext::CCC_ObjCImplementation;
3048 
3049   case Sema::PCC_ObjCInstanceVariableList:
3050     return CodeCompletionContext::CCC_ObjCIvarList;
3051 
3052   case Sema::PCC_Template:
3053   case Sema::PCC_MemberTemplate:
3054     if (S.CurContext->isFileContext())
3055       return CodeCompletionContext::CCC_TopLevel;
3056     if (S.CurContext->isRecord())
3057       return CodeCompletionContext::CCC_ClassStructUnion;
3058     return CodeCompletionContext::CCC_Other;
3059 
3060   case Sema::PCC_RecoveryInFunction:
3061     return CodeCompletionContext::CCC_Recovery;
3062 
3063   case Sema::PCC_ForInit:
3064     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3065         S.getLangOpts().ObjC1)
3066       return CodeCompletionContext::CCC_ParenthesizedExpression;
3067     else
3068       return CodeCompletionContext::CCC_Expression;
3069 
3070   case Sema::PCC_Expression:
3071   case Sema::PCC_Condition:
3072     return CodeCompletionContext::CCC_Expression;
3073 
3074   case Sema::PCC_Statement:
3075     return CodeCompletionContext::CCC_Statement;
3076 
3077   case Sema::PCC_Type:
3078     return CodeCompletionContext::CCC_Type;
3079 
3080   case Sema::PCC_ParenthesizedExpression:
3081     return CodeCompletionContext::CCC_ParenthesizedExpression;
3082 
3083   case Sema::PCC_LocalDeclarationSpecifiers:
3084     return CodeCompletionContext::CCC_Type;
3085   }
3086 
3087   llvm_unreachable("Invalid ParserCompletionContext!");
3088 }
3089 
3090 /// \brief If we're in a C++ virtual member function, add completion results
3091 /// that invoke the functions we override, since it's common to invoke the
3092 /// overridden function as well as adding new functionality.
3093 ///
3094 /// \param S The semantic analysis object for which we are generating results.
3095 ///
3096 /// \param InContext This context in which the nested-name-specifier preceding
3097 /// the code-completion point
3098 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3099                                   ResultBuilder &Results) {
3100   // Look through blocks.
3101   DeclContext *CurContext = S.CurContext;
3102   while (isa<BlockDecl>(CurContext))
3103     CurContext = CurContext->getParent();
3104 
3105 
3106   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3107   if (!Method || !Method->isVirtual())
3108     return;
3109 
3110   // We need to have names for all of the parameters, if we're going to
3111   // generate a forwarding call.
3112   for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3113                                   PEnd = Method->param_end();
3114        P != PEnd;
3115        ++P) {
3116     if (!(*P)->getDeclName())
3117       return;
3118   }
3119 
3120   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3121   for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3122                                    MEnd = Method->end_overridden_methods();
3123        M != MEnd; ++M) {
3124     CodeCompletionBuilder Builder(Results.getAllocator(),
3125                                   Results.getCodeCompletionTUInfo());
3126     const CXXMethodDecl *Overridden = *M;
3127     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3128       continue;
3129 
3130     // If we need a nested-name-specifier, add one now.
3131     if (!InContext) {
3132       NestedNameSpecifier *NNS
3133         = getRequiredQualification(S.Context, CurContext,
3134                                    Overridden->getDeclContext());
3135       if (NNS) {
3136         std::string Str;
3137         llvm::raw_string_ostream OS(Str);
3138         NNS->print(OS, Policy);
3139         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3140       }
3141     } else if (!InContext->Equals(Overridden->getDeclContext()))
3142       continue;
3143 
3144     Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3145                                          Overridden->getNameAsString()));
3146     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3147     bool FirstParam = true;
3148     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3149                                     PEnd = Method->param_end();
3150          P != PEnd; ++P) {
3151       if (FirstParam)
3152         FirstParam = false;
3153       else
3154         Builder.AddChunk(CodeCompletionString::CK_Comma);
3155 
3156       Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
3157                                         (*P)->getIdentifier()->getName()));
3158     }
3159     Builder.AddChunk(CodeCompletionString::CK_RightParen);
3160     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3161                                            CCP_SuperCompletion,
3162                                            CXCursor_CXXMethod,
3163                                            CXAvailability_Available,
3164                                            Overridden));
3165     Results.Ignore(Overridden);
3166   }
3167 }
3168 
3169 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3170                                     ModuleIdPath Path) {
3171   typedef CodeCompletionResult Result;
3172   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3173                         CodeCompleter->getCodeCompletionTUInfo(),
3174                         CodeCompletionContext::CCC_Other);
3175   Results.EnterNewScope();
3176 
3177   CodeCompletionAllocator &Allocator = Results.getAllocator();
3178   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3179   typedef CodeCompletionResult Result;
3180   if (Path.empty()) {
3181     // Enumerate all top-level modules.
3182     SmallVector<Module *, 8> Modules;
3183     PP.getHeaderSearchInfo().collectAllModules(Modules);
3184     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3185       Builder.AddTypedTextChunk(
3186         Builder.getAllocator().CopyString(Modules[I]->Name));
3187       Results.AddResult(Result(Builder.TakeString(),
3188                                CCP_Declaration,
3189                                CXCursor_ModuleImportDecl,
3190                                Modules[I]->isAvailable()
3191                                  ? CXAvailability_Available
3192                                   : CXAvailability_NotAvailable));
3193     }
3194   } else if (getLangOpts().Modules) {
3195     // Load the named module.
3196     Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3197                                                   Module::AllVisible,
3198                                                 /*IsInclusionDirective=*/false);
3199     // Enumerate submodules.
3200     if (Mod) {
3201       for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3202                                    SubEnd = Mod->submodule_end();
3203            Sub != SubEnd; ++Sub) {
3204 
3205         Builder.AddTypedTextChunk(
3206           Builder.getAllocator().CopyString((*Sub)->Name));
3207         Results.AddResult(Result(Builder.TakeString(),
3208                                  CCP_Declaration,
3209                                  CXCursor_ModuleImportDecl,
3210                                  (*Sub)->isAvailable()
3211                                    ? CXAvailability_Available
3212                                    : CXAvailability_NotAvailable));
3213       }
3214     }
3215   }
3216   Results.ExitScope();
3217   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3218                             Results.data(),Results.size());
3219 }
3220 
3221 void Sema::CodeCompleteOrdinaryName(Scope *S,
3222                                     ParserCompletionContext CompletionContext) {
3223   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3224                         CodeCompleter->getCodeCompletionTUInfo(),
3225                         mapCodeCompletionContext(*this, CompletionContext));
3226   Results.EnterNewScope();
3227 
3228   // Determine how to filter results, e.g., so that the names of
3229   // values (functions, enumerators, function templates, etc.) are
3230   // only allowed where we can have an expression.
3231   switch (CompletionContext) {
3232   case PCC_Namespace:
3233   case PCC_Class:
3234   case PCC_ObjCInterface:
3235   case PCC_ObjCImplementation:
3236   case PCC_ObjCInstanceVariableList:
3237   case PCC_Template:
3238   case PCC_MemberTemplate:
3239   case PCC_Type:
3240   case PCC_LocalDeclarationSpecifiers:
3241     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3242     break;
3243 
3244   case PCC_Statement:
3245   case PCC_ParenthesizedExpression:
3246   case PCC_Expression:
3247   case PCC_ForInit:
3248   case PCC_Condition:
3249     if (WantTypesInContext(CompletionContext, getLangOpts()))
3250       Results.setFilter(&ResultBuilder::IsOrdinaryName);
3251     else
3252       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3253 
3254     if (getLangOpts().CPlusPlus)
3255       MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
3256     break;
3257 
3258   case PCC_RecoveryInFunction:
3259     // Unfiltered
3260     break;
3261   }
3262 
3263   // If we are in a C++ non-static member function, check the qualifiers on
3264   // the member function to filter/prioritize the results list.
3265   if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3266     if (CurMethod->isInstance())
3267       Results.setObjectTypeQualifiers(
3268                       Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3269 
3270   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3271   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3272                      CodeCompleter->includeGlobals());
3273 
3274   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3275   Results.ExitScope();
3276 
3277   switch (CompletionContext) {
3278   case PCC_ParenthesizedExpression:
3279   case PCC_Expression:
3280   case PCC_Statement:
3281   case PCC_RecoveryInFunction:
3282     if (S->getFnParent())
3283       AddPrettyFunctionResults(PP.getLangOpts(), Results);
3284     break;
3285 
3286   case PCC_Namespace:
3287   case PCC_Class:
3288   case PCC_ObjCInterface:
3289   case PCC_ObjCImplementation:
3290   case PCC_ObjCInstanceVariableList:
3291   case PCC_Template:
3292   case PCC_MemberTemplate:
3293   case PCC_ForInit:
3294   case PCC_Condition:
3295   case PCC_Type:
3296   case PCC_LocalDeclarationSpecifiers:
3297     break;
3298   }
3299 
3300   if (CodeCompleter->includeMacros())
3301     AddMacroResults(PP, Results, false);
3302 
3303   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3304                             Results.data(),Results.size());
3305 }
3306 
3307 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3308                                        ParsedType Receiver,
3309                                        ArrayRef<IdentifierInfo *> SelIdents,
3310                                        bool AtArgumentExpression,
3311                                        bool IsSuper,
3312                                        ResultBuilder &Results);
3313 
3314 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3315                                 bool AllowNonIdentifiers,
3316                                 bool AllowNestedNameSpecifiers) {
3317   typedef CodeCompletionResult Result;
3318   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3319                         CodeCompleter->getCodeCompletionTUInfo(),
3320                         AllowNestedNameSpecifiers
3321                           ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3322                           : CodeCompletionContext::CCC_Name);
3323   Results.EnterNewScope();
3324 
3325   // Type qualifiers can come after names.
3326   Results.AddResult(Result("const"));
3327   Results.AddResult(Result("volatile"));
3328   if (getLangOpts().C99)
3329     Results.AddResult(Result("restrict"));
3330 
3331   if (getLangOpts().CPlusPlus) {
3332     if (AllowNonIdentifiers) {
3333       Results.AddResult(Result("operator"));
3334     }
3335 
3336     // Add nested-name-specifiers.
3337     if (AllowNestedNameSpecifiers) {
3338       Results.allowNestedNameSpecifiers();
3339       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3340       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3341       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3342                          CodeCompleter->includeGlobals());
3343       Results.setFilter(0);
3344     }
3345   }
3346   Results.ExitScope();
3347 
3348   // If we're in a context where we might have an expression (rather than a
3349   // declaration), and what we've seen so far is an Objective-C type that could
3350   // be a receiver of a class message, this may be a class message send with
3351   // the initial opening bracket '[' missing. Add appropriate completions.
3352   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3353       DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3354       DS.getTypeSpecType() == DeclSpec::TST_typename &&
3355       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3356       DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3357       !DS.isTypeAltiVecVector() &&
3358       S &&
3359       (S->getFlags() & Scope::DeclScope) != 0 &&
3360       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3361                         Scope::FunctionPrototypeScope |
3362                         Scope::AtCatchScope)) == 0) {
3363     ParsedType T = DS.getRepAsType();
3364     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3365       AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3366   }
3367 
3368   // Note that we intentionally suppress macro results here, since we do not
3369   // encourage using macros to produce the names of entities.
3370 
3371   HandleCodeCompleteResults(this, CodeCompleter,
3372                             Results.getCompletionContext(),
3373                             Results.data(), Results.size());
3374 }
3375 
3376 struct Sema::CodeCompleteExpressionData {
3377   CodeCompleteExpressionData(QualType PreferredType = QualType())
3378     : PreferredType(PreferredType), IntegralConstantExpression(false),
3379       ObjCCollection(false) { }
3380 
3381   QualType PreferredType;
3382   bool IntegralConstantExpression;
3383   bool ObjCCollection;
3384   SmallVector<Decl *, 4> IgnoreDecls;
3385 };
3386 
3387 /// \brief Perform code-completion in an expression context when we know what
3388 /// type we're looking for.
3389 void Sema::CodeCompleteExpression(Scope *S,
3390                                   const CodeCompleteExpressionData &Data) {
3391   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3392                         CodeCompleter->getCodeCompletionTUInfo(),
3393                         CodeCompletionContext::CCC_Expression);
3394   if (Data.ObjCCollection)
3395     Results.setFilter(&ResultBuilder::IsObjCCollection);
3396   else if (Data.IntegralConstantExpression)
3397     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3398   else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3399     Results.setFilter(&ResultBuilder::IsOrdinaryName);
3400   else
3401     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3402 
3403   if (!Data.PreferredType.isNull())
3404     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3405 
3406   // Ignore any declarations that we were told that we don't care about.
3407   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3408     Results.Ignore(Data.IgnoreDecls[I]);
3409 
3410   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3411   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3412                      CodeCompleter->includeGlobals());
3413 
3414   Results.EnterNewScope();
3415   AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3416   Results.ExitScope();
3417 
3418   bool PreferredTypeIsPointer = false;
3419   if (!Data.PreferredType.isNull())
3420     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3421       || Data.PreferredType->isMemberPointerType()
3422       || Data.PreferredType->isBlockPointerType();
3423 
3424   if (S->getFnParent() &&
3425       !Data.ObjCCollection &&
3426       !Data.IntegralConstantExpression)
3427     AddPrettyFunctionResults(PP.getLangOpts(), Results);
3428 
3429   if (CodeCompleter->includeMacros())
3430     AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3431   HandleCodeCompleteResults(this, CodeCompleter,
3432                 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3433                                       Data.PreferredType),
3434                             Results.data(),Results.size());
3435 }
3436 
3437 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3438   if (E.isInvalid())
3439     CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3440   else if (getLangOpts().ObjC1)
3441     CodeCompleteObjCInstanceMessage(S, E.take(), None, false);
3442 }
3443 
3444 /// \brief The set of properties that have already been added, referenced by
3445 /// property name.
3446 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3447 
3448 /// \brief Retrieve the container definition, if any?
3449 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3450   if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3451     if (Interface->hasDefinition())
3452       return Interface->getDefinition();
3453 
3454     return Interface;
3455   }
3456 
3457   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3458     if (Protocol->hasDefinition())
3459       return Protocol->getDefinition();
3460 
3461     return Protocol;
3462   }
3463   return Container;
3464 }
3465 
3466 static void AddObjCProperties(ObjCContainerDecl *Container,
3467                               bool AllowCategories,
3468                               bool AllowNullaryMethods,
3469                               DeclContext *CurContext,
3470                               AddedPropertiesSet &AddedProperties,
3471                               ResultBuilder &Results) {
3472   typedef CodeCompletionResult Result;
3473 
3474   // Retrieve the definition.
3475   Container = getContainerDef(Container);
3476 
3477   // Add properties in this container.
3478   for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3479                                      PEnd = Container->prop_end();
3480        P != PEnd;
3481        ++P) {
3482     if (AddedProperties.insert(P->getIdentifier()))
3483       Results.MaybeAddResult(Result(*P, Results.getBasePriority(*P), 0),
3484                              CurContext);
3485   }
3486 
3487   // Add nullary methods
3488   if (AllowNullaryMethods) {
3489     ASTContext &Context = Container->getASTContext();
3490     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3491     for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3492                                          MEnd = Container->meth_end();
3493          M != MEnd; ++M) {
3494       if (M->getSelector().isUnarySelector())
3495         if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3496           if (AddedProperties.insert(Name)) {
3497             CodeCompletionBuilder Builder(Results.getAllocator(),
3498                                           Results.getCodeCompletionTUInfo());
3499             AddResultTypeChunk(Context, Policy, *M, Builder);
3500             Builder.AddTypedTextChunk(
3501                             Results.getAllocator().CopyString(Name->getName()));
3502 
3503             Results.MaybeAddResult(Result(Builder.TakeString(), *M,
3504                                   CCP_MemberDeclaration + CCD_MethodAsProperty),
3505                                           CurContext);
3506           }
3507     }
3508   }
3509 
3510 
3511   // Add properties in referenced protocols.
3512   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3513     for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3514                                           PEnd = Protocol->protocol_end();
3515          P != PEnd; ++P)
3516       AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3517                         AddedProperties, Results);
3518   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3519     if (AllowCategories) {
3520       // Look through categories.
3521       for (ObjCInterfaceDecl::known_categories_iterator
3522              Cat = IFace->known_categories_begin(),
3523              CatEnd = IFace->known_categories_end();
3524            Cat != CatEnd; ++Cat)
3525         AddObjCProperties(*Cat, AllowCategories, AllowNullaryMethods,
3526                           CurContext, AddedProperties, Results);
3527     }
3528 
3529     // Look through protocols.
3530     for (ObjCInterfaceDecl::all_protocol_iterator
3531          I = IFace->all_referenced_protocol_begin(),
3532          E = IFace->all_referenced_protocol_end(); I != E; ++I)
3533       AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3534                         AddedProperties, Results);
3535 
3536     // Look in the superclass.
3537     if (IFace->getSuperClass())
3538       AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3539                         AllowNullaryMethods, CurContext,
3540                         AddedProperties, Results);
3541   } else if (const ObjCCategoryDecl *Category
3542                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
3543     // Look through protocols.
3544     for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3545                                           PEnd = Category->protocol_end();
3546          P != PEnd; ++P)
3547       AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3548                         AddedProperties, Results);
3549   }
3550 }
3551 
3552 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3553                                            SourceLocation OpLoc,
3554                                            bool IsArrow) {
3555   if (!Base || !CodeCompleter)
3556     return;
3557 
3558   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3559   if (ConvertedBase.isInvalid())
3560     return;
3561   Base = ConvertedBase.get();
3562 
3563   typedef CodeCompletionResult Result;
3564 
3565   QualType BaseType = Base->getType();
3566 
3567   if (IsArrow) {
3568     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3569       BaseType = Ptr->getPointeeType();
3570     else if (BaseType->isObjCObjectPointerType())
3571       /*Do nothing*/ ;
3572     else
3573       return;
3574   }
3575 
3576   enum CodeCompletionContext::Kind contextKind;
3577 
3578   if (IsArrow) {
3579     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3580   }
3581   else {
3582     if (BaseType->isObjCObjectPointerType() ||
3583         BaseType->isObjCObjectOrInterfaceType()) {
3584       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3585     }
3586     else {
3587       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3588     }
3589   }
3590 
3591   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3592                         CodeCompleter->getCodeCompletionTUInfo(),
3593                   CodeCompletionContext(contextKind,
3594                                         BaseType),
3595                         &ResultBuilder::IsMember);
3596   Results.EnterNewScope();
3597   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3598     // Indicate that we are performing a member access, and the cv-qualifiers
3599     // for the base object type.
3600     Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3601 
3602     // Access to a C/C++ class, struct, or union.
3603     Results.allowNestedNameSpecifiers();
3604     CodeCompletionDeclConsumer Consumer(Results, CurContext);
3605     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3606                        CodeCompleter->includeGlobals());
3607 
3608     if (getLangOpts().CPlusPlus) {
3609       if (!Results.empty()) {
3610         // The "template" keyword can follow "->" or "." in the grammar.
3611         // However, we only want to suggest the template keyword if something
3612         // is dependent.
3613         bool IsDependent = BaseType->isDependentType();
3614         if (!IsDependent) {
3615           for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3616             if (DeclContext *Ctx = DepScope->getEntity()) {
3617               IsDependent = Ctx->isDependentContext();
3618               break;
3619             }
3620         }
3621 
3622         if (IsDependent)
3623           Results.AddResult(Result("template"));
3624       }
3625     }
3626   } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3627     // Objective-C property reference.
3628     AddedPropertiesSet AddedProperties;
3629 
3630     // Add property results based on our interface.
3631     const ObjCObjectPointerType *ObjCPtr
3632       = BaseType->getAsObjCInterfacePointerType();
3633     assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3634     AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3635                       /*AllowNullaryMethods=*/true, CurContext,
3636                       AddedProperties, Results);
3637 
3638     // Add properties from the protocols in a qualified interface.
3639     for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3640                                               E = ObjCPtr->qual_end();
3641          I != E; ++I)
3642       AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3643                         AddedProperties, Results);
3644   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3645              (!IsArrow && BaseType->isObjCObjectType())) {
3646     // Objective-C instance variable access.
3647     ObjCInterfaceDecl *Class = 0;
3648     if (const ObjCObjectPointerType *ObjCPtr
3649                                     = BaseType->getAs<ObjCObjectPointerType>())
3650       Class = ObjCPtr->getInterfaceDecl();
3651     else
3652       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3653 
3654     // Add all ivars from this class and its superclasses.
3655     if (Class) {
3656       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3657       Results.setFilter(&ResultBuilder::IsObjCIvar);
3658       LookupVisibleDecls(Class, LookupMemberName, Consumer,
3659                          CodeCompleter->includeGlobals());
3660     }
3661   }
3662 
3663   // FIXME: How do we cope with isa?
3664 
3665   Results.ExitScope();
3666 
3667   // Hand off the results found for code completion.
3668   HandleCodeCompleteResults(this, CodeCompleter,
3669                             Results.getCompletionContext(),
3670                             Results.data(),Results.size());
3671 }
3672 
3673 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3674   if (!CodeCompleter)
3675     return;
3676 
3677   ResultBuilder::LookupFilter Filter = 0;
3678   enum CodeCompletionContext::Kind ContextKind
3679     = CodeCompletionContext::CCC_Other;
3680   switch ((DeclSpec::TST)TagSpec) {
3681   case DeclSpec::TST_enum:
3682     Filter = &ResultBuilder::IsEnum;
3683     ContextKind = CodeCompletionContext::CCC_EnumTag;
3684     break;
3685 
3686   case DeclSpec::TST_union:
3687     Filter = &ResultBuilder::IsUnion;
3688     ContextKind = CodeCompletionContext::CCC_UnionTag;
3689     break;
3690 
3691   case DeclSpec::TST_struct:
3692   case DeclSpec::TST_class:
3693   case DeclSpec::TST_interface:
3694     Filter = &ResultBuilder::IsClassOrStruct;
3695     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3696     break;
3697 
3698   default:
3699     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
3700   }
3701 
3702   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3703                         CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
3704   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3705 
3706   // First pass: look for tags.
3707   Results.setFilter(Filter);
3708   LookupVisibleDecls(S, LookupTagName, Consumer,
3709                      CodeCompleter->includeGlobals());
3710 
3711   if (CodeCompleter->includeGlobals()) {
3712     // Second pass: look for nested name specifiers.
3713     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3714     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3715   }
3716 
3717   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3718                             Results.data(),Results.size());
3719 }
3720 
3721 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3722   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3723                         CodeCompleter->getCodeCompletionTUInfo(),
3724                         CodeCompletionContext::CCC_TypeQualifiers);
3725   Results.EnterNewScope();
3726   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3727     Results.AddResult("const");
3728   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3729     Results.AddResult("volatile");
3730   if (getLangOpts().C99 &&
3731       !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3732     Results.AddResult("restrict");
3733   if (getLangOpts().C11 &&
3734       !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3735     Results.AddResult("_Atomic");
3736   Results.ExitScope();
3737   HandleCodeCompleteResults(this, CodeCompleter,
3738                             Results.getCompletionContext(),
3739                             Results.data(), Results.size());
3740 }
3741 
3742 void Sema::CodeCompleteCase(Scope *S) {
3743   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3744     return;
3745 
3746   SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3747   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3748   if (!type->isEnumeralType()) {
3749     CodeCompleteExpressionData Data(type);
3750     Data.IntegralConstantExpression = true;
3751     CodeCompleteExpression(S, Data);
3752     return;
3753   }
3754 
3755   // Code-complete the cases of a switch statement over an enumeration type
3756   // by providing the list of
3757   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
3758   if (EnumDecl *Def = Enum->getDefinition())
3759     Enum = Def;
3760 
3761   // Determine which enumerators we have already seen in the switch statement.
3762   // FIXME: Ideally, we would also be able to look *past* the code-completion
3763   // token, in case we are code-completing in the middle of the switch and not
3764   // at the end. However, we aren't able to do so at the moment.
3765   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3766   NestedNameSpecifier *Qualifier = 0;
3767   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3768        SC = SC->getNextSwitchCase()) {
3769     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3770     if (!Case)
3771       continue;
3772 
3773     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3774     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3775       if (EnumConstantDecl *Enumerator
3776             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3777         // We look into the AST of the case statement to determine which
3778         // enumerator was named. Alternatively, we could compute the value of
3779         // the integral constant expression, then compare it against the
3780         // values of each enumerator. However, value-based approach would not
3781         // work as well with C++ templates where enumerators declared within a
3782         // template are type- and value-dependent.
3783         EnumeratorsSeen.insert(Enumerator);
3784 
3785         // If this is a qualified-id, keep track of the nested-name-specifier
3786         // so that we can reproduce it as part of code completion, e.g.,
3787         //
3788         //   switch (TagD.getKind()) {
3789         //     case TagDecl::TK_enum:
3790         //       break;
3791         //     case XXX
3792         //
3793         // At the XXX, our completions are TagDecl::TK_union,
3794         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3795         // TK_struct, and TK_class.
3796         Qualifier = DRE->getQualifier();
3797       }
3798   }
3799 
3800   if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3801     // If there are no prior enumerators in C++, check whether we have to
3802     // qualify the names of the enumerators that we suggest, because they
3803     // may not be visible in this scope.
3804     Qualifier = getRequiredQualification(Context, CurContext, Enum);
3805   }
3806 
3807   // Add any enumerators that have not yet been mentioned.
3808   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3809                         CodeCompleter->getCodeCompletionTUInfo(),
3810                         CodeCompletionContext::CCC_Expression);
3811   Results.EnterNewScope();
3812   for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3813                                   EEnd = Enum->enumerator_end();
3814        E != EEnd; ++E) {
3815     if (EnumeratorsSeen.count(*E))
3816       continue;
3817 
3818     CodeCompletionResult R(*E, CCP_EnumInCase, Qualifier);
3819     Results.AddResult(R, CurContext, 0, false);
3820   }
3821   Results.ExitScope();
3822 
3823   //We need to make sure we're setting the right context,
3824   //so only say we include macros if the code completer says we do
3825   enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3826   if (CodeCompleter->includeMacros()) {
3827     AddMacroResults(PP, Results, false);
3828     kind = CodeCompletionContext::CCC_OtherWithMacros;
3829   }
3830 
3831   HandleCodeCompleteResults(this, CodeCompleter,
3832                             kind,
3833                             Results.data(),Results.size());
3834 }
3835 
3836 namespace {
3837   struct IsBetterOverloadCandidate {
3838     Sema &S;
3839     SourceLocation Loc;
3840 
3841   public:
3842     explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3843       : S(S), Loc(Loc) { }
3844 
3845     bool
3846     operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
3847       return isBetterOverloadCandidate(S, X, Y, Loc);
3848     }
3849   };
3850 }
3851 
3852 static bool anyNullArguments(ArrayRef<Expr *> Args) {
3853   if (Args.size() && !Args.data())
3854     return true;
3855 
3856   for (unsigned I = 0; I != Args.size(); ++I)
3857     if (!Args[I])
3858       return true;
3859 
3860   return false;
3861 }
3862 
3863 void Sema::CodeCompleteCall(Scope *S, Expr *FnIn, ArrayRef<Expr *> Args) {
3864   if (!CodeCompleter)
3865     return;
3866 
3867   // When we're code-completing for a call, we fall back to ordinary
3868   // name code-completion whenever we can't produce specific
3869   // results. We may want to revisit this strategy in the future,
3870   // e.g., by merging the two kinds of results.
3871 
3872   Expr *Fn = (Expr *)FnIn;
3873 
3874   // Ignore type-dependent call expressions entirely.
3875   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3876       Expr::hasAnyTypeDependentArguments(Args)) {
3877     CodeCompleteOrdinaryName(S, PCC_Expression);
3878     return;
3879   }
3880 
3881   // Build an overload candidate set based on the functions we find.
3882   SourceLocation Loc = Fn->getExprLoc();
3883   OverloadCandidateSet CandidateSet(Loc);
3884 
3885   // FIXME: What if we're calling something that isn't a function declaration?
3886   // FIXME: What if we're calling a pseudo-destructor?
3887   // FIXME: What if we're calling a member function?
3888 
3889   typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3890   SmallVector<ResultCandidate, 8> Results;
3891 
3892   Expr *NakedFn = Fn->IgnoreParenCasts();
3893   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3894     AddOverloadedCallCandidates(ULE, Args, CandidateSet,
3895                                 /*PartialOverloading=*/ true);
3896   else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3897     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
3898     if (FDecl) {
3899       if (!getLangOpts().CPlusPlus ||
3900           !FDecl->getType()->getAs<FunctionProtoType>())
3901         Results.push_back(ResultCandidate(FDecl));
3902       else
3903         // FIXME: access?
3904         AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
3905                              CandidateSet, false, /*PartialOverloading*/true);
3906     }
3907   }
3908 
3909   QualType ParamType;
3910 
3911   if (!CandidateSet.empty()) {
3912     // Sort the overload candidate set by placing the best overloads first.
3913     std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
3914                      IsBetterOverloadCandidate(*this, Loc));
3915 
3916     // Add the remaining viable overload candidates as code-completion reslults.
3917     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3918                                      CandEnd = CandidateSet.end();
3919          Cand != CandEnd; ++Cand) {
3920       if (Cand->Viable)
3921         Results.push_back(ResultCandidate(Cand->Function));
3922     }
3923 
3924     // From the viable candidates, try to determine the type of this parameter.
3925     for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3926       if (const FunctionType *FType = Results[I].getFunctionType())
3927         if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3928           if (Args.size() < Proto->getNumParams()) {
3929             if (ParamType.isNull())
3930               ParamType = Proto->getParamType(Args.size());
3931             else if (!Context.hasSameUnqualifiedType(
3932                           ParamType.getNonReferenceType(),
3933                           Proto->getParamType(Args.size())
3934                               .getNonReferenceType())) {
3935               ParamType = QualType();
3936               break;
3937             }
3938           }
3939     }
3940   } else {
3941     // Try to determine the parameter type from the type of the expression
3942     // being called.
3943     QualType FunctionType = Fn->getType();
3944     if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3945       FunctionType = Ptr->getPointeeType();
3946     else if (const BlockPointerType *BlockPtr
3947                                     = FunctionType->getAs<BlockPointerType>())
3948       FunctionType = BlockPtr->getPointeeType();
3949     else if (const MemberPointerType *MemPtr
3950                                     = FunctionType->getAs<MemberPointerType>())
3951       FunctionType = MemPtr->getPointeeType();
3952 
3953     if (const FunctionProtoType *Proto
3954                                   = FunctionType->getAs<FunctionProtoType>()) {
3955       if (Args.size() < Proto->getNumParams())
3956         ParamType = Proto->getParamType(Args.size());
3957     }
3958   }
3959 
3960   if (ParamType.isNull())
3961     CodeCompleteOrdinaryName(S, PCC_Expression);
3962   else
3963     CodeCompleteExpression(S, ParamType);
3964 
3965   if (!Results.empty())
3966     CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
3967                                              Results.size());
3968 }
3969 
3970 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3971   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3972   if (!VD) {
3973     CodeCompleteOrdinaryName(S, PCC_Expression);
3974     return;
3975   }
3976 
3977   CodeCompleteExpression(S, VD->getType());
3978 }
3979 
3980 void Sema::CodeCompleteReturn(Scope *S) {
3981   QualType ResultType;
3982   if (isa<BlockDecl>(CurContext)) {
3983     if (BlockScopeInfo *BSI = getCurBlock())
3984       ResultType = BSI->ReturnType;
3985   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3986     ResultType = Function->getResultType();
3987   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3988     ResultType = Method->getResultType();
3989 
3990   if (ResultType.isNull())
3991     CodeCompleteOrdinaryName(S, PCC_Expression);
3992   else
3993     CodeCompleteExpression(S, ResultType);
3994 }
3995 
3996 void Sema::CodeCompleteAfterIf(Scope *S) {
3997   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3998                         CodeCompleter->getCodeCompletionTUInfo(),
3999                         mapCodeCompletionContext(*this, PCC_Statement));
4000   Results.setFilter(&ResultBuilder::IsOrdinaryName);
4001   Results.EnterNewScope();
4002 
4003   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4004   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4005                      CodeCompleter->includeGlobals());
4006 
4007   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4008 
4009   // "else" block
4010   CodeCompletionBuilder Builder(Results.getAllocator(),
4011                                 Results.getCodeCompletionTUInfo());
4012   Builder.AddTypedTextChunk("else");
4013   if (Results.includeCodePatterns()) {
4014     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4015     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4016     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4017     Builder.AddPlaceholderChunk("statements");
4018     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4019     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4020   }
4021   Results.AddResult(Builder.TakeString());
4022 
4023   // "else if" block
4024   Builder.AddTypedTextChunk("else");
4025   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4026   Builder.AddTextChunk("if");
4027   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4028   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4029   if (getLangOpts().CPlusPlus)
4030     Builder.AddPlaceholderChunk("condition");
4031   else
4032     Builder.AddPlaceholderChunk("expression");
4033   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4034   if (Results.includeCodePatterns()) {
4035     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4036     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4037     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4038     Builder.AddPlaceholderChunk("statements");
4039     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4040     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4041   }
4042   Results.AddResult(Builder.TakeString());
4043 
4044   Results.ExitScope();
4045 
4046   if (S->getFnParent())
4047     AddPrettyFunctionResults(PP.getLangOpts(), Results);
4048 
4049   if (CodeCompleter->includeMacros())
4050     AddMacroResults(PP, Results, false);
4051 
4052   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4053                             Results.data(),Results.size());
4054 }
4055 
4056 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4057   if (LHS)
4058     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4059   else
4060     CodeCompleteOrdinaryName(S, PCC_Expression);
4061 }
4062 
4063 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4064                                    bool EnteringContext) {
4065   if (!SS.getScopeRep() || !CodeCompleter)
4066     return;
4067 
4068   DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4069   if (!Ctx)
4070     return;
4071 
4072   // Try to instantiate any non-dependent declaration contexts before
4073   // we look in them.
4074   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4075     return;
4076 
4077   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4078                         CodeCompleter->getCodeCompletionTUInfo(),
4079                         CodeCompletionContext::CCC_Name);
4080   Results.EnterNewScope();
4081 
4082   // The "template" keyword can follow "::" in the grammar, but only
4083   // put it into the grammar if the nested-name-specifier is dependent.
4084   NestedNameSpecifier *NNS = SS.getScopeRep();
4085   if (!Results.empty() && NNS->isDependent())
4086     Results.AddResult("template");
4087 
4088   // Add calls to overridden virtual functions, if there are any.
4089   //
4090   // FIXME: This isn't wonderful, because we don't know whether we're actually
4091   // in a context that permits expressions. This is a general issue with
4092   // qualified-id completions.
4093   if (!EnteringContext)
4094     MaybeAddOverrideCalls(*this, Ctx, Results);
4095   Results.ExitScope();
4096 
4097   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4098   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4099 
4100   HandleCodeCompleteResults(this, CodeCompleter,
4101                             Results.getCompletionContext(),
4102                             Results.data(),Results.size());
4103 }
4104 
4105 void Sema::CodeCompleteUsing(Scope *S) {
4106   if (!CodeCompleter)
4107     return;
4108 
4109   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4110                         CodeCompleter->getCodeCompletionTUInfo(),
4111                         CodeCompletionContext::CCC_PotentiallyQualifiedName,
4112                         &ResultBuilder::IsNestedNameSpecifier);
4113   Results.EnterNewScope();
4114 
4115   // If we aren't in class scope, we could see the "namespace" keyword.
4116   if (!S->isClassScope())
4117     Results.AddResult(CodeCompletionResult("namespace"));
4118 
4119   // After "using", we can see anything that would start a
4120   // nested-name-specifier.
4121   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4122   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4123                      CodeCompleter->includeGlobals());
4124   Results.ExitScope();
4125 
4126   HandleCodeCompleteResults(this, CodeCompleter,
4127                             CodeCompletionContext::CCC_PotentiallyQualifiedName,
4128                             Results.data(),Results.size());
4129 }
4130 
4131 void Sema::CodeCompleteUsingDirective(Scope *S) {
4132   if (!CodeCompleter)
4133     return;
4134 
4135   // After "using namespace", we expect to see a namespace name or namespace
4136   // alias.
4137   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4138                         CodeCompleter->getCodeCompletionTUInfo(),
4139                         CodeCompletionContext::CCC_Namespace,
4140                         &ResultBuilder::IsNamespaceOrAlias);
4141   Results.EnterNewScope();
4142   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4143   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4144                      CodeCompleter->includeGlobals());
4145   Results.ExitScope();
4146   HandleCodeCompleteResults(this, CodeCompleter,
4147                             CodeCompletionContext::CCC_Namespace,
4148                             Results.data(),Results.size());
4149 }
4150 
4151 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
4152   if (!CodeCompleter)
4153     return;
4154 
4155   DeclContext *Ctx = S->getEntity();
4156   if (!S->getParent())
4157     Ctx = Context.getTranslationUnitDecl();
4158 
4159   bool SuppressedGlobalResults
4160     = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4161 
4162   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4163                         CodeCompleter->getCodeCompletionTUInfo(),
4164                         SuppressedGlobalResults
4165                           ? CodeCompletionContext::CCC_Namespace
4166                           : CodeCompletionContext::CCC_Other,
4167                         &ResultBuilder::IsNamespace);
4168 
4169   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4170     // We only want to see those namespaces that have already been defined
4171     // within this scope, because its likely that the user is creating an
4172     // extended namespace declaration. Keep track of the most recent
4173     // definition of each namespace.
4174     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4175     for (DeclContext::specific_decl_iterator<NamespaceDecl>
4176          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4177          NS != NSEnd; ++NS)
4178       OrigToLatest[NS->getOriginalNamespace()] = *NS;
4179 
4180     // Add the most recent definition (or extended definition) of each
4181     // namespace to the list of results.
4182     Results.EnterNewScope();
4183     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4184               NS = OrigToLatest.begin(),
4185            NSEnd = OrigToLatest.end();
4186          NS != NSEnd; ++NS)
4187       Results.AddResult(CodeCompletionResult(
4188                           NS->second, Results.getBasePriority(NS->second), 0),
4189                         CurContext, 0, false);
4190     Results.ExitScope();
4191   }
4192 
4193   HandleCodeCompleteResults(this, CodeCompleter,
4194                             Results.getCompletionContext(),
4195                             Results.data(),Results.size());
4196 }
4197 
4198 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
4199   if (!CodeCompleter)
4200     return;
4201 
4202   // After "namespace", we expect to see a namespace or alias.
4203   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4204                         CodeCompleter->getCodeCompletionTUInfo(),
4205                         CodeCompletionContext::CCC_Namespace,
4206                         &ResultBuilder::IsNamespaceOrAlias);
4207   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4208   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4209                      CodeCompleter->includeGlobals());
4210   HandleCodeCompleteResults(this, CodeCompleter,
4211                             Results.getCompletionContext(),
4212                             Results.data(),Results.size());
4213 }
4214 
4215 void Sema::CodeCompleteOperatorName(Scope *S) {
4216   if (!CodeCompleter)
4217     return;
4218 
4219   typedef CodeCompletionResult Result;
4220   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4221                         CodeCompleter->getCodeCompletionTUInfo(),
4222                         CodeCompletionContext::CCC_Type,
4223                         &ResultBuilder::IsType);
4224   Results.EnterNewScope();
4225 
4226   // Add the names of overloadable operators.
4227 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
4228   if (std::strcmp(Spelling, "?"))                                                  \
4229     Results.AddResult(Result(Spelling));
4230 #include "clang/Basic/OperatorKinds.def"
4231 
4232   // Add any type names visible from the current scope
4233   Results.allowNestedNameSpecifiers();
4234   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4235   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4236                      CodeCompleter->includeGlobals());
4237 
4238   // Add any type specifiers
4239   AddTypeSpecifierResults(getLangOpts(), Results);
4240   Results.ExitScope();
4241 
4242   HandleCodeCompleteResults(this, CodeCompleter,
4243                             CodeCompletionContext::CCC_Type,
4244                             Results.data(),Results.size());
4245 }
4246 
4247 void Sema::CodeCompleteConstructorInitializer(
4248                               Decl *ConstructorD,
4249                               ArrayRef <CXXCtorInitializer *> Initializers) {
4250   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4251   CXXConstructorDecl *Constructor
4252     = static_cast<CXXConstructorDecl *>(ConstructorD);
4253   if (!Constructor)
4254     return;
4255 
4256   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4257                         CodeCompleter->getCodeCompletionTUInfo(),
4258                         CodeCompletionContext::CCC_PotentiallyQualifiedName);
4259   Results.EnterNewScope();
4260 
4261   // Fill in any already-initialized fields or base classes.
4262   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4263   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4264   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4265     if (Initializers[I]->isBaseInitializer())
4266       InitializedBases.insert(
4267         Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4268     else
4269       InitializedFields.insert(cast<FieldDecl>(
4270                                Initializers[I]->getAnyMember()));
4271   }
4272 
4273   // Add completions for base classes.
4274   CodeCompletionBuilder Builder(Results.getAllocator(),
4275                                 Results.getCodeCompletionTUInfo());
4276   bool SawLastInitializer = Initializers.empty();
4277   CXXRecordDecl *ClassDecl = Constructor->getParent();
4278   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4279                                        BaseEnd = ClassDecl->bases_end();
4280        Base != BaseEnd; ++Base) {
4281     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4282       SawLastInitializer
4283         = !Initializers.empty() &&
4284           Initializers.back()->isBaseInitializer() &&
4285           Context.hasSameUnqualifiedType(Base->getType(),
4286                QualType(Initializers.back()->getBaseClass(), 0));
4287       continue;
4288     }
4289 
4290     Builder.AddTypedTextChunk(
4291                Results.getAllocator().CopyString(
4292                           Base->getType().getAsString(Policy)));
4293     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4294     Builder.AddPlaceholderChunk("args");
4295     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4296     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4297                                    SawLastInitializer? CCP_NextInitializer
4298                                                      : CCP_MemberDeclaration));
4299     SawLastInitializer = false;
4300   }
4301 
4302   // Add completions for virtual base classes.
4303   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4304                                        BaseEnd = ClassDecl->vbases_end();
4305        Base != BaseEnd; ++Base) {
4306     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4307       SawLastInitializer
4308         = !Initializers.empty() &&
4309           Initializers.back()->isBaseInitializer() &&
4310           Context.hasSameUnqualifiedType(Base->getType(),
4311                QualType(Initializers.back()->getBaseClass(), 0));
4312       continue;
4313     }
4314 
4315     Builder.AddTypedTextChunk(
4316                Builder.getAllocator().CopyString(
4317                           Base->getType().getAsString(Policy)));
4318     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4319     Builder.AddPlaceholderChunk("args");
4320     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4321     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4322                                    SawLastInitializer? CCP_NextInitializer
4323                                                      : CCP_MemberDeclaration));
4324     SawLastInitializer = false;
4325   }
4326 
4327   // Add completions for members.
4328   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4329                                   FieldEnd = ClassDecl->field_end();
4330        Field != FieldEnd; ++Field) {
4331     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4332       SawLastInitializer
4333         = !Initializers.empty() &&
4334           Initializers.back()->isAnyMemberInitializer() &&
4335           Initializers.back()->getAnyMember() == *Field;
4336       continue;
4337     }
4338 
4339     if (!Field->getDeclName())
4340       continue;
4341 
4342     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4343                                          Field->getIdentifier()->getName()));
4344     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4345     Builder.AddPlaceholderChunk("args");
4346     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4347     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4348                                    SawLastInitializer? CCP_NextInitializer
4349                                                      : CCP_MemberDeclaration,
4350                                            CXCursor_MemberRef,
4351                                            CXAvailability_Available,
4352                                            *Field));
4353     SawLastInitializer = false;
4354   }
4355   Results.ExitScope();
4356 
4357   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4358                             Results.data(), Results.size());
4359 }
4360 
4361 /// \brief Determine whether this scope denotes a namespace.
4362 static bool isNamespaceScope(Scope *S) {
4363   DeclContext *DC = S->getEntity();
4364   if (!DC)
4365     return false;
4366 
4367   return DC->isFileContext();
4368 }
4369 
4370 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4371                                         bool AfterAmpersand) {
4372   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4373                         CodeCompleter->getCodeCompletionTUInfo(),
4374                         CodeCompletionContext::CCC_Other);
4375   Results.EnterNewScope();
4376 
4377   // Note what has already been captured.
4378   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4379   bool IncludedThis = false;
4380   for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4381                                              CEnd = Intro.Captures.end();
4382        C != CEnd; ++C) {
4383     if (C->Kind == LCK_This) {
4384       IncludedThis = true;
4385       continue;
4386     }
4387 
4388     Known.insert(C->Id);
4389   }
4390 
4391   // Look for other capturable variables.
4392   for (; S && !isNamespaceScope(S); S = S->getParent()) {
4393     for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4394          D != DEnd; ++D) {
4395       VarDecl *Var = dyn_cast<VarDecl>(*D);
4396       if (!Var ||
4397           !Var->hasLocalStorage() ||
4398           Var->hasAttr<BlocksAttr>())
4399         continue;
4400 
4401       if (Known.insert(Var->getIdentifier()))
4402         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4403                           CurContext, 0, false);
4404     }
4405   }
4406 
4407   // Add 'this', if it would be valid.
4408   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4409     addThisCompletion(*this, Results);
4410 
4411   Results.ExitScope();
4412 
4413   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4414                             Results.data(), Results.size());
4415 }
4416 
4417 /// Macro that optionally prepends an "@" to the string literal passed in via
4418 /// Keyword, depending on whether NeedAt is true or false.
4419 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4420 
4421 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4422                                          ResultBuilder &Results,
4423                                          bool NeedAt) {
4424   typedef CodeCompletionResult Result;
4425   // Since we have an implementation, we can end it.
4426   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4427 
4428   CodeCompletionBuilder Builder(Results.getAllocator(),
4429                                 Results.getCodeCompletionTUInfo());
4430   if (LangOpts.ObjC2) {
4431     // @dynamic
4432     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4433     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4434     Builder.AddPlaceholderChunk("property");
4435     Results.AddResult(Result(Builder.TakeString()));
4436 
4437     // @synthesize
4438     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4439     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4440     Builder.AddPlaceholderChunk("property");
4441     Results.AddResult(Result(Builder.TakeString()));
4442   }
4443 }
4444 
4445 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4446                                     ResultBuilder &Results,
4447                                     bool NeedAt) {
4448   typedef CodeCompletionResult Result;
4449 
4450   // Since we have an interface or protocol, we can end it.
4451   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4452 
4453   if (LangOpts.ObjC2) {
4454     // @property
4455     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
4456 
4457     // @required
4458     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
4459 
4460     // @optional
4461     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
4462   }
4463 }
4464 
4465 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4466   typedef CodeCompletionResult Result;
4467   CodeCompletionBuilder Builder(Results.getAllocator(),
4468                                 Results.getCodeCompletionTUInfo());
4469 
4470   // @class name ;
4471   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
4472   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4473   Builder.AddPlaceholderChunk("name");
4474   Results.AddResult(Result(Builder.TakeString()));
4475 
4476   if (Results.includeCodePatterns()) {
4477     // @interface name
4478     // FIXME: Could introduce the whole pattern, including superclasses and
4479     // such.
4480     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
4481     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4482     Builder.AddPlaceholderChunk("class");
4483     Results.AddResult(Result(Builder.TakeString()));
4484 
4485     // @protocol name
4486     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4487     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4488     Builder.AddPlaceholderChunk("protocol");
4489     Results.AddResult(Result(Builder.TakeString()));
4490 
4491     // @implementation name
4492     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
4493     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4494     Builder.AddPlaceholderChunk("class");
4495     Results.AddResult(Result(Builder.TakeString()));
4496   }
4497 
4498   // @compatibility_alias name
4499   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
4500   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4501   Builder.AddPlaceholderChunk("alias");
4502   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4503   Builder.AddPlaceholderChunk("class");
4504   Results.AddResult(Result(Builder.TakeString()));
4505 
4506   if (Results.getSema().getLangOpts().Modules) {
4507     // @import name
4508     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4509     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4510     Builder.AddPlaceholderChunk("module");
4511     Results.AddResult(Result(Builder.TakeString()));
4512   }
4513 }
4514 
4515 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4516   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4517                         CodeCompleter->getCodeCompletionTUInfo(),
4518                         CodeCompletionContext::CCC_Other);
4519   Results.EnterNewScope();
4520   if (isa<ObjCImplDecl>(CurContext))
4521     AddObjCImplementationResults(getLangOpts(), Results, false);
4522   else if (CurContext->isObjCContainer())
4523     AddObjCInterfaceResults(getLangOpts(), Results, false);
4524   else
4525     AddObjCTopLevelResults(Results, false);
4526   Results.ExitScope();
4527   HandleCodeCompleteResults(this, CodeCompleter,
4528                             CodeCompletionContext::CCC_Other,
4529                             Results.data(),Results.size());
4530 }
4531 
4532 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
4533   typedef CodeCompletionResult Result;
4534   CodeCompletionBuilder Builder(Results.getAllocator(),
4535                                 Results.getCodeCompletionTUInfo());
4536 
4537   // @encode ( type-name )
4538   const char *EncodeType = "char[]";
4539   if (Results.getSema().getLangOpts().CPlusPlus ||
4540       Results.getSema().getLangOpts().ConstStrings)
4541     EncodeType = "const char[]";
4542   Builder.AddResultTypeChunk(EncodeType);
4543   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
4544   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4545   Builder.AddPlaceholderChunk("type-name");
4546   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4547   Results.AddResult(Result(Builder.TakeString()));
4548 
4549   // @protocol ( protocol-name )
4550   Builder.AddResultTypeChunk("Protocol *");
4551   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4552   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4553   Builder.AddPlaceholderChunk("protocol-name");
4554   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4555   Results.AddResult(Result(Builder.TakeString()));
4556 
4557   // @selector ( selector )
4558   Builder.AddResultTypeChunk("SEL");
4559   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
4560   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4561   Builder.AddPlaceholderChunk("selector");
4562   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4563   Results.AddResult(Result(Builder.TakeString()));
4564 
4565   // @"string"
4566   Builder.AddResultTypeChunk("NSString *");
4567   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4568   Builder.AddPlaceholderChunk("string");
4569   Builder.AddTextChunk("\"");
4570   Results.AddResult(Result(Builder.TakeString()));
4571 
4572   // @[objects, ...]
4573   Builder.AddResultTypeChunk("NSArray *");
4574   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
4575   Builder.AddPlaceholderChunk("objects, ...");
4576   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4577   Results.AddResult(Result(Builder.TakeString()));
4578 
4579   // @{key : object, ...}
4580   Builder.AddResultTypeChunk("NSDictionary *");
4581   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
4582   Builder.AddPlaceholderChunk("key");
4583   Builder.AddChunk(CodeCompletionString::CK_Colon);
4584   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4585   Builder.AddPlaceholderChunk("object, ...");
4586   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4587   Results.AddResult(Result(Builder.TakeString()));
4588 
4589   // @(expression)
4590   Builder.AddResultTypeChunk("id");
4591   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
4592   Builder.AddPlaceholderChunk("expression");
4593   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4594   Results.AddResult(Result(Builder.TakeString()));
4595 }
4596 
4597 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
4598   typedef CodeCompletionResult Result;
4599   CodeCompletionBuilder Builder(Results.getAllocator(),
4600                                 Results.getCodeCompletionTUInfo());
4601 
4602   if (Results.includeCodePatterns()) {
4603     // @try { statements } @catch ( declaration ) { statements } @finally
4604     //   { statements }
4605     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
4606     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4607     Builder.AddPlaceholderChunk("statements");
4608     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4609     Builder.AddTextChunk("@catch");
4610     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4611     Builder.AddPlaceholderChunk("parameter");
4612     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4613     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4614     Builder.AddPlaceholderChunk("statements");
4615     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4616     Builder.AddTextChunk("@finally");
4617     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4618     Builder.AddPlaceholderChunk("statements");
4619     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4620     Results.AddResult(Result(Builder.TakeString()));
4621   }
4622 
4623   // @throw
4624   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
4625   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4626   Builder.AddPlaceholderChunk("expression");
4627   Results.AddResult(Result(Builder.TakeString()));
4628 
4629   if (Results.includeCodePatterns()) {
4630     // @synchronized ( expression ) { statements }
4631     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
4632     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4633     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4634     Builder.AddPlaceholderChunk("expression");
4635     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4636     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4637     Builder.AddPlaceholderChunk("statements");
4638     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4639     Results.AddResult(Result(Builder.TakeString()));
4640   }
4641 }
4642 
4643 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
4644                                      ResultBuilder &Results,
4645                                      bool NeedAt) {
4646   typedef CodeCompletionResult Result;
4647   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4648   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4649   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
4650   if (LangOpts.ObjC2)
4651     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
4652 }
4653 
4654 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
4655   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4656                         CodeCompleter->getCodeCompletionTUInfo(),
4657                         CodeCompletionContext::CCC_Other);
4658   Results.EnterNewScope();
4659   AddObjCVisibilityResults(getLangOpts(), Results, false);
4660   Results.ExitScope();
4661   HandleCodeCompleteResults(this, CodeCompleter,
4662                             CodeCompletionContext::CCC_Other,
4663                             Results.data(),Results.size());
4664 }
4665 
4666 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
4667   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4668                         CodeCompleter->getCodeCompletionTUInfo(),
4669                         CodeCompletionContext::CCC_Other);
4670   Results.EnterNewScope();
4671   AddObjCStatementResults(Results, false);
4672   AddObjCExpressionResults(Results, false);
4673   Results.ExitScope();
4674   HandleCodeCompleteResults(this, CodeCompleter,
4675                             CodeCompletionContext::CCC_Other,
4676                             Results.data(),Results.size());
4677 }
4678 
4679 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
4680   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4681                         CodeCompleter->getCodeCompletionTUInfo(),
4682                         CodeCompletionContext::CCC_Other);
4683   Results.EnterNewScope();
4684   AddObjCExpressionResults(Results, false);
4685   Results.ExitScope();
4686   HandleCodeCompleteResults(this, CodeCompleter,
4687                             CodeCompletionContext::CCC_Other,
4688                             Results.data(),Results.size());
4689 }
4690 
4691 /// \brief Determine whether the addition of the given flag to an Objective-C
4692 /// property's attributes will cause a conflict.
4693 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4694   // Check if we've already added this flag.
4695   if (Attributes & NewFlag)
4696     return true;
4697 
4698   Attributes |= NewFlag;
4699 
4700   // Check for collisions with "readonly".
4701   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4702       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
4703     return true;
4704 
4705   // Check for more than one of { assign, copy, retain, strong, weak }.
4706   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4707                                          ObjCDeclSpec::DQ_PR_unsafe_unretained |
4708                                              ObjCDeclSpec::DQ_PR_copy |
4709                                              ObjCDeclSpec::DQ_PR_retain |
4710                                              ObjCDeclSpec::DQ_PR_strong |
4711                                              ObjCDeclSpec::DQ_PR_weak);
4712   if (AssignCopyRetMask &&
4713       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4714       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
4715       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4716       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4717       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4718       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
4719     return true;
4720 
4721   return false;
4722 }
4723 
4724 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
4725   if (!CodeCompleter)
4726     return;
4727 
4728   unsigned Attributes = ODS.getPropertyAttributes();
4729 
4730   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4731                         CodeCompleter->getCodeCompletionTUInfo(),
4732                         CodeCompletionContext::CCC_Other);
4733   Results.EnterNewScope();
4734   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
4735     Results.AddResult(CodeCompletionResult("readonly"));
4736   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
4737     Results.AddResult(CodeCompletionResult("assign"));
4738   if (!ObjCPropertyFlagConflicts(Attributes,
4739                                  ObjCDeclSpec::DQ_PR_unsafe_unretained))
4740     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
4741   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
4742     Results.AddResult(CodeCompletionResult("readwrite"));
4743   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
4744     Results.AddResult(CodeCompletionResult("retain"));
4745   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4746     Results.AddResult(CodeCompletionResult("strong"));
4747   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
4748     Results.AddResult(CodeCompletionResult("copy"));
4749   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
4750     Results.AddResult(CodeCompletionResult("nonatomic"));
4751   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4752     Results.AddResult(CodeCompletionResult("atomic"));
4753 
4754   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
4755   if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
4756     if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
4757       Results.AddResult(CodeCompletionResult("weak"));
4758 
4759   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
4760     CodeCompletionBuilder Setter(Results.getAllocator(),
4761                                  Results.getCodeCompletionTUInfo());
4762     Setter.AddTypedTextChunk("setter");
4763     Setter.AddTextChunk(" = ");
4764     Setter.AddPlaceholderChunk("method");
4765     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
4766   }
4767   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4768     CodeCompletionBuilder Getter(Results.getAllocator(),
4769                                  Results.getCodeCompletionTUInfo());
4770     Getter.AddTypedTextChunk("getter");
4771     Getter.AddTextChunk(" = ");
4772     Getter.AddPlaceholderChunk("method");
4773     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
4774   }
4775   Results.ExitScope();
4776   HandleCodeCompleteResults(this, CodeCompleter,
4777                             CodeCompletionContext::CCC_Other,
4778                             Results.data(),Results.size());
4779 }
4780 
4781 /// \brief Describes the kind of Objective-C method that we want to find
4782 /// via code completion.
4783 enum ObjCMethodKind {
4784   MK_Any, ///< Any kind of method, provided it means other specified criteria.
4785   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4786   MK_OneArgSelector ///< One-argument selector.
4787 };
4788 
4789 static bool isAcceptableObjCSelector(Selector Sel,
4790                                      ObjCMethodKind WantKind,
4791                                      ArrayRef<IdentifierInfo *> SelIdents,
4792                                      bool AllowSameLength = true) {
4793   unsigned NumSelIdents = SelIdents.size();
4794   if (NumSelIdents > Sel.getNumArgs())
4795     return false;
4796 
4797   switch (WantKind) {
4798     case MK_Any:             break;
4799     case MK_ZeroArgSelector: return Sel.isUnarySelector();
4800     case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
4801   }
4802 
4803   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4804     return false;
4805 
4806   for (unsigned I = 0; I != NumSelIdents; ++I)
4807     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4808       return false;
4809 
4810   return true;
4811 }
4812 
4813 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4814                                    ObjCMethodKind WantKind,
4815                                    ArrayRef<IdentifierInfo *> SelIdents,
4816                                    bool AllowSameLength = true) {
4817   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4818                                   AllowSameLength);
4819 }
4820 
4821 namespace {
4822   /// \brief A set of selectors, which is used to avoid introducing multiple
4823   /// completions with the same selector into the result set.
4824   typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4825 }
4826 
4827 /// \brief Add all of the Objective-C methods in the given Objective-C
4828 /// container to the set of results.
4829 ///
4830 /// The container will be a class, protocol, category, or implementation of
4831 /// any of the above. This mether will recurse to include methods from
4832 /// the superclasses of classes along with their categories, protocols, and
4833 /// implementations.
4834 ///
4835 /// \param Container the container in which we'll look to find methods.
4836 ///
4837 /// \param WantInstanceMethods Whether to add instance methods (only); if
4838 /// false, this routine will add factory methods (only).
4839 ///
4840 /// \param CurContext the context in which we're performing the lookup that
4841 /// finds methods.
4842 ///
4843 /// \param AllowSameLength Whether we allow a method to be added to the list
4844 /// when it has the same number of parameters as we have selector identifiers.
4845 ///
4846 /// \param Results the structure into which we'll add results.
4847 static void AddObjCMethods(ObjCContainerDecl *Container,
4848                            bool WantInstanceMethods,
4849                            ObjCMethodKind WantKind,
4850                            ArrayRef<IdentifierInfo *> SelIdents,
4851                            DeclContext *CurContext,
4852                            VisitedSelectorSet &Selectors,
4853                            bool AllowSameLength,
4854                            ResultBuilder &Results,
4855                            bool InOriginalClass = true) {
4856   typedef CodeCompletionResult Result;
4857   Container = getContainerDef(Container);
4858   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4859   bool isRootClass = IFace && !IFace->getSuperClass();
4860   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4861                                        MEnd = Container->meth_end();
4862        M != MEnd; ++M) {
4863     // The instance methods on the root class can be messaged via the
4864     // metaclass.
4865     if (M->isInstanceMethod() == WantInstanceMethods ||
4866         (isRootClass && !WantInstanceMethods)) {
4867       // Check whether the selector identifiers we've been given are a
4868       // subset of the identifiers for this particular method.
4869       if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, AllowSameLength))
4870         continue;
4871 
4872       if (!Selectors.insert(M->getSelector()))
4873         continue;
4874 
4875       Result R = Result(*M, Results.getBasePriority(*M), 0);
4876       R.StartParameter = SelIdents.size();
4877       R.AllParametersAreInformative = (WantKind != MK_Any);
4878       if (!InOriginalClass)
4879         R.Priority += CCD_InBaseClass;
4880       Results.MaybeAddResult(R, CurContext);
4881     }
4882   }
4883 
4884   // Visit the protocols of protocols.
4885   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4886     if (Protocol->hasDefinition()) {
4887       const ObjCList<ObjCProtocolDecl> &Protocols
4888         = Protocol->getReferencedProtocols();
4889       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4890                                                 E = Protocols.end();
4891            I != E; ++I)
4892         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4893                        CurContext, Selectors, AllowSameLength, Results, false);
4894     }
4895   }
4896 
4897   if (!IFace || !IFace->hasDefinition())
4898     return;
4899 
4900   // Add methods in protocols.
4901   for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
4902                                             E = IFace->protocol_end();
4903        I != E; ++I)
4904     AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4905                    CurContext, Selectors, AllowSameLength, Results, false);
4906 
4907   // Add methods in categories.
4908   for (ObjCInterfaceDecl::known_categories_iterator
4909          Cat = IFace->known_categories_begin(),
4910          CatEnd = IFace->known_categories_end();
4911        Cat != CatEnd; ++Cat) {
4912     ObjCCategoryDecl *CatDecl = *Cat;
4913 
4914     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
4915                    CurContext, Selectors, AllowSameLength,
4916                    Results, InOriginalClass);
4917 
4918     // Add a categories protocol methods.
4919     const ObjCList<ObjCProtocolDecl> &Protocols
4920       = CatDecl->getReferencedProtocols();
4921     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4922                                               E = Protocols.end();
4923          I != E; ++I)
4924       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4925                      CurContext, Selectors, AllowSameLength,
4926                      Results, false);
4927 
4928     // Add methods in category implementations.
4929     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
4930       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4931                      CurContext, Selectors, AllowSameLength,
4932                      Results, InOriginalClass);
4933   }
4934 
4935   // Add methods in superclass.
4936   if (IFace->getSuperClass())
4937     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
4938                    SelIdents, CurContext, Selectors,
4939                    AllowSameLength, Results, false);
4940 
4941   // Add methods in our implementation, if any.
4942   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4943     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4944                    CurContext, Selectors, AllowSameLength,
4945                    Results, InOriginalClass);
4946 }
4947 
4948 
4949 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
4950   // Try to find the interface where getters might live.
4951   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4952   if (!Class) {
4953     if (ObjCCategoryDecl *Category
4954           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4955       Class = Category->getClassInterface();
4956 
4957     if (!Class)
4958       return;
4959   }
4960 
4961   // Find all of the potential getters.
4962   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4963                         CodeCompleter->getCodeCompletionTUInfo(),
4964                         CodeCompletionContext::CCC_Other);
4965   Results.EnterNewScope();
4966 
4967   VisitedSelectorSet Selectors;
4968   AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
4969                  /*AllowSameLength=*/true, Results);
4970   Results.ExitScope();
4971   HandleCodeCompleteResults(this, CodeCompleter,
4972                             CodeCompletionContext::CCC_Other,
4973                             Results.data(),Results.size());
4974 }
4975 
4976 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
4977   // Try to find the interface where setters might live.
4978   ObjCInterfaceDecl *Class
4979     = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4980   if (!Class) {
4981     if (ObjCCategoryDecl *Category
4982           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4983       Class = Category->getClassInterface();
4984 
4985     if (!Class)
4986       return;
4987   }
4988 
4989   // Find all of the potential getters.
4990   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4991                         CodeCompleter->getCodeCompletionTUInfo(),
4992                         CodeCompletionContext::CCC_Other);
4993   Results.EnterNewScope();
4994 
4995   VisitedSelectorSet Selectors;
4996   AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
4997                  Selectors, /*AllowSameLength=*/true, Results);
4998 
4999   Results.ExitScope();
5000   HandleCodeCompleteResults(this, CodeCompleter,
5001                             CodeCompletionContext::CCC_Other,
5002                             Results.data(),Results.size());
5003 }
5004 
5005 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5006                                        bool IsParameter) {
5007   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5008                         CodeCompleter->getCodeCompletionTUInfo(),
5009                         CodeCompletionContext::CCC_Type);
5010   Results.EnterNewScope();
5011 
5012   // Add context-sensitive, Objective-C parameter-passing keywords.
5013   bool AddedInOut = false;
5014   if ((DS.getObjCDeclQualifier() &
5015        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5016     Results.AddResult("in");
5017     Results.AddResult("inout");
5018     AddedInOut = true;
5019   }
5020   if ((DS.getObjCDeclQualifier() &
5021        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5022     Results.AddResult("out");
5023     if (!AddedInOut)
5024       Results.AddResult("inout");
5025   }
5026   if ((DS.getObjCDeclQualifier() &
5027        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5028         ObjCDeclSpec::DQ_Oneway)) == 0) {
5029      Results.AddResult("bycopy");
5030      Results.AddResult("byref");
5031      Results.AddResult("oneway");
5032   }
5033 
5034   // If we're completing the return type of an Objective-C method and the
5035   // identifier IBAction refers to a macro, provide a completion item for
5036   // an action, e.g.,
5037   //   IBAction)<#selector#>:(id)sender
5038   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5039       Context.Idents.get("IBAction").hasMacroDefinition()) {
5040     CodeCompletionBuilder Builder(Results.getAllocator(),
5041                                   Results.getCodeCompletionTUInfo(),
5042                                   CCP_CodePattern, CXAvailability_Available);
5043     Builder.AddTypedTextChunk("IBAction");
5044     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5045     Builder.AddPlaceholderChunk("selector");
5046     Builder.AddChunk(CodeCompletionString::CK_Colon);
5047     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5048     Builder.AddTextChunk("id");
5049     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5050     Builder.AddTextChunk("sender");
5051     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5052   }
5053 
5054   // If we're completing the return type, provide 'instancetype'.
5055   if (!IsParameter) {
5056     Results.AddResult(CodeCompletionResult("instancetype"));
5057   }
5058 
5059   // Add various builtin type names and specifiers.
5060   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5061   Results.ExitScope();
5062 
5063   // Add the various type names
5064   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5065   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5066   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5067                      CodeCompleter->includeGlobals());
5068 
5069   if (CodeCompleter->includeMacros())
5070     AddMacroResults(PP, Results, false);
5071 
5072   HandleCodeCompleteResults(this, CodeCompleter,
5073                             CodeCompletionContext::CCC_Type,
5074                             Results.data(), Results.size());
5075 }
5076 
5077 /// \brief When we have an expression with type "id", we may assume
5078 /// that it has some more-specific class type based on knowledge of
5079 /// common uses of Objective-C. This routine returns that class type,
5080 /// or NULL if no better result could be determined.
5081 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5082   ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5083   if (!Msg)
5084     return 0;
5085 
5086   Selector Sel = Msg->getSelector();
5087   if (Sel.isNull())
5088     return 0;
5089 
5090   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5091   if (!Id)
5092     return 0;
5093 
5094   ObjCMethodDecl *Method = Msg->getMethodDecl();
5095   if (!Method)
5096     return 0;
5097 
5098   // Determine the class that we're sending the message to.
5099   ObjCInterfaceDecl *IFace = 0;
5100   switch (Msg->getReceiverKind()) {
5101   case ObjCMessageExpr::Class:
5102     if (const ObjCObjectType *ObjType
5103                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5104       IFace = ObjType->getInterface();
5105     break;
5106 
5107   case ObjCMessageExpr::Instance: {
5108     QualType T = Msg->getInstanceReceiver()->getType();
5109     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5110       IFace = Ptr->getInterfaceDecl();
5111     break;
5112   }
5113 
5114   case ObjCMessageExpr::SuperInstance:
5115   case ObjCMessageExpr::SuperClass:
5116     break;
5117   }
5118 
5119   if (!IFace)
5120     return 0;
5121 
5122   ObjCInterfaceDecl *Super = IFace->getSuperClass();
5123   if (Method->isInstanceMethod())
5124     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5125       .Case("retain", IFace)
5126       .Case("strong", IFace)
5127       .Case("autorelease", IFace)
5128       .Case("copy", IFace)
5129       .Case("copyWithZone", IFace)
5130       .Case("mutableCopy", IFace)
5131       .Case("mutableCopyWithZone", IFace)
5132       .Case("awakeFromCoder", IFace)
5133       .Case("replacementObjectFromCoder", IFace)
5134       .Case("class", IFace)
5135       .Case("classForCoder", IFace)
5136       .Case("superclass", Super)
5137       .Default(0);
5138 
5139   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5140     .Case("new", IFace)
5141     .Case("alloc", IFace)
5142     .Case("allocWithZone", IFace)
5143     .Case("class", IFace)
5144     .Case("superclass", Super)
5145     .Default(0);
5146 }
5147 
5148 // Add a special completion for a message send to "super", which fills in the
5149 // most likely case of forwarding all of our arguments to the superclass
5150 // function.
5151 ///
5152 /// \param S The semantic analysis object.
5153 ///
5154 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5155 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5156 ///
5157 /// \param SelIdents The identifiers in the selector that have already been
5158 /// provided as arguments for a send to "super".
5159 ///
5160 /// \param Results The set of results to augment.
5161 ///
5162 /// \returns the Objective-C method declaration that would be invoked by
5163 /// this "super" completion. If NULL, no completion was added.
5164 static ObjCMethodDecl *AddSuperSendCompletion(
5165                                           Sema &S, bool NeedSuperKeyword,
5166                                           ArrayRef<IdentifierInfo *> SelIdents,
5167                                           ResultBuilder &Results) {
5168   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5169   if (!CurMethod)
5170     return 0;
5171 
5172   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5173   if (!Class)
5174     return 0;
5175 
5176   // Try to find a superclass method with the same selector.
5177   ObjCMethodDecl *SuperMethod = 0;
5178   while ((Class = Class->getSuperClass()) && !SuperMethod) {
5179     // Check in the class
5180     SuperMethod = Class->getMethod(CurMethod->getSelector(),
5181                                    CurMethod->isInstanceMethod());
5182 
5183     // Check in categories or class extensions.
5184     if (!SuperMethod) {
5185       for (ObjCInterfaceDecl::known_categories_iterator
5186              Cat = Class->known_categories_begin(),
5187              CatEnd = Class->known_categories_end();
5188            Cat != CatEnd; ++Cat) {
5189         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5190                                                CurMethod->isInstanceMethod())))
5191           break;
5192       }
5193     }
5194   }
5195 
5196   if (!SuperMethod)
5197     return 0;
5198 
5199   // Check whether the superclass method has the same signature.
5200   if (CurMethod->param_size() != SuperMethod->param_size() ||
5201       CurMethod->isVariadic() != SuperMethod->isVariadic())
5202     return 0;
5203 
5204   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5205                                    CurPEnd = CurMethod->param_end(),
5206                                     SuperP = SuperMethod->param_begin();
5207        CurP != CurPEnd; ++CurP, ++SuperP) {
5208     // Make sure the parameter types are compatible.
5209     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5210                                           (*SuperP)->getType()))
5211       return 0;
5212 
5213     // Make sure we have a parameter name to forward!
5214     if (!(*CurP)->getIdentifier())
5215       return 0;
5216   }
5217 
5218   // We have a superclass method. Now, form the send-to-super completion.
5219   CodeCompletionBuilder Builder(Results.getAllocator(),
5220                                 Results.getCodeCompletionTUInfo());
5221 
5222   // Give this completion a return type.
5223   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5224                      Builder);
5225 
5226   // If we need the "super" keyword, add it (plus some spacing).
5227   if (NeedSuperKeyword) {
5228     Builder.AddTypedTextChunk("super");
5229     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5230   }
5231 
5232   Selector Sel = CurMethod->getSelector();
5233   if (Sel.isUnarySelector()) {
5234     if (NeedSuperKeyword)
5235       Builder.AddTextChunk(Builder.getAllocator().CopyString(
5236                                   Sel.getNameForSlot(0)));
5237     else
5238       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5239                                    Sel.getNameForSlot(0)));
5240   } else {
5241     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5242     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5243       if (I > SelIdents.size())
5244         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5245 
5246       if (I < SelIdents.size())
5247         Builder.AddInformativeChunk(
5248                    Builder.getAllocator().CopyString(
5249                                                  Sel.getNameForSlot(I) + ":"));
5250       else if (NeedSuperKeyword || I > SelIdents.size()) {
5251         Builder.AddTextChunk(
5252                  Builder.getAllocator().CopyString(
5253                                                   Sel.getNameForSlot(I) + ":"));
5254         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5255                                          (*CurP)->getIdentifier()->getName()));
5256       } else {
5257         Builder.AddTypedTextChunk(
5258                   Builder.getAllocator().CopyString(
5259                                                   Sel.getNameForSlot(I) + ":"));
5260         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5261                                          (*CurP)->getIdentifier()->getName()));
5262       }
5263     }
5264   }
5265 
5266   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5267                                          CCP_SuperCompletion));
5268   return SuperMethod;
5269 }
5270 
5271 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5272   typedef CodeCompletionResult Result;
5273   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5274                         CodeCompleter->getCodeCompletionTUInfo(),
5275                         CodeCompletionContext::CCC_ObjCMessageReceiver,
5276                         getLangOpts().CPlusPlus11
5277                           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5278                           : &ResultBuilder::IsObjCMessageReceiver);
5279 
5280   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5281   Results.EnterNewScope();
5282   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5283                      CodeCompleter->includeGlobals());
5284 
5285   // If we are in an Objective-C method inside a class that has a superclass,
5286   // add "super" as an option.
5287   if (ObjCMethodDecl *Method = getCurMethodDecl())
5288     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5289       if (Iface->getSuperClass()) {
5290         Results.AddResult(Result("super"));
5291 
5292         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5293       }
5294 
5295   if (getLangOpts().CPlusPlus11)
5296     addThisCompletion(*this, Results);
5297 
5298   Results.ExitScope();
5299 
5300   if (CodeCompleter->includeMacros())
5301     AddMacroResults(PP, Results, false);
5302   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5303                             Results.data(), Results.size());
5304 
5305 }
5306 
5307 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5308                                         ArrayRef<IdentifierInfo *> SelIdents,
5309                                         bool AtArgumentExpression) {
5310   ObjCInterfaceDecl *CDecl = 0;
5311   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5312     // Figure out which interface we're in.
5313     CDecl = CurMethod->getClassInterface();
5314     if (!CDecl)
5315       return;
5316 
5317     // Find the superclass of this class.
5318     CDecl = CDecl->getSuperClass();
5319     if (!CDecl)
5320       return;
5321 
5322     if (CurMethod->isInstanceMethod()) {
5323       // We are inside an instance method, which means that the message
5324       // send [super ...] is actually calling an instance method on the
5325       // current object.
5326       return CodeCompleteObjCInstanceMessage(S, 0, SelIdents,
5327                                              AtArgumentExpression,
5328                                              CDecl);
5329     }
5330 
5331     // Fall through to send to the superclass in CDecl.
5332   } else {
5333     // "super" may be the name of a type or variable. Figure out which
5334     // it is.
5335     IdentifierInfo *Super = getSuperIdentifier();
5336     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5337                                      LookupOrdinaryName);
5338     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5339       // "super" names an interface. Use it.
5340     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5341       if (const ObjCObjectType *Iface
5342             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5343         CDecl = Iface->getInterface();
5344     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5345       // "super" names an unresolved type; we can't be more specific.
5346     } else {
5347       // Assume that "super" names some kind of value and parse that way.
5348       CXXScopeSpec SS;
5349       SourceLocation TemplateKWLoc;
5350       UnqualifiedId id;
5351       id.setIdentifier(Super, SuperLoc);
5352       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5353                                                false, false);
5354       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5355                                              SelIdents,
5356                                              AtArgumentExpression);
5357     }
5358 
5359     // Fall through
5360   }
5361 
5362   ParsedType Receiver;
5363   if (CDecl)
5364     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5365   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5366                                       AtArgumentExpression,
5367                                       /*IsSuper=*/true);
5368 }
5369 
5370 /// \brief Given a set of code-completion results for the argument of a message
5371 /// send, determine the preferred type (if any) for that argument expression.
5372 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5373                                                        unsigned NumSelIdents) {
5374   typedef CodeCompletionResult Result;
5375   ASTContext &Context = Results.getSema().Context;
5376 
5377   QualType PreferredType;
5378   unsigned BestPriority = CCP_Unlikely * 2;
5379   Result *ResultsData = Results.data();
5380   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5381     Result &R = ResultsData[I];
5382     if (R.Kind == Result::RK_Declaration &&
5383         isa<ObjCMethodDecl>(R.Declaration)) {
5384       if (R.Priority <= BestPriority) {
5385         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5386         if (NumSelIdents <= Method->param_size()) {
5387           QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5388                                        ->getType();
5389           if (R.Priority < BestPriority || PreferredType.isNull()) {
5390             BestPriority = R.Priority;
5391             PreferredType = MyPreferredType;
5392           } else if (!Context.hasSameUnqualifiedType(PreferredType,
5393                                                      MyPreferredType)) {
5394             PreferredType = QualType();
5395           }
5396         }
5397       }
5398     }
5399   }
5400 
5401   return PreferredType;
5402 }
5403 
5404 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5405                                        ParsedType Receiver,
5406                                        ArrayRef<IdentifierInfo *> SelIdents,
5407                                        bool AtArgumentExpression,
5408                                        bool IsSuper,
5409                                        ResultBuilder &Results) {
5410   typedef CodeCompletionResult Result;
5411   ObjCInterfaceDecl *CDecl = 0;
5412 
5413   // If the given name refers to an interface type, retrieve the
5414   // corresponding declaration.
5415   if (Receiver) {
5416     QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
5417     if (!T.isNull())
5418       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5419         CDecl = Interface->getInterface();
5420   }
5421 
5422   // Add all of the factory methods in this Objective-C class, its protocols,
5423   // superclasses, categories, implementation, etc.
5424   Results.EnterNewScope();
5425 
5426   // If this is a send-to-super, try to add the special "super" send
5427   // completion.
5428   if (IsSuper) {
5429     if (ObjCMethodDecl *SuperMethod
5430         = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5431       Results.Ignore(SuperMethod);
5432   }
5433 
5434   // If we're inside an Objective-C method definition, prefer its selector to
5435   // others.
5436   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5437     Results.setPreferredSelector(CurMethod->getSelector());
5438 
5439   VisitedSelectorSet Selectors;
5440   if (CDecl)
5441     AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5442                    SemaRef.CurContext, Selectors, AtArgumentExpression,
5443                    Results);
5444   else {
5445     // We're messaging "id" as a type; provide all class/factory methods.
5446 
5447     // If we have an external source, load the entire class method
5448     // pool from the AST file.
5449     if (SemaRef.getExternalSource()) {
5450       for (uint32_t I = 0,
5451                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
5452            I != N; ++I) {
5453         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
5454         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5455           continue;
5456 
5457         SemaRef.ReadMethodPool(Sel);
5458       }
5459     }
5460 
5461     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5462                                        MEnd = SemaRef.MethodPool.end();
5463          M != MEnd; ++M) {
5464       for (ObjCMethodList *MethList = &M->second.second;
5465            MethList && MethList->Method;
5466            MethList = MethList->getNext()) {
5467         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
5468           continue;
5469 
5470         Result R(MethList->Method, Results.getBasePriority(MethList->Method),0);
5471         R.StartParameter = SelIdents.size();
5472         R.AllParametersAreInformative = false;
5473         Results.MaybeAddResult(R, SemaRef.CurContext);
5474       }
5475     }
5476   }
5477 
5478   Results.ExitScope();
5479 }
5480 
5481 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5482                                         ArrayRef<IdentifierInfo *> SelIdents,
5483                                         bool AtArgumentExpression,
5484                                         bool IsSuper) {
5485 
5486   QualType T = this->GetTypeFromParser(Receiver);
5487 
5488   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5489                         CodeCompleter->getCodeCompletionTUInfo(),
5490               CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5491                                     T, SelIdents));
5492 
5493   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
5494                              AtArgumentExpression, IsSuper, Results);
5495 
5496   // If we're actually at the argument expression (rather than prior to the
5497   // selector), we're actually performing code completion for an expression.
5498   // Determine whether we have a single, best method. If so, we can
5499   // code-complete the expression using the corresponding parameter type as
5500   // our preferred type, improving completion results.
5501   if (AtArgumentExpression) {
5502     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5503                                                               SelIdents.size());
5504     if (PreferredType.isNull())
5505       CodeCompleteOrdinaryName(S, PCC_Expression);
5506     else
5507       CodeCompleteExpression(S, PreferredType);
5508     return;
5509   }
5510 
5511   HandleCodeCompleteResults(this, CodeCompleter,
5512                             Results.getCompletionContext(),
5513                             Results.data(), Results.size());
5514 }
5515 
5516 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5517                                            ArrayRef<IdentifierInfo *> SelIdents,
5518                                            bool AtArgumentExpression,
5519                                            ObjCInterfaceDecl *Super) {
5520   typedef CodeCompletionResult Result;
5521 
5522   Expr *RecExpr = static_cast<Expr *>(Receiver);
5523 
5524   // If necessary, apply function/array conversion to the receiver.
5525   // C99 6.7.5.3p[7,8].
5526   if (RecExpr) {
5527     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5528     if (Conv.isInvalid()) // conversion failed. bail.
5529       return;
5530     RecExpr = Conv.take();
5531   }
5532   QualType ReceiverType = RecExpr? RecExpr->getType()
5533                           : Super? Context.getObjCObjectPointerType(
5534                                             Context.getObjCInterfaceType(Super))
5535                                  : Context.getObjCIdType();
5536 
5537   // If we're messaging an expression with type "id" or "Class", check
5538   // whether we know something special about the receiver that allows
5539   // us to assume a more-specific receiver type.
5540   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5541     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5542       if (ReceiverType->isObjCClassType())
5543         return CodeCompleteObjCClassMessage(S,
5544                        ParsedType::make(Context.getObjCInterfaceType(IFace)),
5545                                             SelIdents,
5546                                             AtArgumentExpression, Super);
5547 
5548       ReceiverType = Context.getObjCObjectPointerType(
5549                                           Context.getObjCInterfaceType(IFace));
5550     }
5551 
5552   // Build the set of methods we can see.
5553   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5554                         CodeCompleter->getCodeCompletionTUInfo(),
5555            CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
5556                                  ReceiverType, SelIdents));
5557 
5558   Results.EnterNewScope();
5559 
5560   // If this is a send-to-super, try to add the special "super" send
5561   // completion.
5562   if (Super) {
5563     if (ObjCMethodDecl *SuperMethod
5564           = AddSuperSendCompletion(*this, false, SelIdents, Results))
5565       Results.Ignore(SuperMethod);
5566   }
5567 
5568   // If we're inside an Objective-C method definition, prefer its selector to
5569   // others.
5570   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5571     Results.setPreferredSelector(CurMethod->getSelector());
5572 
5573   // Keep track of the selectors we've already added.
5574   VisitedSelectorSet Selectors;
5575 
5576   // Handle messages to Class. This really isn't a message to an instance
5577   // method, so we treat it the same way we would treat a message send to a
5578   // class method.
5579   if (ReceiverType->isObjCClassType() ||
5580       ReceiverType->isObjCQualifiedClassType()) {
5581     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5582       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
5583         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
5584                        CurContext, Selectors, AtArgumentExpression, Results);
5585     }
5586   }
5587   // Handle messages to a qualified ID ("id<foo>").
5588   else if (const ObjCObjectPointerType *QualID
5589              = ReceiverType->getAsObjCQualifiedIdType()) {
5590     // Search protocols for instance methods.
5591     for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5592                                               E = QualID->qual_end();
5593          I != E; ++I)
5594       AddObjCMethods(*I, true, MK_Any, SelIdents, CurContext,
5595                      Selectors, AtArgumentExpression, Results);
5596   }
5597   // Handle messages to a pointer to interface type.
5598   else if (const ObjCObjectPointerType *IFacePtr
5599                               = ReceiverType->getAsObjCInterfacePointerType()) {
5600     // Search the class, its superclasses, etc., for instance methods.
5601     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
5602                    CurContext, Selectors, AtArgumentExpression,
5603                    Results);
5604 
5605     // Search protocols for instance methods.
5606     for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5607          E = IFacePtr->qual_end();
5608          I != E; ++I)
5609       AddObjCMethods(*I, true, MK_Any, SelIdents, CurContext,
5610                      Selectors, AtArgumentExpression, Results);
5611   }
5612   // Handle messages to "id".
5613   else if (ReceiverType->isObjCIdType()) {
5614     // We're messaging "id", so provide all instance methods we know
5615     // about as code-completion results.
5616 
5617     // If we have an external source, load the entire class method
5618     // pool from the AST file.
5619     if (ExternalSource) {
5620       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5621            I != N; ++I) {
5622         Selector Sel = ExternalSource->GetExternalSelector(I);
5623         if (Sel.isNull() || MethodPool.count(Sel))
5624           continue;
5625 
5626         ReadMethodPool(Sel);
5627       }
5628     }
5629 
5630     for (GlobalMethodPool::iterator M = MethodPool.begin(),
5631                                     MEnd = MethodPool.end();
5632          M != MEnd; ++M) {
5633       for (ObjCMethodList *MethList = &M->second.first;
5634            MethList && MethList->Method;
5635            MethList = MethList->getNext()) {
5636         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
5637           continue;
5638 
5639         if (!Selectors.insert(MethList->Method->getSelector()))
5640           continue;
5641 
5642         Result R(MethList->Method, Results.getBasePriority(MethList->Method),0);
5643         R.StartParameter = SelIdents.size();
5644         R.AllParametersAreInformative = false;
5645         Results.MaybeAddResult(R, CurContext);
5646       }
5647     }
5648   }
5649   Results.ExitScope();
5650 
5651 
5652   // If we're actually at the argument expression (rather than prior to the
5653   // selector), we're actually performing code completion for an expression.
5654   // Determine whether we have a single, best method. If so, we can
5655   // code-complete the expression using the corresponding parameter type as
5656   // our preferred type, improving completion results.
5657   if (AtArgumentExpression) {
5658     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5659                                                               SelIdents.size());
5660     if (PreferredType.isNull())
5661       CodeCompleteOrdinaryName(S, PCC_Expression);
5662     else
5663       CodeCompleteExpression(S, PreferredType);
5664     return;
5665   }
5666 
5667   HandleCodeCompleteResults(this, CodeCompleter,
5668                             Results.getCompletionContext(),
5669                             Results.data(),Results.size());
5670 }
5671 
5672 void Sema::CodeCompleteObjCForCollection(Scope *S,
5673                                          DeclGroupPtrTy IterationVar) {
5674   CodeCompleteExpressionData Data;
5675   Data.ObjCCollection = true;
5676 
5677   if (IterationVar.getAsOpaquePtr()) {
5678     DeclGroupRef DG = IterationVar.get();
5679     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5680       if (*I)
5681         Data.IgnoreDecls.push_back(*I);
5682     }
5683   }
5684 
5685   CodeCompleteExpression(S, Data);
5686 }
5687 
5688 void Sema::CodeCompleteObjCSelector(Scope *S,
5689                                     ArrayRef<IdentifierInfo *> SelIdents) {
5690   // If we have an external source, load the entire class method
5691   // pool from the AST file.
5692   if (ExternalSource) {
5693     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5694          I != N; ++I) {
5695       Selector Sel = ExternalSource->GetExternalSelector(I);
5696       if (Sel.isNull() || MethodPool.count(Sel))
5697         continue;
5698 
5699       ReadMethodPool(Sel);
5700     }
5701   }
5702 
5703   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5704                         CodeCompleter->getCodeCompletionTUInfo(),
5705                         CodeCompletionContext::CCC_SelectorName);
5706   Results.EnterNewScope();
5707   for (GlobalMethodPool::iterator M = MethodPool.begin(),
5708                                MEnd = MethodPool.end();
5709        M != MEnd; ++M) {
5710 
5711     Selector Sel = M->first;
5712     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
5713       continue;
5714 
5715     CodeCompletionBuilder Builder(Results.getAllocator(),
5716                                   Results.getCodeCompletionTUInfo());
5717     if (Sel.isUnarySelector()) {
5718       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5719                                                        Sel.getNameForSlot(0)));
5720       Results.AddResult(Builder.TakeString());
5721       continue;
5722     }
5723 
5724     std::string Accumulator;
5725     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
5726       if (I == SelIdents.size()) {
5727         if (!Accumulator.empty()) {
5728           Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
5729                                                  Accumulator));
5730           Accumulator.clear();
5731         }
5732       }
5733 
5734       Accumulator += Sel.getNameForSlot(I);
5735       Accumulator += ':';
5736     }
5737     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
5738     Results.AddResult(Builder.TakeString());
5739   }
5740   Results.ExitScope();
5741 
5742   HandleCodeCompleteResults(this, CodeCompleter,
5743                             CodeCompletionContext::CCC_SelectorName,
5744                             Results.data(), Results.size());
5745 }
5746 
5747 /// \brief Add all of the protocol declarations that we find in the given
5748 /// (translation unit) context.
5749 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
5750                                bool OnlyForwardDeclarations,
5751                                ResultBuilder &Results) {
5752   typedef CodeCompletionResult Result;
5753 
5754   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5755                                DEnd = Ctx->decls_end();
5756        D != DEnd; ++D) {
5757     // Record any protocols we find.
5758     if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
5759       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
5760         Results.AddResult(Result(Proto, Results.getBasePriority(Proto), 0),
5761                           CurContext, 0, false);
5762   }
5763 }
5764 
5765 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5766                                               unsigned NumProtocols) {
5767   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5768                         CodeCompleter->getCodeCompletionTUInfo(),
5769                         CodeCompletionContext::CCC_ObjCProtocolName);
5770 
5771   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5772     Results.EnterNewScope();
5773 
5774     // Tell the result set to ignore all of the protocols we have
5775     // already seen.
5776     // FIXME: This doesn't work when caching code-completion results.
5777     for (unsigned I = 0; I != NumProtocols; ++I)
5778       if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5779                                                       Protocols[I].second))
5780         Results.Ignore(Protocol);
5781 
5782     // Add all protocols.
5783     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5784                        Results);
5785 
5786     Results.ExitScope();
5787   }
5788 
5789   HandleCodeCompleteResults(this, CodeCompleter,
5790                             CodeCompletionContext::CCC_ObjCProtocolName,
5791                             Results.data(),Results.size());
5792 }
5793 
5794 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
5795   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5796                         CodeCompleter->getCodeCompletionTUInfo(),
5797                         CodeCompletionContext::CCC_ObjCProtocolName);
5798 
5799   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5800     Results.EnterNewScope();
5801 
5802     // Add all protocols.
5803     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5804                        Results);
5805 
5806     Results.ExitScope();
5807   }
5808 
5809   HandleCodeCompleteResults(this, CodeCompleter,
5810                             CodeCompletionContext::CCC_ObjCProtocolName,
5811                             Results.data(),Results.size());
5812 }
5813 
5814 /// \brief Add all of the Objective-C interface declarations that we find in
5815 /// the given (translation unit) context.
5816 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5817                                 bool OnlyForwardDeclarations,
5818                                 bool OnlyUnimplemented,
5819                                 ResultBuilder &Results) {
5820   typedef CodeCompletionResult Result;
5821 
5822   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5823                                DEnd = Ctx->decls_end();
5824        D != DEnd; ++D) {
5825     // Record any interfaces we find.
5826     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5827       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
5828           (!OnlyUnimplemented || !Class->getImplementation()))
5829         Results.AddResult(Result(Class, Results.getBasePriority(Class), 0),
5830                           CurContext, 0, false);
5831   }
5832 }
5833 
5834 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5835   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5836                         CodeCompleter->getCodeCompletionTUInfo(),
5837                         CodeCompletionContext::CCC_Other);
5838   Results.EnterNewScope();
5839 
5840   if (CodeCompleter->includeGlobals()) {
5841     // Add all classes.
5842     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5843                         false, Results);
5844   }
5845 
5846   Results.ExitScope();
5847 
5848   HandleCodeCompleteResults(this, CodeCompleter,
5849                             CodeCompletionContext::CCC_ObjCInterfaceName,
5850                             Results.data(),Results.size());
5851 }
5852 
5853 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5854                                       SourceLocation ClassNameLoc) {
5855   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5856                         CodeCompleter->getCodeCompletionTUInfo(),
5857                         CodeCompletionContext::CCC_ObjCInterfaceName);
5858   Results.EnterNewScope();
5859 
5860   // Make sure that we ignore the class we're currently defining.
5861   NamedDecl *CurClass
5862     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5863   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
5864     Results.Ignore(CurClass);
5865 
5866   if (CodeCompleter->includeGlobals()) {
5867     // Add all classes.
5868     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5869                         false, Results);
5870   }
5871 
5872   Results.ExitScope();
5873 
5874   HandleCodeCompleteResults(this, CodeCompleter,
5875                             CodeCompletionContext::CCC_ObjCInterfaceName,
5876                             Results.data(),Results.size());
5877 }
5878 
5879 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
5880   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5881                         CodeCompleter->getCodeCompletionTUInfo(),
5882                         CodeCompletionContext::CCC_Other);
5883   Results.EnterNewScope();
5884 
5885   if (CodeCompleter->includeGlobals()) {
5886     // Add all unimplemented classes.
5887     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5888                         true, Results);
5889   }
5890 
5891   Results.ExitScope();
5892 
5893   HandleCodeCompleteResults(this, CodeCompleter,
5894                             CodeCompletionContext::CCC_ObjCInterfaceName,
5895                             Results.data(),Results.size());
5896 }
5897 
5898 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
5899                                              IdentifierInfo *ClassName,
5900                                              SourceLocation ClassNameLoc) {
5901   typedef CodeCompletionResult Result;
5902 
5903   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5904                         CodeCompleter->getCodeCompletionTUInfo(),
5905                         CodeCompletionContext::CCC_ObjCCategoryName);
5906 
5907   // Ignore any categories we find that have already been implemented by this
5908   // interface.
5909   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5910   NamedDecl *CurClass
5911     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5912   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
5913     for (ObjCInterfaceDecl::visible_categories_iterator
5914            Cat = Class->visible_categories_begin(),
5915            CatEnd = Class->visible_categories_end();
5916          Cat != CatEnd; ++Cat) {
5917       CategoryNames.insert(Cat->getIdentifier());
5918     }
5919   }
5920 
5921   // Add all of the categories we know about.
5922   Results.EnterNewScope();
5923   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5924   for (DeclContext::decl_iterator D = TU->decls_begin(),
5925                                DEnd = TU->decls_end();
5926        D != DEnd; ++D)
5927     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5928       if (CategoryNames.insert(Category->getIdentifier()))
5929         Results.AddResult(Result(Category, Results.getBasePriority(Category),0),
5930                           CurContext, 0, false);
5931   Results.ExitScope();
5932 
5933   HandleCodeCompleteResults(this, CodeCompleter,
5934                             CodeCompletionContext::CCC_ObjCCategoryName,
5935                             Results.data(),Results.size());
5936 }
5937 
5938 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
5939                                                   IdentifierInfo *ClassName,
5940                                                   SourceLocation ClassNameLoc) {
5941   typedef CodeCompletionResult Result;
5942 
5943   // Find the corresponding interface. If we couldn't find the interface, the
5944   // program itself is ill-formed. However, we'll try to be helpful still by
5945   // providing the list of all of the categories we know about.
5946   NamedDecl *CurClass
5947     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5948   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5949   if (!Class)
5950     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
5951 
5952   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5953                         CodeCompleter->getCodeCompletionTUInfo(),
5954                         CodeCompletionContext::CCC_ObjCCategoryName);
5955 
5956   // Add all of the categories that have have corresponding interface
5957   // declarations in this class and any of its superclasses, except for
5958   // already-implemented categories in the class itself.
5959   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5960   Results.EnterNewScope();
5961   bool IgnoreImplemented = true;
5962   while (Class) {
5963     for (ObjCInterfaceDecl::visible_categories_iterator
5964            Cat = Class->visible_categories_begin(),
5965            CatEnd = Class->visible_categories_end();
5966          Cat != CatEnd; ++Cat) {
5967       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
5968           CategoryNames.insert(Cat->getIdentifier()))
5969         Results.AddResult(Result(*Cat, Results.getBasePriority(*Cat), 0),
5970                           CurContext, 0, false);
5971     }
5972 
5973     Class = Class->getSuperClass();
5974     IgnoreImplemented = false;
5975   }
5976   Results.ExitScope();
5977 
5978   HandleCodeCompleteResults(this, CodeCompleter,
5979                             CodeCompletionContext::CCC_ObjCCategoryName,
5980                             Results.data(),Results.size());
5981 }
5982 
5983 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
5984   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5985                         CodeCompleter->getCodeCompletionTUInfo(),
5986                         CodeCompletionContext::CCC_Other);
5987 
5988   // Figure out where this @synthesize lives.
5989   ObjCContainerDecl *Container
5990     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
5991   if (!Container ||
5992       (!isa<ObjCImplementationDecl>(Container) &&
5993        !isa<ObjCCategoryImplDecl>(Container)))
5994     return;
5995 
5996   // Ignore any properties that have already been implemented.
5997   Container = getContainerDef(Container);
5998   for (DeclContext::decl_iterator D = Container->decls_begin(),
5999                                DEnd = Container->decls_end();
6000        D != DEnd; ++D)
6001     if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
6002       Results.Ignore(PropertyImpl->getPropertyDecl());
6003 
6004   // Add any properties that we find.
6005   AddedPropertiesSet AddedProperties;
6006   Results.EnterNewScope();
6007   if (ObjCImplementationDecl *ClassImpl
6008         = dyn_cast<ObjCImplementationDecl>(Container))
6009     AddObjCProperties(ClassImpl->getClassInterface(), false,
6010                       /*AllowNullaryMethods=*/false, CurContext,
6011                       AddedProperties, Results);
6012   else
6013     AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6014                       false, /*AllowNullaryMethods=*/false, CurContext,
6015                       AddedProperties, Results);
6016   Results.ExitScope();
6017 
6018   HandleCodeCompleteResults(this, CodeCompleter,
6019                             CodeCompletionContext::CCC_Other,
6020                             Results.data(),Results.size());
6021 }
6022 
6023 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6024                                                   IdentifierInfo *PropertyName) {
6025   typedef CodeCompletionResult Result;
6026   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6027                         CodeCompleter->getCodeCompletionTUInfo(),
6028                         CodeCompletionContext::CCC_Other);
6029 
6030   // Figure out where this @synthesize lives.
6031   ObjCContainerDecl *Container
6032     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6033   if (!Container ||
6034       (!isa<ObjCImplementationDecl>(Container) &&
6035        !isa<ObjCCategoryImplDecl>(Container)))
6036     return;
6037 
6038   // Figure out which interface we're looking into.
6039   ObjCInterfaceDecl *Class = 0;
6040   if (ObjCImplementationDecl *ClassImpl
6041                                  = dyn_cast<ObjCImplementationDecl>(Container))
6042     Class = ClassImpl->getClassInterface();
6043   else
6044     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6045                                                           ->getClassInterface();
6046 
6047   // Determine the type of the property we're synthesizing.
6048   QualType PropertyType = Context.getObjCIdType();
6049   if (Class) {
6050     if (ObjCPropertyDecl *Property
6051                               = Class->FindPropertyDeclaration(PropertyName)) {
6052       PropertyType
6053         = Property->getType().getNonReferenceType().getUnqualifiedType();
6054 
6055       // Give preference to ivars
6056       Results.setPreferredType(PropertyType);
6057     }
6058   }
6059 
6060   // Add all of the instance variables in this class and its superclasses.
6061   Results.EnterNewScope();
6062   bool SawSimilarlyNamedIvar = false;
6063   std::string NameWithPrefix;
6064   NameWithPrefix += '_';
6065   NameWithPrefix += PropertyName->getName();
6066   std::string NameWithSuffix = PropertyName->getName().str();
6067   NameWithSuffix += '_';
6068   for(; Class; Class = Class->getSuperClass()) {
6069     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6070          Ivar = Ivar->getNextIvar()) {
6071       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), 0),
6072                         CurContext, 0, false);
6073 
6074       // Determine whether we've seen an ivar with a name similar to the
6075       // property.
6076       if ((PropertyName == Ivar->getIdentifier() ||
6077            NameWithPrefix == Ivar->getName() ||
6078            NameWithSuffix == Ivar->getName())) {
6079         SawSimilarlyNamedIvar = true;
6080 
6081         // Reduce the priority of this result by one, to give it a slight
6082         // advantage over other results whose names don't match so closely.
6083         if (Results.size() &&
6084             Results.data()[Results.size() - 1].Kind
6085                                       == CodeCompletionResult::RK_Declaration &&
6086             Results.data()[Results.size() - 1].Declaration == Ivar)
6087           Results.data()[Results.size() - 1].Priority--;
6088       }
6089     }
6090   }
6091 
6092   if (!SawSimilarlyNamedIvar) {
6093     // Create ivar result _propName, that the user can use to synthesize
6094     // an ivar of the appropriate type.
6095     unsigned Priority = CCP_MemberDeclaration + 1;
6096     typedef CodeCompletionResult Result;
6097     CodeCompletionAllocator &Allocator = Results.getAllocator();
6098     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6099                                   Priority,CXAvailability_Available);
6100 
6101     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6102     Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6103                                                        Policy, Allocator));
6104     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6105     Results.AddResult(Result(Builder.TakeString(), Priority,
6106                              CXCursor_ObjCIvarDecl));
6107   }
6108 
6109   Results.ExitScope();
6110 
6111   HandleCodeCompleteResults(this, CodeCompleter,
6112                             CodeCompletionContext::CCC_Other,
6113                             Results.data(),Results.size());
6114 }
6115 
6116 // Mapping from selectors to the methods that implement that selector, along
6117 // with the "in original class" flag.
6118 typedef llvm::DenseMap<
6119     Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6120 
6121 /// \brief Find all of the methods that reside in the given container
6122 /// (and its superclasses, protocols, etc.) that meet the given
6123 /// criteria. Insert those methods into the map of known methods,
6124 /// indexed by selector so they can be easily found.
6125 static void FindImplementableMethods(ASTContext &Context,
6126                                      ObjCContainerDecl *Container,
6127                                      bool WantInstanceMethods,
6128                                      QualType ReturnType,
6129                                      KnownMethodsMap &KnownMethods,
6130                                      bool InOriginalClass = true) {
6131   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6132     // Make sure we have a definition; that's what we'll walk.
6133     if (!IFace->hasDefinition())
6134       return;
6135 
6136     IFace = IFace->getDefinition();
6137     Container = IFace;
6138 
6139     const ObjCList<ObjCProtocolDecl> &Protocols
6140       = IFace->getReferencedProtocols();
6141     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6142                                               E = Protocols.end();
6143          I != E; ++I)
6144       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6145                                KnownMethods, InOriginalClass);
6146 
6147     // Add methods from any class extensions and categories.
6148     for (ObjCInterfaceDecl::visible_categories_iterator
6149            Cat = IFace->visible_categories_begin(),
6150            CatEnd = IFace->visible_categories_end();
6151          Cat != CatEnd; ++Cat) {
6152       FindImplementableMethods(Context, *Cat, WantInstanceMethods, ReturnType,
6153                                KnownMethods, false);
6154     }
6155 
6156     // Visit the superclass.
6157     if (IFace->getSuperClass())
6158       FindImplementableMethods(Context, IFace->getSuperClass(),
6159                                WantInstanceMethods, ReturnType,
6160                                KnownMethods, false);
6161   }
6162 
6163   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6164     // Recurse into protocols.
6165     const ObjCList<ObjCProtocolDecl> &Protocols
6166       = Category->getReferencedProtocols();
6167     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6168                                               E = Protocols.end();
6169          I != E; ++I)
6170       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6171                                KnownMethods, InOriginalClass);
6172 
6173     // If this category is the original class, jump to the interface.
6174     if (InOriginalClass && Category->getClassInterface())
6175       FindImplementableMethods(Context, Category->getClassInterface(),
6176                                WantInstanceMethods, ReturnType, KnownMethods,
6177                                false);
6178   }
6179 
6180   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6181     // Make sure we have a definition; that's what we'll walk.
6182     if (!Protocol->hasDefinition())
6183       return;
6184     Protocol = Protocol->getDefinition();
6185     Container = Protocol;
6186 
6187     // Recurse into protocols.
6188     const ObjCList<ObjCProtocolDecl> &Protocols
6189       = Protocol->getReferencedProtocols();
6190     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6191            E = Protocols.end();
6192          I != E; ++I)
6193       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6194                                KnownMethods, false);
6195   }
6196 
6197   // Add methods in this container. This operation occurs last because
6198   // we want the methods from this container to override any methods
6199   // we've previously seen with the same selector.
6200   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
6201                                        MEnd = Container->meth_end();
6202        M != MEnd; ++M) {
6203     if (M->isInstanceMethod() == WantInstanceMethods) {
6204       if (!ReturnType.isNull() &&
6205           !Context.hasSameUnqualifiedType(ReturnType, M->getResultType()))
6206         continue;
6207 
6208       KnownMethods[M->getSelector()] =
6209           KnownMethodsMap::mapped_type(*M, InOriginalClass);
6210     }
6211   }
6212 }
6213 
6214 /// \brief Add the parenthesized return or parameter type chunk to a code
6215 /// completion string.
6216 static void AddObjCPassingTypeChunk(QualType Type,
6217                                     unsigned ObjCDeclQuals,
6218                                     ASTContext &Context,
6219                                     const PrintingPolicy &Policy,
6220                                     CodeCompletionBuilder &Builder) {
6221   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6222   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6223   if (!Quals.empty())
6224     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6225   Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6226                                                Builder.getAllocator()));
6227   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6228 }
6229 
6230 /// \brief Determine whether the given class is or inherits from a class by
6231 /// the given name.
6232 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6233                                    StringRef Name) {
6234   if (!Class)
6235     return false;
6236 
6237   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6238     return true;
6239 
6240   return InheritsFromClassNamed(Class->getSuperClass(), Name);
6241 }
6242 
6243 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6244 /// Key-Value Observing (KVO).
6245 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6246                                        bool IsInstanceMethod,
6247                                        QualType ReturnType,
6248                                        ASTContext &Context,
6249                                        VisitedSelectorSet &KnownSelectors,
6250                                        ResultBuilder &Results) {
6251   IdentifierInfo *PropName = Property->getIdentifier();
6252   if (!PropName || PropName->getLength() == 0)
6253     return;
6254 
6255   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6256 
6257   // Builder that will create each code completion.
6258   typedef CodeCompletionResult Result;
6259   CodeCompletionAllocator &Allocator = Results.getAllocator();
6260   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6261 
6262   // The selector table.
6263   SelectorTable &Selectors = Context.Selectors;
6264 
6265   // The property name, copied into the code completion allocation region
6266   // on demand.
6267   struct KeyHolder {
6268     CodeCompletionAllocator &Allocator;
6269     StringRef Key;
6270     const char *CopiedKey;
6271 
6272     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6273     : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6274 
6275     operator const char *() {
6276       if (CopiedKey)
6277         return CopiedKey;
6278 
6279       return CopiedKey = Allocator.CopyString(Key);
6280     }
6281   } Key(Allocator, PropName->getName());
6282 
6283   // The uppercased name of the property name.
6284   std::string UpperKey = PropName->getName();
6285   if (!UpperKey.empty())
6286     UpperKey[0] = toUppercase(UpperKey[0]);
6287 
6288   bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6289     Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6290                                    Property->getType());
6291   bool ReturnTypeMatchesVoid
6292     = ReturnType.isNull() || ReturnType->isVoidType();
6293 
6294   // Add the normal accessor -(type)key.
6295   if (IsInstanceMethod &&
6296       KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
6297       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6298     if (ReturnType.isNull())
6299       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6300                               Context, Policy, Builder);
6301 
6302     Builder.AddTypedTextChunk(Key);
6303     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6304                              CXCursor_ObjCInstanceMethodDecl));
6305   }
6306 
6307   // If we have an integral or boolean property (or the user has provided
6308   // an integral or boolean return type), add the accessor -(type)isKey.
6309   if (IsInstanceMethod &&
6310       ((!ReturnType.isNull() &&
6311         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6312        (ReturnType.isNull() &&
6313         (Property->getType()->isIntegerType() ||
6314          Property->getType()->isBooleanType())))) {
6315     std::string SelectorName = (Twine("is") + UpperKey).str();
6316     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6317     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6318       if (ReturnType.isNull()) {
6319         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6320         Builder.AddTextChunk("BOOL");
6321         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6322       }
6323 
6324       Builder.AddTypedTextChunk(
6325                                 Allocator.CopyString(SelectorId->getName()));
6326       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6327                                CXCursor_ObjCInstanceMethodDecl));
6328     }
6329   }
6330 
6331   // Add the normal mutator.
6332   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6333       !Property->getSetterMethodDecl()) {
6334     std::string SelectorName = (Twine("set") + UpperKey).str();
6335     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6336     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6337       if (ReturnType.isNull()) {
6338         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6339         Builder.AddTextChunk("void");
6340         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6341       }
6342 
6343       Builder.AddTypedTextChunk(
6344                                 Allocator.CopyString(SelectorId->getName()));
6345       Builder.AddTypedTextChunk(":");
6346       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6347                               Context, Policy, Builder);
6348       Builder.AddTextChunk(Key);
6349       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6350                                CXCursor_ObjCInstanceMethodDecl));
6351     }
6352   }
6353 
6354   // Indexed and unordered accessors
6355   unsigned IndexedGetterPriority = CCP_CodePattern;
6356   unsigned IndexedSetterPriority = CCP_CodePattern;
6357   unsigned UnorderedGetterPriority = CCP_CodePattern;
6358   unsigned UnorderedSetterPriority = CCP_CodePattern;
6359   if (const ObjCObjectPointerType *ObjCPointer
6360                     = Property->getType()->getAs<ObjCObjectPointerType>()) {
6361     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6362       // If this interface type is not provably derived from a known
6363       // collection, penalize the corresponding completions.
6364       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6365         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6366         if (!InheritsFromClassNamed(IFace, "NSArray"))
6367           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6368       }
6369 
6370       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6371         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6372         if (!InheritsFromClassNamed(IFace, "NSSet"))
6373           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6374       }
6375     }
6376   } else {
6377     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6378     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6379     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6380     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6381   }
6382 
6383   // Add -(NSUInteger)countOf<key>
6384   if (IsInstanceMethod &&
6385       (ReturnType.isNull() || ReturnType->isIntegerType())) {
6386     std::string SelectorName = (Twine("countOf") + UpperKey).str();
6387     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6388     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6389       if (ReturnType.isNull()) {
6390         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6391         Builder.AddTextChunk("NSUInteger");
6392         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6393       }
6394 
6395       Builder.AddTypedTextChunk(
6396                                 Allocator.CopyString(SelectorId->getName()));
6397       Results.AddResult(Result(Builder.TakeString(),
6398                                std::min(IndexedGetterPriority,
6399                                         UnorderedGetterPriority),
6400                                CXCursor_ObjCInstanceMethodDecl));
6401     }
6402   }
6403 
6404   // Indexed getters
6405   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6406   if (IsInstanceMethod &&
6407       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6408     std::string SelectorName
6409       = (Twine("objectIn") + UpperKey + "AtIndex").str();
6410     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6411     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6412       if (ReturnType.isNull()) {
6413         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6414         Builder.AddTextChunk("id");
6415         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6416       }
6417 
6418       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6419       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6420       Builder.AddTextChunk("NSUInteger");
6421       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6422       Builder.AddTextChunk("index");
6423       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6424                                CXCursor_ObjCInstanceMethodDecl));
6425     }
6426   }
6427 
6428   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6429   if (IsInstanceMethod &&
6430       (ReturnType.isNull() ||
6431        (ReturnType->isObjCObjectPointerType() &&
6432         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6433         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6434                                                 ->getName() == "NSArray"))) {
6435     std::string SelectorName
6436       = (Twine(Property->getName()) + "AtIndexes").str();
6437     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6438     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6439       if (ReturnType.isNull()) {
6440         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6441         Builder.AddTextChunk("NSArray *");
6442         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6443       }
6444 
6445       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6446       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6447       Builder.AddTextChunk("NSIndexSet *");
6448       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6449       Builder.AddTextChunk("indexes");
6450       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6451                                CXCursor_ObjCInstanceMethodDecl));
6452     }
6453   }
6454 
6455   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6456   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6457     std::string SelectorName = (Twine("get") + UpperKey).str();
6458     IdentifierInfo *SelectorIds[2] = {
6459       &Context.Idents.get(SelectorName),
6460       &Context.Idents.get("range")
6461     };
6462 
6463     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6464       if (ReturnType.isNull()) {
6465         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6466         Builder.AddTextChunk("void");
6467         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6468       }
6469 
6470       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6471       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6472       Builder.AddPlaceholderChunk("object-type");
6473       Builder.AddTextChunk(" **");
6474       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6475       Builder.AddTextChunk("buffer");
6476       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6477       Builder.AddTypedTextChunk("range:");
6478       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6479       Builder.AddTextChunk("NSRange");
6480       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6481       Builder.AddTextChunk("inRange");
6482       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6483                                CXCursor_ObjCInstanceMethodDecl));
6484     }
6485   }
6486 
6487   // Mutable indexed accessors
6488 
6489   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6490   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6491     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6492     IdentifierInfo *SelectorIds[2] = {
6493       &Context.Idents.get("insertObject"),
6494       &Context.Idents.get(SelectorName)
6495     };
6496 
6497     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6498       if (ReturnType.isNull()) {
6499         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6500         Builder.AddTextChunk("void");
6501         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6502       }
6503 
6504       Builder.AddTypedTextChunk("insertObject:");
6505       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6506       Builder.AddPlaceholderChunk("object-type");
6507       Builder.AddTextChunk(" *");
6508       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6509       Builder.AddTextChunk("object");
6510       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6511       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6512       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6513       Builder.AddPlaceholderChunk("NSUInteger");
6514       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6515       Builder.AddTextChunk("index");
6516       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6517                                CXCursor_ObjCInstanceMethodDecl));
6518     }
6519   }
6520 
6521   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6522   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6523     std::string SelectorName = (Twine("insert") + UpperKey).str();
6524     IdentifierInfo *SelectorIds[2] = {
6525       &Context.Idents.get(SelectorName),
6526       &Context.Idents.get("atIndexes")
6527     };
6528 
6529     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6530       if (ReturnType.isNull()) {
6531         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6532         Builder.AddTextChunk("void");
6533         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6534       }
6535 
6536       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6537       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6538       Builder.AddTextChunk("NSArray *");
6539       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6540       Builder.AddTextChunk("array");
6541       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6542       Builder.AddTypedTextChunk("atIndexes:");
6543       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6544       Builder.AddPlaceholderChunk("NSIndexSet *");
6545       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6546       Builder.AddTextChunk("indexes");
6547       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6548                                CXCursor_ObjCInstanceMethodDecl));
6549     }
6550   }
6551 
6552   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6553   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6554     std::string SelectorName
6555       = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
6556     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6557     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6558       if (ReturnType.isNull()) {
6559         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6560         Builder.AddTextChunk("void");
6561         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6562       }
6563 
6564       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6565       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6566       Builder.AddTextChunk("NSUInteger");
6567       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6568       Builder.AddTextChunk("index");
6569       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6570                                CXCursor_ObjCInstanceMethodDecl));
6571     }
6572   }
6573 
6574   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6575   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6576     std::string SelectorName
6577       = (Twine("remove") + UpperKey + "AtIndexes").str();
6578     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6579     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6580       if (ReturnType.isNull()) {
6581         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6582         Builder.AddTextChunk("void");
6583         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6584       }
6585 
6586       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6587       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6588       Builder.AddTextChunk("NSIndexSet *");
6589       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6590       Builder.AddTextChunk("indexes");
6591       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6592                                CXCursor_ObjCInstanceMethodDecl));
6593     }
6594   }
6595 
6596   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6597   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6598     std::string SelectorName
6599       = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
6600     IdentifierInfo *SelectorIds[2] = {
6601       &Context.Idents.get(SelectorName),
6602       &Context.Idents.get("withObject")
6603     };
6604 
6605     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6606       if (ReturnType.isNull()) {
6607         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6608         Builder.AddTextChunk("void");
6609         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6610       }
6611 
6612       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6613       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6614       Builder.AddPlaceholderChunk("NSUInteger");
6615       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6616       Builder.AddTextChunk("index");
6617       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6618       Builder.AddTypedTextChunk("withObject:");
6619       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6620       Builder.AddTextChunk("id");
6621       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6622       Builder.AddTextChunk("object");
6623       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6624                                CXCursor_ObjCInstanceMethodDecl));
6625     }
6626   }
6627 
6628   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6629   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6630     std::string SelectorName1
6631       = (Twine("replace") + UpperKey + "AtIndexes").str();
6632     std::string SelectorName2 = (Twine("with") + UpperKey).str();
6633     IdentifierInfo *SelectorIds[2] = {
6634       &Context.Idents.get(SelectorName1),
6635       &Context.Idents.get(SelectorName2)
6636     };
6637 
6638     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6639       if (ReturnType.isNull()) {
6640         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6641         Builder.AddTextChunk("void");
6642         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6643       }
6644 
6645       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6646       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6647       Builder.AddPlaceholderChunk("NSIndexSet *");
6648       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6649       Builder.AddTextChunk("indexes");
6650       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6651       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6652       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6653       Builder.AddTextChunk("NSArray *");
6654       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6655       Builder.AddTextChunk("array");
6656       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6657                                CXCursor_ObjCInstanceMethodDecl));
6658     }
6659   }
6660 
6661   // Unordered getters
6662   // - (NSEnumerator *)enumeratorOfKey
6663   if (IsInstanceMethod &&
6664       (ReturnType.isNull() ||
6665        (ReturnType->isObjCObjectPointerType() &&
6666         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6667         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6668           ->getName() == "NSEnumerator"))) {
6669     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
6670     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6671     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6672       if (ReturnType.isNull()) {
6673         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6674         Builder.AddTextChunk("NSEnumerator *");
6675         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6676       }
6677 
6678       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6679       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6680                               CXCursor_ObjCInstanceMethodDecl));
6681     }
6682   }
6683 
6684   // - (type *)memberOfKey:(type *)object
6685   if (IsInstanceMethod &&
6686       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6687     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
6688     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6689     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6690       if (ReturnType.isNull()) {
6691         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6692         Builder.AddPlaceholderChunk("object-type");
6693         Builder.AddTextChunk(" *");
6694         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6695       }
6696 
6697       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6698       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6699       if (ReturnType.isNull()) {
6700         Builder.AddPlaceholderChunk("object-type");
6701         Builder.AddTextChunk(" *");
6702       } else {
6703         Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6704                                                      Policy,
6705                                                      Builder.getAllocator()));
6706       }
6707       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6708       Builder.AddTextChunk("object");
6709       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6710                                CXCursor_ObjCInstanceMethodDecl));
6711     }
6712   }
6713 
6714   // Mutable unordered accessors
6715   // - (void)addKeyObject:(type *)object
6716   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6717     std::string SelectorName
6718       = (Twine("add") + UpperKey + Twine("Object")).str();
6719     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6720     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6721       if (ReturnType.isNull()) {
6722         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6723         Builder.AddTextChunk("void");
6724         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6725       }
6726 
6727       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6728       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6729       Builder.AddPlaceholderChunk("object-type");
6730       Builder.AddTextChunk(" *");
6731       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6732       Builder.AddTextChunk("object");
6733       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6734                                CXCursor_ObjCInstanceMethodDecl));
6735     }
6736   }
6737 
6738   // - (void)addKey:(NSSet *)objects
6739   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6740     std::string SelectorName = (Twine("add") + UpperKey).str();
6741     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6742     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6743       if (ReturnType.isNull()) {
6744         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6745         Builder.AddTextChunk("void");
6746         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6747       }
6748 
6749       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6750       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6751       Builder.AddTextChunk("NSSet *");
6752       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6753       Builder.AddTextChunk("objects");
6754       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6755                                CXCursor_ObjCInstanceMethodDecl));
6756     }
6757   }
6758 
6759   // - (void)removeKeyObject:(type *)object
6760   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6761     std::string SelectorName
6762       = (Twine("remove") + UpperKey + Twine("Object")).str();
6763     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6764     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6765       if (ReturnType.isNull()) {
6766         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6767         Builder.AddTextChunk("void");
6768         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6769       }
6770 
6771       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6772       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6773       Builder.AddPlaceholderChunk("object-type");
6774       Builder.AddTextChunk(" *");
6775       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6776       Builder.AddTextChunk("object");
6777       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6778                                CXCursor_ObjCInstanceMethodDecl));
6779     }
6780   }
6781 
6782   // - (void)removeKey:(NSSet *)objects
6783   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6784     std::string SelectorName = (Twine("remove") + UpperKey).str();
6785     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6786     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6787       if (ReturnType.isNull()) {
6788         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6789         Builder.AddTextChunk("void");
6790         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6791       }
6792 
6793       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6794       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6795       Builder.AddTextChunk("NSSet *");
6796       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6797       Builder.AddTextChunk("objects");
6798       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6799                                CXCursor_ObjCInstanceMethodDecl));
6800     }
6801   }
6802 
6803   // - (void)intersectKey:(NSSet *)objects
6804   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6805     std::string SelectorName = (Twine("intersect") + UpperKey).str();
6806     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6807     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6808       if (ReturnType.isNull()) {
6809         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6810         Builder.AddTextChunk("void");
6811         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6812       }
6813 
6814       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6815       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6816       Builder.AddTextChunk("NSSet *");
6817       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6818       Builder.AddTextChunk("objects");
6819       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6820                                CXCursor_ObjCInstanceMethodDecl));
6821     }
6822   }
6823 
6824   // Key-Value Observing
6825   // + (NSSet *)keyPathsForValuesAffectingKey
6826   if (!IsInstanceMethod &&
6827       (ReturnType.isNull() ||
6828        (ReturnType->isObjCObjectPointerType() &&
6829         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6830         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6831                                                     ->getName() == "NSSet"))) {
6832     std::string SelectorName
6833       = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
6834     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6835     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6836       if (ReturnType.isNull()) {
6837         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6838         Builder.AddTextChunk("NSSet *");
6839         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6840       }
6841 
6842       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6843       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6844                               CXCursor_ObjCClassMethodDecl));
6845     }
6846   }
6847 
6848   // + (BOOL)automaticallyNotifiesObserversForKey
6849   if (!IsInstanceMethod &&
6850       (ReturnType.isNull() ||
6851        ReturnType->isIntegerType() ||
6852        ReturnType->isBooleanType())) {
6853     std::string SelectorName
6854       = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
6855     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6856     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6857       if (ReturnType.isNull()) {
6858         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6859         Builder.AddTextChunk("BOOL");
6860         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6861       }
6862 
6863       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6864       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6865                               CXCursor_ObjCClassMethodDecl));
6866     }
6867   }
6868 }
6869 
6870 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6871                                       bool IsInstanceMethod,
6872                                       ParsedType ReturnTy) {
6873   // Determine the return type of the method we're declaring, if
6874   // provided.
6875   QualType ReturnType = GetTypeFromParser(ReturnTy);
6876   Decl *IDecl = 0;
6877   if (CurContext->isObjCContainer()) {
6878       ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6879       IDecl = cast<Decl>(OCD);
6880   }
6881   // Determine where we should start searching for methods.
6882   ObjCContainerDecl *SearchDecl = 0;
6883   bool IsInImplementation = false;
6884   if (Decl *D = IDecl) {
6885     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6886       SearchDecl = Impl->getClassInterface();
6887       IsInImplementation = true;
6888     } else if (ObjCCategoryImplDecl *CatImpl
6889                                          = dyn_cast<ObjCCategoryImplDecl>(D)) {
6890       SearchDecl = CatImpl->getCategoryDecl();
6891       IsInImplementation = true;
6892     } else
6893       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
6894   }
6895 
6896   if (!SearchDecl && S) {
6897     if (DeclContext *DC = S->getEntity())
6898       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
6899   }
6900 
6901   if (!SearchDecl) {
6902     HandleCodeCompleteResults(this, CodeCompleter,
6903                               CodeCompletionContext::CCC_Other,
6904                               0, 0);
6905     return;
6906   }
6907 
6908   // Find all of the methods that we could declare/implement here.
6909   KnownMethodsMap KnownMethods;
6910   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
6911                            ReturnType, KnownMethods);
6912 
6913   // Add declarations or definitions for each of the known methods.
6914   typedef CodeCompletionResult Result;
6915   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6916                         CodeCompleter->getCodeCompletionTUInfo(),
6917                         CodeCompletionContext::CCC_Other);
6918   Results.EnterNewScope();
6919   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6920   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6921                               MEnd = KnownMethods.end();
6922        M != MEnd; ++M) {
6923     ObjCMethodDecl *Method = M->second.getPointer();
6924     CodeCompletionBuilder Builder(Results.getAllocator(),
6925                                   Results.getCodeCompletionTUInfo());
6926 
6927     // If the result type was not already provided, add it to the
6928     // pattern as (type).
6929     if (ReturnType.isNull())
6930       AddObjCPassingTypeChunk(Method->getResultType(),
6931                               Method->getObjCDeclQualifier(),
6932                               Context, Policy,
6933                               Builder);
6934 
6935     Selector Sel = Method->getSelector();
6936 
6937     // Add the first part of the selector to the pattern.
6938     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6939                                                        Sel.getNameForSlot(0)));
6940 
6941     // Add parameters to the pattern.
6942     unsigned I = 0;
6943     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6944                                      PEnd = Method->param_end();
6945          P != PEnd; (void)++P, ++I) {
6946       // Add the part of the selector name.
6947       if (I == 0)
6948         Builder.AddTypedTextChunk(":");
6949       else if (I < Sel.getNumArgs()) {
6950         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6951         Builder.AddTypedTextChunk(
6952                 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6953       } else
6954         break;
6955 
6956       // Add the parameter type.
6957       AddObjCPassingTypeChunk((*P)->getOriginalType(),
6958                               (*P)->getObjCDeclQualifier(),
6959                               Context, Policy,
6960                               Builder);
6961 
6962       if (IdentifierInfo *Id = (*P)->getIdentifier())
6963         Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
6964     }
6965 
6966     if (Method->isVariadic()) {
6967       if (Method->param_size() > 0)
6968         Builder.AddChunk(CodeCompletionString::CK_Comma);
6969       Builder.AddTextChunk("...");
6970     }
6971 
6972     if (IsInImplementation && Results.includeCodePatterns()) {
6973       // We will be defining the method here, so add a compound statement.
6974       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6975       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6976       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6977       if (!Method->getResultType()->isVoidType()) {
6978         // If the result type is not void, add a return clause.
6979         Builder.AddTextChunk("return");
6980         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6981         Builder.AddPlaceholderChunk("expression");
6982         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6983       } else
6984         Builder.AddPlaceholderChunk("statements");
6985 
6986       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6987       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6988     }
6989 
6990     unsigned Priority = CCP_CodePattern;
6991     if (!M->second.getInt())
6992       Priority += CCD_InBaseClass;
6993 
6994     Results.AddResult(Result(Builder.TakeString(), Method, Priority));
6995   }
6996 
6997   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6998   // the properties in this class and its categories.
6999   if (Context.getLangOpts().ObjC2) {
7000     SmallVector<ObjCContainerDecl *, 4> Containers;
7001     Containers.push_back(SearchDecl);
7002 
7003     VisitedSelectorSet KnownSelectors;
7004     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7005                                 MEnd = KnownMethods.end();
7006          M != MEnd; ++M)
7007       KnownSelectors.insert(M->first);
7008 
7009 
7010     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7011     if (!IFace)
7012       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7013         IFace = Category->getClassInterface();
7014 
7015     if (IFace) {
7016       for (ObjCInterfaceDecl::visible_categories_iterator
7017              Cat = IFace->visible_categories_begin(),
7018              CatEnd = IFace->visible_categories_end();
7019            Cat != CatEnd; ++Cat) {
7020         Containers.push_back(*Cat);
7021       }
7022     }
7023 
7024     for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
7025       for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
7026                                          PEnd = Containers[I]->prop_end();
7027            P != PEnd; ++P) {
7028         AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
7029                                    KnownSelectors, Results);
7030       }
7031     }
7032   }
7033 
7034   Results.ExitScope();
7035 
7036   HandleCodeCompleteResults(this, CodeCompleter,
7037                             CodeCompletionContext::CCC_Other,
7038                             Results.data(),Results.size());
7039 }
7040 
7041 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7042                                               bool IsInstanceMethod,
7043                                               bool AtParameterName,
7044                                               ParsedType ReturnTy,
7045                                          ArrayRef<IdentifierInfo *> SelIdents) {
7046   // If we have an external source, load the entire class method
7047   // pool from the AST file.
7048   if (ExternalSource) {
7049     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7050          I != N; ++I) {
7051       Selector Sel = ExternalSource->GetExternalSelector(I);
7052       if (Sel.isNull() || MethodPool.count(Sel))
7053         continue;
7054 
7055       ReadMethodPool(Sel);
7056     }
7057   }
7058 
7059   // Build the set of methods we can see.
7060   typedef CodeCompletionResult Result;
7061   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7062                         CodeCompleter->getCodeCompletionTUInfo(),
7063                         CodeCompletionContext::CCC_Other);
7064 
7065   if (ReturnTy)
7066     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7067 
7068   Results.EnterNewScope();
7069   for (GlobalMethodPool::iterator M = MethodPool.begin(),
7070                                   MEnd = MethodPool.end();
7071        M != MEnd; ++M) {
7072     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7073                                                        &M->second.second;
7074          MethList && MethList->Method;
7075          MethList = MethList->getNext()) {
7076       if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
7077         continue;
7078 
7079       if (AtParameterName) {
7080         // Suggest parameter names we've seen before.
7081         unsigned NumSelIdents = SelIdents.size();
7082         if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
7083           ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
7084           if (Param->getIdentifier()) {
7085             CodeCompletionBuilder Builder(Results.getAllocator(),
7086                                           Results.getCodeCompletionTUInfo());
7087             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7088                                            Param->getIdentifier()->getName()));
7089             Results.AddResult(Builder.TakeString());
7090           }
7091         }
7092 
7093         continue;
7094       }
7095 
7096       Result R(MethList->Method, Results.getBasePriority(MethList->Method), 0);
7097       R.StartParameter = SelIdents.size();
7098       R.AllParametersAreInformative = false;
7099       R.DeclaringEntity = true;
7100       Results.MaybeAddResult(R, CurContext);
7101     }
7102   }
7103 
7104   Results.ExitScope();
7105   HandleCodeCompleteResults(this, CodeCompleter,
7106                             CodeCompletionContext::CCC_Other,
7107                             Results.data(),Results.size());
7108 }
7109 
7110 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7111   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7112                         CodeCompleter->getCodeCompletionTUInfo(),
7113                         CodeCompletionContext::CCC_PreprocessorDirective);
7114   Results.EnterNewScope();
7115 
7116   // #if <condition>
7117   CodeCompletionBuilder Builder(Results.getAllocator(),
7118                                 Results.getCodeCompletionTUInfo());
7119   Builder.AddTypedTextChunk("if");
7120   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7121   Builder.AddPlaceholderChunk("condition");
7122   Results.AddResult(Builder.TakeString());
7123 
7124   // #ifdef <macro>
7125   Builder.AddTypedTextChunk("ifdef");
7126   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7127   Builder.AddPlaceholderChunk("macro");
7128   Results.AddResult(Builder.TakeString());
7129 
7130   // #ifndef <macro>
7131   Builder.AddTypedTextChunk("ifndef");
7132   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7133   Builder.AddPlaceholderChunk("macro");
7134   Results.AddResult(Builder.TakeString());
7135 
7136   if (InConditional) {
7137     // #elif <condition>
7138     Builder.AddTypedTextChunk("elif");
7139     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7140     Builder.AddPlaceholderChunk("condition");
7141     Results.AddResult(Builder.TakeString());
7142 
7143     // #else
7144     Builder.AddTypedTextChunk("else");
7145     Results.AddResult(Builder.TakeString());
7146 
7147     // #endif
7148     Builder.AddTypedTextChunk("endif");
7149     Results.AddResult(Builder.TakeString());
7150   }
7151 
7152   // #include "header"
7153   Builder.AddTypedTextChunk("include");
7154   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7155   Builder.AddTextChunk("\"");
7156   Builder.AddPlaceholderChunk("header");
7157   Builder.AddTextChunk("\"");
7158   Results.AddResult(Builder.TakeString());
7159 
7160   // #include <header>
7161   Builder.AddTypedTextChunk("include");
7162   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7163   Builder.AddTextChunk("<");
7164   Builder.AddPlaceholderChunk("header");
7165   Builder.AddTextChunk(">");
7166   Results.AddResult(Builder.TakeString());
7167 
7168   // #define <macro>
7169   Builder.AddTypedTextChunk("define");
7170   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7171   Builder.AddPlaceholderChunk("macro");
7172   Results.AddResult(Builder.TakeString());
7173 
7174   // #define <macro>(<args>)
7175   Builder.AddTypedTextChunk("define");
7176   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7177   Builder.AddPlaceholderChunk("macro");
7178   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7179   Builder.AddPlaceholderChunk("args");
7180   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7181   Results.AddResult(Builder.TakeString());
7182 
7183   // #undef <macro>
7184   Builder.AddTypedTextChunk("undef");
7185   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7186   Builder.AddPlaceholderChunk("macro");
7187   Results.AddResult(Builder.TakeString());
7188 
7189   // #line <number>
7190   Builder.AddTypedTextChunk("line");
7191   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7192   Builder.AddPlaceholderChunk("number");
7193   Results.AddResult(Builder.TakeString());
7194 
7195   // #line <number> "filename"
7196   Builder.AddTypedTextChunk("line");
7197   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7198   Builder.AddPlaceholderChunk("number");
7199   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7200   Builder.AddTextChunk("\"");
7201   Builder.AddPlaceholderChunk("filename");
7202   Builder.AddTextChunk("\"");
7203   Results.AddResult(Builder.TakeString());
7204 
7205   // #error <message>
7206   Builder.AddTypedTextChunk("error");
7207   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7208   Builder.AddPlaceholderChunk("message");
7209   Results.AddResult(Builder.TakeString());
7210 
7211   // #pragma <arguments>
7212   Builder.AddTypedTextChunk("pragma");
7213   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7214   Builder.AddPlaceholderChunk("arguments");
7215   Results.AddResult(Builder.TakeString());
7216 
7217   if (getLangOpts().ObjC1) {
7218     // #import "header"
7219     Builder.AddTypedTextChunk("import");
7220     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7221     Builder.AddTextChunk("\"");
7222     Builder.AddPlaceholderChunk("header");
7223     Builder.AddTextChunk("\"");
7224     Results.AddResult(Builder.TakeString());
7225 
7226     // #import <header>
7227     Builder.AddTypedTextChunk("import");
7228     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7229     Builder.AddTextChunk("<");
7230     Builder.AddPlaceholderChunk("header");
7231     Builder.AddTextChunk(">");
7232     Results.AddResult(Builder.TakeString());
7233   }
7234 
7235   // #include_next "header"
7236   Builder.AddTypedTextChunk("include_next");
7237   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7238   Builder.AddTextChunk("\"");
7239   Builder.AddPlaceholderChunk("header");
7240   Builder.AddTextChunk("\"");
7241   Results.AddResult(Builder.TakeString());
7242 
7243   // #include_next <header>
7244   Builder.AddTypedTextChunk("include_next");
7245   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7246   Builder.AddTextChunk("<");
7247   Builder.AddPlaceholderChunk("header");
7248   Builder.AddTextChunk(">");
7249   Results.AddResult(Builder.TakeString());
7250 
7251   // #warning <message>
7252   Builder.AddTypedTextChunk("warning");
7253   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7254   Builder.AddPlaceholderChunk("message");
7255   Results.AddResult(Builder.TakeString());
7256 
7257   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7258   // completions for them. And __include_macros is a Clang-internal extension
7259   // that we don't want to encourage anyone to use.
7260 
7261   // FIXME: we don't support #assert or #unassert, so don't suggest them.
7262   Results.ExitScope();
7263 
7264   HandleCodeCompleteResults(this, CodeCompleter,
7265                             CodeCompletionContext::CCC_PreprocessorDirective,
7266                             Results.data(), Results.size());
7267 }
7268 
7269 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7270   CodeCompleteOrdinaryName(S,
7271                            S->getFnParent()? Sema::PCC_RecoveryInFunction
7272                                            : Sema::PCC_Namespace);
7273 }
7274 
7275 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7276   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7277                         CodeCompleter->getCodeCompletionTUInfo(),
7278                         IsDefinition? CodeCompletionContext::CCC_MacroName
7279                                     : CodeCompletionContext::CCC_MacroNameUse);
7280   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7281     // Add just the names of macros, not their arguments.
7282     CodeCompletionBuilder Builder(Results.getAllocator(),
7283                                   Results.getCodeCompletionTUInfo());
7284     Results.EnterNewScope();
7285     for (Preprocessor::macro_iterator M = PP.macro_begin(),
7286                                    MEnd = PP.macro_end();
7287          M != MEnd; ++M) {
7288       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7289                                            M->first->getName()));
7290       Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7291                                              CCP_CodePattern,
7292                                              CXCursor_MacroDefinition));
7293     }
7294     Results.ExitScope();
7295   } else if (IsDefinition) {
7296     // FIXME: Can we detect when the user just wrote an include guard above?
7297   }
7298 
7299   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7300                             Results.data(), Results.size());
7301 }
7302 
7303 void Sema::CodeCompletePreprocessorExpression() {
7304   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7305                         CodeCompleter->getCodeCompletionTUInfo(),
7306                         CodeCompletionContext::CCC_PreprocessorExpression);
7307 
7308   if (!CodeCompleter || CodeCompleter->includeMacros())
7309     AddMacroResults(PP, Results, true);
7310 
7311     // defined (<macro>)
7312   Results.EnterNewScope();
7313   CodeCompletionBuilder Builder(Results.getAllocator(),
7314                                 Results.getCodeCompletionTUInfo());
7315   Builder.AddTypedTextChunk("defined");
7316   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7317   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7318   Builder.AddPlaceholderChunk("macro");
7319   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7320   Results.AddResult(Builder.TakeString());
7321   Results.ExitScope();
7322 
7323   HandleCodeCompleteResults(this, CodeCompleter,
7324                             CodeCompletionContext::CCC_PreprocessorExpression,
7325                             Results.data(), Results.size());
7326 }
7327 
7328 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7329                                                  IdentifierInfo *Macro,
7330                                                  MacroInfo *MacroInfo,
7331                                                  unsigned Argument) {
7332   // FIXME: In the future, we could provide "overload" results, much like we
7333   // do for function calls.
7334 
7335   // Now just ignore this. There will be another code-completion callback
7336   // for the expanded tokens.
7337 }
7338 
7339 void Sema::CodeCompleteNaturalLanguage() {
7340   HandleCodeCompleteResults(this, CodeCompleter,
7341                             CodeCompletionContext::CCC_NaturalLanguage,
7342                             0, 0);
7343 }
7344 
7345 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7346                                        CodeCompletionTUInfo &CCTUInfo,
7347                  SmallVectorImpl<CodeCompletionResult> &Results) {
7348   ResultBuilder Builder(*this, Allocator, CCTUInfo,
7349                         CodeCompletionContext::CCC_Recovery);
7350   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7351     CodeCompletionDeclConsumer Consumer(Builder,
7352                                         Context.getTranslationUnitDecl());
7353     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7354                        Consumer);
7355   }
7356 
7357   if (!CodeCompleter || CodeCompleter->includeMacros())
7358     AddMacroResults(PP, Builder, true);
7359 
7360   Results.clear();
7361   Results.insert(Results.end(),
7362                  Builder.data(), Builder.data() + Builder.size());
7363 }
7364