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