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