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