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