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