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