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   typedef CodeCompletionString::Chunk Chunk;
2184   bool FirstParameter = true;
2185 
2186   for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2187     ParmVarDecl *Param = Function->getParamDecl(P);
2188 
2189     if (Param->hasDefaultArg() && !InOptional) {
2190       // When we see an optional default argument, put that argument and
2191       // the remaining default arguments into a new, optional string.
2192       CodeCompletionBuilder Opt(Result.getAllocator());
2193       if (!FirstParameter)
2194         Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2195       AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
2196       Result.AddOptionalChunk(Opt.TakeString());
2197       break;
2198     }
2199 
2200     if (FirstParameter)
2201       FirstParameter = false;
2202     else
2203       Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2204 
2205     InOptional = false;
2206 
2207     // Format the placeholder string.
2208     std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2209                                                          Param);
2210 
2211     if (Function->isVariadic() && P == N - 1)
2212       PlaceholderStr += ", ...";
2213 
2214     // Add the placeholder string.
2215     Result.AddPlaceholderChunk(
2216                              Result.getAllocator().CopyString(PlaceholderStr));
2217   }
2218 
2219   if (const FunctionProtoType *Proto
2220         = Function->getType()->getAs<FunctionProtoType>())
2221     if (Proto->isVariadic()) {
2222       if (Proto->getNumArgs() == 0)
2223         Result.AddPlaceholderChunk("...");
2224 
2225       MaybeAddSentinel(Context, Function, Result);
2226     }
2227 }
2228 
2229 /// \brief Add template parameter chunks to the given code completion string.
2230 static void AddTemplateParameterChunks(ASTContext &Context,
2231                                        const PrintingPolicy &Policy,
2232                                        TemplateDecl *Template,
2233                                        CodeCompletionBuilder &Result,
2234                                        unsigned MaxParameters = 0,
2235                                        unsigned Start = 0,
2236                                        bool InDefaultArg = false) {
2237   typedef CodeCompletionString::Chunk Chunk;
2238   bool FirstParameter = true;
2239 
2240   TemplateParameterList *Params = Template->getTemplateParameters();
2241   TemplateParameterList::iterator PEnd = Params->end();
2242   if (MaxParameters)
2243     PEnd = Params->begin() + MaxParameters;
2244   for (TemplateParameterList::iterator P = Params->begin() + Start;
2245        P != PEnd; ++P) {
2246     bool HasDefaultArg = false;
2247     std::string PlaceholderStr;
2248     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2249       if (TTP->wasDeclaredWithTypename())
2250         PlaceholderStr = "typename";
2251       else
2252         PlaceholderStr = "class";
2253 
2254       if (TTP->getIdentifier()) {
2255         PlaceholderStr += ' ';
2256         PlaceholderStr += TTP->getIdentifier()->getName();
2257       }
2258 
2259       HasDefaultArg = TTP->hasDefaultArgument();
2260     } else if (NonTypeTemplateParmDecl *NTTP
2261                                     = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2262       if (NTTP->getIdentifier())
2263         PlaceholderStr = NTTP->getIdentifier()->getName();
2264       NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2265       HasDefaultArg = NTTP->hasDefaultArgument();
2266     } else {
2267       assert(isa<TemplateTemplateParmDecl>(*P));
2268       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2269 
2270       // Since putting the template argument list into the placeholder would
2271       // be very, very long, we just use an abbreviation.
2272       PlaceholderStr = "template<...> class";
2273       if (TTP->getIdentifier()) {
2274         PlaceholderStr += ' ';
2275         PlaceholderStr += TTP->getIdentifier()->getName();
2276       }
2277 
2278       HasDefaultArg = TTP->hasDefaultArgument();
2279     }
2280 
2281     if (HasDefaultArg && !InDefaultArg) {
2282       // When we see an optional default argument, put that argument and
2283       // the remaining default arguments into a new, optional string.
2284       CodeCompletionBuilder Opt(Result.getAllocator());
2285       if (!FirstParameter)
2286         Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2287       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2288                                  P - Params->begin(), true);
2289       Result.AddOptionalChunk(Opt.TakeString());
2290       break;
2291     }
2292 
2293     InDefaultArg = false;
2294 
2295     if (FirstParameter)
2296       FirstParameter = false;
2297     else
2298       Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2299 
2300     // Add the placeholder string.
2301     Result.AddPlaceholderChunk(
2302                               Result.getAllocator().CopyString(PlaceholderStr));
2303   }
2304 }
2305 
2306 /// \brief Add a qualifier to the given code-completion string, if the
2307 /// provided nested-name-specifier is non-NULL.
2308 static void
2309 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2310                                NestedNameSpecifier *Qualifier,
2311                                bool QualifierIsInformative,
2312                                ASTContext &Context,
2313                                const PrintingPolicy &Policy) {
2314   if (!Qualifier)
2315     return;
2316 
2317   std::string PrintedNNS;
2318   {
2319     llvm::raw_string_ostream OS(PrintedNNS);
2320     Qualifier->print(OS, Policy);
2321   }
2322   if (QualifierIsInformative)
2323     Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2324   else
2325     Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2326 }
2327 
2328 static void
2329 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2330                                        FunctionDecl *Function) {
2331   const FunctionProtoType *Proto
2332     = Function->getType()->getAs<FunctionProtoType>();
2333   if (!Proto || !Proto->getTypeQuals())
2334     return;
2335 
2336   // FIXME: Add ref-qualifier!
2337 
2338   // Handle single qualifiers without copying
2339   if (Proto->getTypeQuals() == Qualifiers::Const) {
2340     Result.AddInformativeChunk(" const");
2341     return;
2342   }
2343 
2344   if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2345     Result.AddInformativeChunk(" volatile");
2346     return;
2347   }
2348 
2349   if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2350     Result.AddInformativeChunk(" restrict");
2351     return;
2352   }
2353 
2354   // Handle multiple qualifiers.
2355   std::string QualsStr;
2356   if (Proto->getTypeQuals() & Qualifiers::Const)
2357     QualsStr += " const";
2358   if (Proto->getTypeQuals() & Qualifiers::Volatile)
2359     QualsStr += " volatile";
2360   if (Proto->getTypeQuals() & Qualifiers::Restrict)
2361     QualsStr += " restrict";
2362   Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2363 }
2364 
2365 /// \brief Add the name of the given declaration
2366 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2367                               NamedDecl *ND, CodeCompletionBuilder &Result) {
2368   typedef CodeCompletionString::Chunk Chunk;
2369 
2370   DeclarationName Name = ND->getDeclName();
2371   if (!Name)
2372     return;
2373 
2374   switch (Name.getNameKind()) {
2375     case DeclarationName::CXXOperatorName: {
2376       const char *OperatorName = 0;
2377       switch (Name.getCXXOverloadedOperator()) {
2378       case OO_None:
2379       case OO_Conditional:
2380       case NUM_OVERLOADED_OPERATORS:
2381         OperatorName = "operator";
2382         break;
2383 
2384 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2385       case OO_##Name: OperatorName = "operator" Spelling; break;
2386 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2387 #include "clang/Basic/OperatorKinds.def"
2388 
2389       case OO_New:          OperatorName = "operator new"; break;
2390       case OO_Delete:       OperatorName = "operator delete"; break;
2391       case OO_Array_New:    OperatorName = "operator new[]"; break;
2392       case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2393       case OO_Call:         OperatorName = "operator()"; break;
2394       case OO_Subscript:    OperatorName = "operator[]"; break;
2395       }
2396       Result.AddTypedTextChunk(OperatorName);
2397       break;
2398     }
2399 
2400   case DeclarationName::Identifier:
2401   case DeclarationName::CXXConversionFunctionName:
2402   case DeclarationName::CXXDestructorName:
2403   case DeclarationName::CXXLiteralOperatorName:
2404     Result.AddTypedTextChunk(
2405                       Result.getAllocator().CopyString(ND->getNameAsString()));
2406     break;
2407 
2408   case DeclarationName::CXXUsingDirective:
2409   case DeclarationName::ObjCZeroArgSelector:
2410   case DeclarationName::ObjCOneArgSelector:
2411   case DeclarationName::ObjCMultiArgSelector:
2412     break;
2413 
2414   case DeclarationName::CXXConstructorName: {
2415     CXXRecordDecl *Record = 0;
2416     QualType Ty = Name.getCXXNameType();
2417     if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2418       Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2419     else if (const InjectedClassNameType *InjectedTy
2420                                         = Ty->getAs<InjectedClassNameType>())
2421       Record = InjectedTy->getDecl();
2422     else {
2423       Result.AddTypedTextChunk(
2424                       Result.getAllocator().CopyString(ND->getNameAsString()));
2425       break;
2426     }
2427 
2428     Result.AddTypedTextChunk(
2429                   Result.getAllocator().CopyString(Record->getNameAsString()));
2430     if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2431       Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2432       AddTemplateParameterChunks(Context, Policy, Template, Result);
2433       Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2434     }
2435     break;
2436   }
2437   }
2438 }
2439 
2440 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2441                                          CodeCompletionAllocator &Allocator) {
2442   return CreateCodeCompletionString(S.Context, S.PP, Allocator);
2443 }
2444 
2445 /// \brief If possible, create a new code completion string for the given
2446 /// result.
2447 ///
2448 /// \returns Either a new, heap-allocated code completion string describing
2449 /// how to use this result, or NULL to indicate that the string or name of the
2450 /// result is all that is needed.
2451 CodeCompletionString *
2452 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2453                                                  Preprocessor &PP,
2454                                            CodeCompletionAllocator &Allocator) {
2455   typedef CodeCompletionString::Chunk Chunk;
2456   CodeCompletionBuilder Result(Allocator, Priority, Availability);
2457 
2458   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2459   if (Kind == RK_Pattern) {
2460     Pattern->Priority = Priority;
2461     Pattern->Availability = Availability;
2462     return Pattern;
2463   }
2464 
2465   if (Kind == RK_Keyword) {
2466     Result.AddTypedTextChunk(Keyword);
2467     return Result.TakeString();
2468   }
2469 
2470   if (Kind == RK_Macro) {
2471     MacroInfo *MI = PP.getMacroInfo(Macro);
2472     assert(MI && "Not a macro?");
2473 
2474     Result.AddTypedTextChunk(
2475                             Result.getAllocator().CopyString(Macro->getName()));
2476 
2477     if (!MI->isFunctionLike())
2478       return Result.TakeString();
2479 
2480     // Format a function-like macro with placeholders for the arguments.
2481     Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2482     MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2483 
2484     // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2485     if (MI->isC99Varargs()) {
2486       --AEnd;
2487 
2488       if (A == AEnd) {
2489         Result.AddPlaceholderChunk("...");
2490       }
2491     }
2492 
2493     for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
2494       if (A != MI->arg_begin())
2495         Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2496 
2497       if (MI->isVariadic() && (A+1) == AEnd) {
2498         SmallString<32> Arg = (*A)->getName();
2499         if (MI->isC99Varargs())
2500           Arg += ", ...";
2501         else
2502           Arg += "...";
2503         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2504         break;
2505       }
2506 
2507       // Non-variadic macros are simple.
2508       Result.AddPlaceholderChunk(
2509                           Result.getAllocator().CopyString((*A)->getName()));
2510     }
2511     Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2512     return Result.TakeString();
2513   }
2514 
2515   assert(Kind == RK_Declaration && "Missed a result kind?");
2516   NamedDecl *ND = Declaration;
2517 
2518   if (StartsNestedNameSpecifier) {
2519     Result.AddTypedTextChunk(
2520                       Result.getAllocator().CopyString(ND->getNameAsString()));
2521     Result.AddTextChunk("::");
2522     return Result.TakeString();
2523   }
2524 
2525   for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2526     if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2527       Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2528     }
2529   }
2530 
2531   AddResultTypeChunk(Ctx, Policy, ND, Result);
2532 
2533   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2534     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2535                                    Ctx, Policy);
2536     AddTypedNameChunk(Ctx, Policy, ND, Result);
2537     Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2538     AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2539     Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2540     AddFunctionTypeQualsToCompletionString(Result, Function);
2541     return Result.TakeString();
2542   }
2543 
2544   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2545     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2546                                    Ctx, Policy);
2547     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2548     AddTypedNameChunk(Ctx, Policy, Function, Result);
2549 
2550     // Figure out which template parameters are deduced (or have default
2551     // arguments).
2552     llvm::SmallBitVector Deduced;
2553     Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2554     unsigned LastDeducibleArgument;
2555     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2556          --LastDeducibleArgument) {
2557       if (!Deduced[LastDeducibleArgument - 1]) {
2558         // C++0x: Figure out if the template argument has a default. If so,
2559         // the user doesn't need to type this argument.
2560         // FIXME: We need to abstract template parameters better!
2561         bool HasDefaultArg = false;
2562         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2563                                                     LastDeducibleArgument - 1);
2564         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2565           HasDefaultArg = TTP->hasDefaultArgument();
2566         else if (NonTypeTemplateParmDecl *NTTP
2567                  = dyn_cast<NonTypeTemplateParmDecl>(Param))
2568           HasDefaultArg = NTTP->hasDefaultArgument();
2569         else {
2570           assert(isa<TemplateTemplateParmDecl>(Param));
2571           HasDefaultArg
2572             = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2573         }
2574 
2575         if (!HasDefaultArg)
2576           break;
2577       }
2578     }
2579 
2580     if (LastDeducibleArgument) {
2581       // Some of the function template arguments cannot be deduced from a
2582       // function call, so we introduce an explicit template argument list
2583       // containing all of the arguments up to the first deducible argument.
2584       Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2585       AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2586                                  LastDeducibleArgument);
2587       Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2588     }
2589 
2590     // Add the function parameters
2591     Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2592     AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2593     Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2594     AddFunctionTypeQualsToCompletionString(Result, Function);
2595     return Result.TakeString();
2596   }
2597 
2598   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2599     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2600                                    Ctx, Policy);
2601     Result.AddTypedTextChunk(
2602                 Result.getAllocator().CopyString(Template->getNameAsString()));
2603     Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2604     AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2605     Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2606     return Result.TakeString();
2607   }
2608 
2609   if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2610     Selector Sel = Method->getSelector();
2611     if (Sel.isUnarySelector()) {
2612       Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2613                                   Sel.getNameForSlot(0)));
2614       return Result.TakeString();
2615     }
2616 
2617     std::string SelName = Sel.getNameForSlot(0).str();
2618     SelName += ':';
2619     if (StartParameter == 0)
2620       Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2621     else {
2622       Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2623 
2624       // If there is only one parameter, and we're past it, add an empty
2625       // typed-text chunk since there is nothing to type.
2626       if (Method->param_size() == 1)
2627         Result.AddTypedTextChunk("");
2628     }
2629     unsigned Idx = 0;
2630     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2631                                      PEnd = Method->param_end();
2632          P != PEnd; (void)++P, ++Idx) {
2633       if (Idx > 0) {
2634         std::string Keyword;
2635         if (Idx > StartParameter)
2636           Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2637         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2638           Keyword += II->getName();
2639         Keyword += ":";
2640         if (Idx < StartParameter || AllParametersAreInformative)
2641           Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2642         else
2643           Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2644       }
2645 
2646       // If we're before the starting parameter, skip the placeholder.
2647       if (Idx < StartParameter)
2648         continue;
2649 
2650       std::string Arg;
2651 
2652       if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2653         Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
2654       else {
2655         (*P)->getType().getAsStringInternal(Arg, Policy);
2656         Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2657             + Arg + ")";
2658         if (IdentifierInfo *II = (*P)->getIdentifier())
2659           if (DeclaringEntity || AllParametersAreInformative)
2660             Arg += II->getName();
2661       }
2662 
2663       if (Method->isVariadic() && (P + 1) == PEnd)
2664         Arg += ", ...";
2665 
2666       if (DeclaringEntity)
2667         Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2668       else if (AllParametersAreInformative)
2669         Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2670       else
2671         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2672     }
2673 
2674     if (Method->isVariadic()) {
2675       if (Method->param_size() == 0) {
2676         if (DeclaringEntity)
2677           Result.AddTextChunk(", ...");
2678         else if (AllParametersAreInformative)
2679           Result.AddInformativeChunk(", ...");
2680         else
2681           Result.AddPlaceholderChunk(", ...");
2682       }
2683 
2684       MaybeAddSentinel(Ctx, Method, Result);
2685     }
2686 
2687     return Result.TakeString();
2688   }
2689 
2690   if (Qualifier)
2691     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2692                                    Ctx, Policy);
2693 
2694   Result.AddTypedTextChunk(
2695                        Result.getAllocator().CopyString(ND->getNameAsString()));
2696   return Result.TakeString();
2697 }
2698 
2699 CodeCompletionString *
2700 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2701                                                           unsigned CurrentArg,
2702                                                                Sema &S,
2703                                      CodeCompletionAllocator &Allocator) const {
2704   typedef CodeCompletionString::Chunk Chunk;
2705   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2706 
2707   // FIXME: Set priority, availability appropriately.
2708   CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
2709   FunctionDecl *FDecl = getFunction();
2710   AddResultTypeChunk(S.Context, Policy, FDecl, Result);
2711   const FunctionProtoType *Proto
2712     = dyn_cast<FunctionProtoType>(getFunctionType());
2713   if (!FDecl && !Proto) {
2714     // Function without a prototype. Just give the return type and a
2715     // highlighted ellipsis.
2716     const FunctionType *FT = getFunctionType();
2717     Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2718                                                 S.Context, Policy,
2719                                                 Result.getAllocator()));
2720     Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2721     Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2722     Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2723     return Result.TakeString();
2724   }
2725 
2726   if (FDecl)
2727     Result.AddTextChunk(
2728                     Result.getAllocator().CopyString(FDecl->getNameAsString()));
2729   else
2730     Result.AddTextChunk(
2731          Result.getAllocator().CopyString(
2732                                   Proto->getResultType().getAsString(Policy)));
2733 
2734   Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2735   unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2736   for (unsigned I = 0; I != NumParams; ++I) {
2737     if (I)
2738       Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2739 
2740     std::string ArgString;
2741     QualType ArgType;
2742 
2743     if (FDecl) {
2744       ArgString = FDecl->getParamDecl(I)->getNameAsString();
2745       ArgType = FDecl->getParamDecl(I)->getOriginalType();
2746     } else {
2747       ArgType = Proto->getArgType(I);
2748     }
2749 
2750     ArgType.getAsStringInternal(ArgString, Policy);
2751 
2752     if (I == CurrentArg)
2753       Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
2754                              Result.getAllocator().CopyString(ArgString)));
2755     else
2756       Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
2757   }
2758 
2759   if (Proto && Proto->isVariadic()) {
2760     Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2761     if (CurrentArg < NumParams)
2762       Result.AddTextChunk("...");
2763     else
2764       Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2765   }
2766   Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2767 
2768   return Result.TakeString();
2769 }
2770 
2771 unsigned clang::getMacroUsagePriority(StringRef MacroName,
2772                                       const LangOptions &LangOpts,
2773                                       bool PreferredTypeIsPointer) {
2774   unsigned Priority = CCP_Macro;
2775 
2776   // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2777   if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2778       MacroName.equals("Nil")) {
2779     Priority = CCP_Constant;
2780     if (PreferredTypeIsPointer)
2781       Priority = Priority / CCF_SimilarTypeMatch;
2782   }
2783   // Treat "YES", "NO", "true", and "false" as constants.
2784   else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2785            MacroName.equals("true") || MacroName.equals("false"))
2786     Priority = CCP_Constant;
2787   // Treat "bool" as a type.
2788   else if (MacroName.equals("bool"))
2789     Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2790 
2791 
2792   return Priority;
2793 }
2794 
2795 CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2796   if (!D)
2797     return CXCursor_UnexposedDecl;
2798 
2799   switch (D->getKind()) {
2800     case Decl::Enum:               return CXCursor_EnumDecl;
2801     case Decl::EnumConstant:       return CXCursor_EnumConstantDecl;
2802     case Decl::Field:              return CXCursor_FieldDecl;
2803     case Decl::Function:
2804       return CXCursor_FunctionDecl;
2805     case Decl::ObjCCategory:       return CXCursor_ObjCCategoryDecl;
2806     case Decl::ObjCCategoryImpl:   return CXCursor_ObjCCategoryImplDecl;
2807     case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2808 
2809     case Decl::ObjCInterface:      return CXCursor_ObjCInterfaceDecl;
2810     case Decl::ObjCIvar:           return CXCursor_ObjCIvarDecl;
2811     case Decl::ObjCMethod:
2812       return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2813       ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2814     case Decl::CXXMethod:          return CXCursor_CXXMethod;
2815     case Decl::CXXConstructor:     return CXCursor_Constructor;
2816     case Decl::CXXDestructor:      return CXCursor_Destructor;
2817     case Decl::CXXConversion:      return CXCursor_ConversionFunction;
2818     case Decl::ObjCProperty:       return CXCursor_ObjCPropertyDecl;
2819     case Decl::ObjCProtocol:       return CXCursor_ObjCProtocolDecl;
2820     case Decl::ParmVar:            return CXCursor_ParmDecl;
2821     case Decl::Typedef:            return CXCursor_TypedefDecl;
2822     case Decl::TypeAlias:          return CXCursor_TypeAliasDecl;
2823     case Decl::Var:                return CXCursor_VarDecl;
2824     case Decl::Namespace:          return CXCursor_Namespace;
2825     case Decl::NamespaceAlias:     return CXCursor_NamespaceAlias;
2826     case Decl::TemplateTypeParm:   return CXCursor_TemplateTypeParameter;
2827     case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2828     case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2829     case Decl::FunctionTemplate:   return CXCursor_FunctionTemplate;
2830     case Decl::ClassTemplate:      return CXCursor_ClassTemplate;
2831     case Decl::AccessSpec:         return CXCursor_CXXAccessSpecifier;
2832     case Decl::ClassTemplatePartialSpecialization:
2833       return CXCursor_ClassTemplatePartialSpecialization;
2834     case Decl::UsingDirective:     return CXCursor_UsingDirective;
2835 
2836     case Decl::Using:
2837     case Decl::UnresolvedUsingValue:
2838     case Decl::UnresolvedUsingTypename:
2839       return CXCursor_UsingDeclaration;
2840 
2841     case Decl::ObjCPropertyImpl:
2842       switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2843       case ObjCPropertyImplDecl::Dynamic:
2844         return CXCursor_ObjCDynamicDecl;
2845 
2846       case ObjCPropertyImplDecl::Synthesize:
2847         return CXCursor_ObjCSynthesizeDecl;
2848       }
2849 
2850     default:
2851       if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2852         switch (TD->getTagKind()) {
2853           case TTK_Struct: return CXCursor_StructDecl;
2854           case TTK_Class:  return CXCursor_ClassDecl;
2855           case TTK_Union:  return CXCursor_UnionDecl;
2856           case TTK_Enum:   return CXCursor_EnumDecl;
2857         }
2858       }
2859   }
2860 
2861   return CXCursor_UnexposedDecl;
2862 }
2863 
2864 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2865                             bool TargetTypeIsPointer = false) {
2866   typedef CodeCompletionResult Result;
2867 
2868   Results.EnterNewScope();
2869 
2870   for (Preprocessor::macro_iterator M = PP.macro_begin(),
2871                                  MEnd = PP.macro_end();
2872        M != MEnd; ++M) {
2873     Results.AddResult(Result(M->first,
2874                              getMacroUsagePriority(M->first->getName(),
2875                                                    PP.getLangOpts(),
2876                                                    TargetTypeIsPointer)));
2877   }
2878 
2879   Results.ExitScope();
2880 
2881 }
2882 
2883 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2884                                      ResultBuilder &Results) {
2885   typedef CodeCompletionResult Result;
2886 
2887   Results.EnterNewScope();
2888 
2889   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2890   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2891   if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2892     Results.AddResult(Result("__func__", CCP_Constant));
2893   Results.ExitScope();
2894 }
2895 
2896 static void HandleCodeCompleteResults(Sema *S,
2897                                       CodeCompleteConsumer *CodeCompleter,
2898                                       CodeCompletionContext Context,
2899                                       CodeCompletionResult *Results,
2900                                       unsigned NumResults) {
2901   if (CodeCompleter)
2902     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
2903 }
2904 
2905 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2906                                             Sema::ParserCompletionContext PCC) {
2907   switch (PCC) {
2908   case Sema::PCC_Namespace:
2909     return CodeCompletionContext::CCC_TopLevel;
2910 
2911   case Sema::PCC_Class:
2912     return CodeCompletionContext::CCC_ClassStructUnion;
2913 
2914   case Sema::PCC_ObjCInterface:
2915     return CodeCompletionContext::CCC_ObjCInterface;
2916 
2917   case Sema::PCC_ObjCImplementation:
2918     return CodeCompletionContext::CCC_ObjCImplementation;
2919 
2920   case Sema::PCC_ObjCInstanceVariableList:
2921     return CodeCompletionContext::CCC_ObjCIvarList;
2922 
2923   case Sema::PCC_Template:
2924   case Sema::PCC_MemberTemplate:
2925     if (S.CurContext->isFileContext())
2926       return CodeCompletionContext::CCC_TopLevel;
2927     if (S.CurContext->isRecord())
2928       return CodeCompletionContext::CCC_ClassStructUnion;
2929     return CodeCompletionContext::CCC_Other;
2930 
2931   case Sema::PCC_RecoveryInFunction:
2932     return CodeCompletionContext::CCC_Recovery;
2933 
2934   case Sema::PCC_ForInit:
2935     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
2936         S.getLangOpts().ObjC1)
2937       return CodeCompletionContext::CCC_ParenthesizedExpression;
2938     else
2939       return CodeCompletionContext::CCC_Expression;
2940 
2941   case Sema::PCC_Expression:
2942   case Sema::PCC_Condition:
2943     return CodeCompletionContext::CCC_Expression;
2944 
2945   case Sema::PCC_Statement:
2946     return CodeCompletionContext::CCC_Statement;
2947 
2948   case Sema::PCC_Type:
2949     return CodeCompletionContext::CCC_Type;
2950 
2951   case Sema::PCC_ParenthesizedExpression:
2952     return CodeCompletionContext::CCC_ParenthesizedExpression;
2953 
2954   case Sema::PCC_LocalDeclarationSpecifiers:
2955     return CodeCompletionContext::CCC_Type;
2956   }
2957 
2958   llvm_unreachable("Invalid ParserCompletionContext!");
2959 }
2960 
2961 /// \brief If we're in a C++ virtual member function, add completion results
2962 /// that invoke the functions we override, since it's common to invoke the
2963 /// overridden function as well as adding new functionality.
2964 ///
2965 /// \param S The semantic analysis object for which we are generating results.
2966 ///
2967 /// \param InContext This context in which the nested-name-specifier preceding
2968 /// the code-completion point
2969 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2970                                   ResultBuilder &Results) {
2971   // Look through blocks.
2972   DeclContext *CurContext = S.CurContext;
2973   while (isa<BlockDecl>(CurContext))
2974     CurContext = CurContext->getParent();
2975 
2976 
2977   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2978   if (!Method || !Method->isVirtual())
2979     return;
2980 
2981   // We need to have names for all of the parameters, if we're going to
2982   // generate a forwarding call.
2983   for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2984                                   PEnd = Method->param_end();
2985        P != PEnd;
2986        ++P) {
2987     if (!(*P)->getDeclName())
2988       return;
2989   }
2990 
2991   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2992   for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2993                                    MEnd = Method->end_overridden_methods();
2994        M != MEnd; ++M) {
2995     CodeCompletionBuilder Builder(Results.getAllocator());
2996     CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2997     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2998       continue;
2999 
3000     // If we need a nested-name-specifier, add one now.
3001     if (!InContext) {
3002       NestedNameSpecifier *NNS
3003         = getRequiredQualification(S.Context, CurContext,
3004                                    Overridden->getDeclContext());
3005       if (NNS) {
3006         std::string Str;
3007         llvm::raw_string_ostream OS(Str);
3008         NNS->print(OS, Policy);
3009         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3010       }
3011     } else if (!InContext->Equals(Overridden->getDeclContext()))
3012       continue;
3013 
3014     Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3015                                          Overridden->getNameAsString()));
3016     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3017     bool FirstParam = true;
3018     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3019                                     PEnd = Method->param_end();
3020          P != PEnd; ++P) {
3021       if (FirstParam)
3022         FirstParam = false;
3023       else
3024         Builder.AddChunk(CodeCompletionString::CK_Comma);
3025 
3026       Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
3027                                         (*P)->getIdentifier()->getName()));
3028     }
3029     Builder.AddChunk(CodeCompletionString::CK_RightParen);
3030     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3031                                            CCP_SuperCompletion,
3032                                            CXCursor_CXXMethod));
3033     Results.Ignore(Overridden);
3034   }
3035 }
3036 
3037 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3038                                     ModuleIdPath Path) {
3039   typedef CodeCompletionResult Result;
3040   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3041                         CodeCompletionContext::CCC_Other);
3042   Results.EnterNewScope();
3043 
3044   CodeCompletionAllocator &Allocator = Results.getAllocator();
3045   CodeCompletionBuilder Builder(Allocator);
3046   typedef CodeCompletionResult Result;
3047   if (Path.empty()) {
3048     // Enumerate all top-level modules.
3049     llvm::SmallVector<Module *, 8> Modules;
3050     PP.getHeaderSearchInfo().collectAllModules(Modules);
3051     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3052       Builder.AddTypedTextChunk(
3053         Builder.getAllocator().CopyString(Modules[I]->Name));
3054       Results.AddResult(Result(Builder.TakeString(),
3055                                CCP_Declaration,
3056                                CXCursor_NotImplemented,
3057                                Modules[I]->isAvailable()
3058                                  ? CXAvailability_Available
3059                                   : CXAvailability_NotAvailable));
3060     }
3061   } else {
3062     // Load the named module.
3063     Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3064                                                   Module::AllVisible,
3065                                                 /*IsInclusionDirective=*/false);
3066     // Enumerate submodules.
3067     if (Mod) {
3068       for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3069                                    SubEnd = Mod->submodule_end();
3070            Sub != SubEnd; ++Sub) {
3071 
3072         Builder.AddTypedTextChunk(
3073           Builder.getAllocator().CopyString((*Sub)->Name));
3074         Results.AddResult(Result(Builder.TakeString(),
3075                                  CCP_Declaration,
3076                                  CXCursor_NotImplemented,
3077                                  (*Sub)->isAvailable()
3078                                    ? CXAvailability_Available
3079                                    : CXAvailability_NotAvailable));
3080       }
3081     }
3082   }
3083   Results.ExitScope();
3084   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3085                             Results.data(),Results.size());
3086 }
3087 
3088 void Sema::CodeCompleteOrdinaryName(Scope *S,
3089                                     ParserCompletionContext CompletionContext) {
3090   typedef CodeCompletionResult Result;
3091   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3092                         mapCodeCompletionContext(*this, CompletionContext));
3093   Results.EnterNewScope();
3094 
3095   // Determine how to filter results, e.g., so that the names of
3096   // values (functions, enumerators, function templates, etc.) are
3097   // only allowed where we can have an expression.
3098   switch (CompletionContext) {
3099   case PCC_Namespace:
3100   case PCC_Class:
3101   case PCC_ObjCInterface:
3102   case PCC_ObjCImplementation:
3103   case PCC_ObjCInstanceVariableList:
3104   case PCC_Template:
3105   case PCC_MemberTemplate:
3106   case PCC_Type:
3107   case PCC_LocalDeclarationSpecifiers:
3108     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3109     break;
3110 
3111   case PCC_Statement:
3112   case PCC_ParenthesizedExpression:
3113   case PCC_Expression:
3114   case PCC_ForInit:
3115   case PCC_Condition:
3116     if (WantTypesInContext(CompletionContext, getLangOpts()))
3117       Results.setFilter(&ResultBuilder::IsOrdinaryName);
3118     else
3119       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3120 
3121     if (getLangOpts().CPlusPlus)
3122       MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
3123     break;
3124 
3125   case PCC_RecoveryInFunction:
3126     // Unfiltered
3127     break;
3128   }
3129 
3130   // If we are in a C++ non-static member function, check the qualifiers on
3131   // the member function to filter/prioritize the results list.
3132   if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3133     if (CurMethod->isInstance())
3134       Results.setObjectTypeQualifiers(
3135                       Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3136 
3137   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3138   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3139                      CodeCompleter->includeGlobals());
3140 
3141   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3142   Results.ExitScope();
3143 
3144   switch (CompletionContext) {
3145   case PCC_ParenthesizedExpression:
3146   case PCC_Expression:
3147   case PCC_Statement:
3148   case PCC_RecoveryInFunction:
3149     if (S->getFnParent())
3150       AddPrettyFunctionResults(PP.getLangOpts(), Results);
3151     break;
3152 
3153   case PCC_Namespace:
3154   case PCC_Class:
3155   case PCC_ObjCInterface:
3156   case PCC_ObjCImplementation:
3157   case PCC_ObjCInstanceVariableList:
3158   case PCC_Template:
3159   case PCC_MemberTemplate:
3160   case PCC_ForInit:
3161   case PCC_Condition:
3162   case PCC_Type:
3163   case PCC_LocalDeclarationSpecifiers:
3164     break;
3165   }
3166 
3167   if (CodeCompleter->includeMacros())
3168     AddMacroResults(PP, Results);
3169 
3170   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3171                             Results.data(),Results.size());
3172 }
3173 
3174 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3175                                        ParsedType Receiver,
3176                                        IdentifierInfo **SelIdents,
3177                                        unsigned NumSelIdents,
3178                                        bool AtArgumentExpression,
3179                                        bool IsSuper,
3180                                        ResultBuilder &Results);
3181 
3182 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3183                                 bool AllowNonIdentifiers,
3184                                 bool AllowNestedNameSpecifiers) {
3185   typedef CodeCompletionResult Result;
3186   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3187                         AllowNestedNameSpecifiers
3188                           ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3189                           : CodeCompletionContext::CCC_Name);
3190   Results.EnterNewScope();
3191 
3192   // Type qualifiers can come after names.
3193   Results.AddResult(Result("const"));
3194   Results.AddResult(Result("volatile"));
3195   if (getLangOpts().C99)
3196     Results.AddResult(Result("restrict"));
3197 
3198   if (getLangOpts().CPlusPlus) {
3199     if (AllowNonIdentifiers) {
3200       Results.AddResult(Result("operator"));
3201     }
3202 
3203     // Add nested-name-specifiers.
3204     if (AllowNestedNameSpecifiers) {
3205       Results.allowNestedNameSpecifiers();
3206       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3207       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3208       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3209                          CodeCompleter->includeGlobals());
3210       Results.setFilter(0);
3211     }
3212   }
3213   Results.ExitScope();
3214 
3215   // If we're in a context where we might have an expression (rather than a
3216   // declaration), and what we've seen so far is an Objective-C type that could
3217   // be a receiver of a class message, this may be a class message send with
3218   // the initial opening bracket '[' missing. Add appropriate completions.
3219   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3220       DS.getTypeSpecType() == DeclSpec::TST_typename &&
3221       DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3222       !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3223       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3224       DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3225       DS.getTypeQualifiers() == 0 &&
3226       S &&
3227       (S->getFlags() & Scope::DeclScope) != 0 &&
3228       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3229                         Scope::FunctionPrototypeScope |
3230                         Scope::AtCatchScope)) == 0) {
3231     ParsedType T = DS.getRepAsType();
3232     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3233       AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
3234   }
3235 
3236   // Note that we intentionally suppress macro results here, since we do not
3237   // encourage using macros to produce the names of entities.
3238 
3239   HandleCodeCompleteResults(this, CodeCompleter,
3240                             Results.getCompletionContext(),
3241                             Results.data(), Results.size());
3242 }
3243 
3244 struct Sema::CodeCompleteExpressionData {
3245   CodeCompleteExpressionData(QualType PreferredType = QualType())
3246     : PreferredType(PreferredType), IntegralConstantExpression(false),
3247       ObjCCollection(false) { }
3248 
3249   QualType PreferredType;
3250   bool IntegralConstantExpression;
3251   bool ObjCCollection;
3252   SmallVector<Decl *, 4> IgnoreDecls;
3253 };
3254 
3255 /// \brief Perform code-completion in an expression context when we know what
3256 /// type we're looking for.
3257 ///
3258 /// \param IntegralConstantExpression Only permit integral constant
3259 /// expressions.
3260 void Sema::CodeCompleteExpression(Scope *S,
3261                                   const CodeCompleteExpressionData &Data) {
3262   typedef CodeCompletionResult Result;
3263   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3264                         CodeCompletionContext::CCC_Expression);
3265   if (Data.ObjCCollection)
3266     Results.setFilter(&ResultBuilder::IsObjCCollection);
3267   else if (Data.IntegralConstantExpression)
3268     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3269   else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3270     Results.setFilter(&ResultBuilder::IsOrdinaryName);
3271   else
3272     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3273 
3274   if (!Data.PreferredType.isNull())
3275     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3276 
3277   // Ignore any declarations that we were told that we don't care about.
3278   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3279     Results.Ignore(Data.IgnoreDecls[I]);
3280 
3281   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3282   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3283                      CodeCompleter->includeGlobals());
3284 
3285   Results.EnterNewScope();
3286   AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3287   Results.ExitScope();
3288 
3289   bool PreferredTypeIsPointer = false;
3290   if (!Data.PreferredType.isNull())
3291     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3292       || Data.PreferredType->isMemberPointerType()
3293       || Data.PreferredType->isBlockPointerType();
3294 
3295   if (S->getFnParent() &&
3296       !Data.ObjCCollection &&
3297       !Data.IntegralConstantExpression)
3298     AddPrettyFunctionResults(PP.getLangOpts(), Results);
3299 
3300   if (CodeCompleter->includeMacros())
3301     AddMacroResults(PP, Results, PreferredTypeIsPointer);
3302   HandleCodeCompleteResults(this, CodeCompleter,
3303                 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3304                                       Data.PreferredType),
3305                             Results.data(),Results.size());
3306 }
3307 
3308 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3309   if (E.isInvalid())
3310     CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3311   else if (getLangOpts().ObjC1)
3312     CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
3313 }
3314 
3315 /// \brief The set of properties that have already been added, referenced by
3316 /// property name.
3317 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3318 
3319 static void AddObjCProperties(ObjCContainerDecl *Container,
3320                               bool AllowCategories,
3321                               bool AllowNullaryMethods,
3322                               DeclContext *CurContext,
3323                               AddedPropertiesSet &AddedProperties,
3324                               ResultBuilder &Results) {
3325   typedef CodeCompletionResult Result;
3326 
3327   // Add properties in this container.
3328   for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3329                                      PEnd = Container->prop_end();
3330        P != PEnd;
3331        ++P) {
3332     if (AddedProperties.insert(P->getIdentifier()))
3333       Results.MaybeAddResult(Result(*P, 0), CurContext);
3334   }
3335 
3336   // Add nullary methods
3337   if (AllowNullaryMethods) {
3338     ASTContext &Context = Container->getASTContext();
3339     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3340     for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3341                                          MEnd = Container->meth_end();
3342          M != MEnd; ++M) {
3343       if (M->getSelector().isUnarySelector())
3344         if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3345           if (AddedProperties.insert(Name)) {
3346             CodeCompletionBuilder Builder(Results.getAllocator());
3347             AddResultTypeChunk(Context, Policy, *M, Builder);
3348             Builder.AddTypedTextChunk(
3349                             Results.getAllocator().CopyString(Name->getName()));
3350 
3351             CXAvailabilityKind Availability = CXAvailability_Available;
3352             switch (M->getAvailability()) {
3353             case AR_Available:
3354             case AR_NotYetIntroduced:
3355               Availability = CXAvailability_Available;
3356               break;
3357 
3358             case AR_Deprecated:
3359               Availability = CXAvailability_Deprecated;
3360               break;
3361 
3362             case AR_Unavailable:
3363               Availability = CXAvailability_NotAvailable;
3364               break;
3365             }
3366 
3367             Results.MaybeAddResult(Result(Builder.TakeString(),
3368                                   CCP_MemberDeclaration + CCD_MethodAsProperty,
3369                                           M->isInstanceMethod()
3370                                             ? CXCursor_ObjCInstanceMethodDecl
3371                                             : CXCursor_ObjCClassMethodDecl,
3372                                           Availability),
3373                                           CurContext);
3374           }
3375     }
3376   }
3377 
3378 
3379   // Add properties in referenced protocols.
3380   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3381     for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3382                                           PEnd = Protocol->protocol_end();
3383          P != PEnd; ++P)
3384       AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3385                         AddedProperties, Results);
3386   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3387     if (AllowCategories) {
3388       // Look through categories.
3389       for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3390            Category; Category = Category->getNextClassCategory())
3391         AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3392                           CurContext, AddedProperties, Results);
3393     }
3394 
3395     // Look through protocols.
3396     for (ObjCInterfaceDecl::all_protocol_iterator
3397          I = IFace->all_referenced_protocol_begin(),
3398          E = IFace->all_referenced_protocol_end(); I != E; ++I)
3399       AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3400                         AddedProperties, Results);
3401 
3402     // Look in the superclass.
3403     if (IFace->getSuperClass())
3404       AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3405                         AllowNullaryMethods, CurContext,
3406                         AddedProperties, Results);
3407   } else if (const ObjCCategoryDecl *Category
3408                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
3409     // Look through protocols.
3410     for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3411                                           PEnd = Category->protocol_end();
3412          P != PEnd; ++P)
3413       AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3414                         AddedProperties, Results);
3415   }
3416 }
3417 
3418 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3419                                            SourceLocation OpLoc,
3420                                            bool IsArrow) {
3421   if (!Base || !CodeCompleter)
3422     return;
3423 
3424   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3425   if (ConvertedBase.isInvalid())
3426     return;
3427   Base = ConvertedBase.get();
3428 
3429   typedef CodeCompletionResult Result;
3430 
3431   QualType BaseType = Base->getType();
3432 
3433   if (IsArrow) {
3434     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3435       BaseType = Ptr->getPointeeType();
3436     else if (BaseType->isObjCObjectPointerType())
3437       /*Do nothing*/ ;
3438     else
3439       return;
3440   }
3441 
3442   enum CodeCompletionContext::Kind contextKind;
3443 
3444   if (IsArrow) {
3445     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3446   }
3447   else {
3448     if (BaseType->isObjCObjectPointerType() ||
3449         BaseType->isObjCObjectOrInterfaceType()) {
3450       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3451     }
3452     else {
3453       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3454     }
3455   }
3456 
3457   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3458                   CodeCompletionContext(contextKind,
3459                                         BaseType),
3460                         &ResultBuilder::IsMember);
3461   Results.EnterNewScope();
3462   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3463     // Indicate that we are performing a member access, and the cv-qualifiers
3464     // for the base object type.
3465     Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3466 
3467     // Access to a C/C++ class, struct, or union.
3468     Results.allowNestedNameSpecifiers();
3469     CodeCompletionDeclConsumer Consumer(Results, CurContext);
3470     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3471                        CodeCompleter->includeGlobals());
3472 
3473     if (getLangOpts().CPlusPlus) {
3474       if (!Results.empty()) {
3475         // The "template" keyword can follow "->" or "." in the grammar.
3476         // However, we only want to suggest the template keyword if something
3477         // is dependent.
3478         bool IsDependent = BaseType->isDependentType();
3479         if (!IsDependent) {
3480           for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3481             if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3482               IsDependent = Ctx->isDependentContext();
3483               break;
3484             }
3485         }
3486 
3487         if (IsDependent)
3488           Results.AddResult(Result("template"));
3489       }
3490     }
3491   } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3492     // Objective-C property reference.
3493     AddedPropertiesSet AddedProperties;
3494 
3495     // Add property results based on our interface.
3496     const ObjCObjectPointerType *ObjCPtr
3497       = BaseType->getAsObjCInterfacePointerType();
3498     assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3499     AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3500                       /*AllowNullaryMethods=*/true, CurContext,
3501                       AddedProperties, Results);
3502 
3503     // Add properties from the protocols in a qualified interface.
3504     for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3505                                               E = ObjCPtr->qual_end();
3506          I != E; ++I)
3507       AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3508                         AddedProperties, Results);
3509   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3510              (!IsArrow && BaseType->isObjCObjectType())) {
3511     // Objective-C instance variable access.
3512     ObjCInterfaceDecl *Class = 0;
3513     if (const ObjCObjectPointerType *ObjCPtr
3514                                     = BaseType->getAs<ObjCObjectPointerType>())
3515       Class = ObjCPtr->getInterfaceDecl();
3516     else
3517       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3518 
3519     // Add all ivars from this class and its superclasses.
3520     if (Class) {
3521       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3522       Results.setFilter(&ResultBuilder::IsObjCIvar);
3523       LookupVisibleDecls(Class, LookupMemberName, Consumer,
3524                          CodeCompleter->includeGlobals());
3525     }
3526   }
3527 
3528   // FIXME: How do we cope with isa?
3529 
3530   Results.ExitScope();
3531 
3532   // Hand off the results found for code completion.
3533   HandleCodeCompleteResults(this, CodeCompleter,
3534                             Results.getCompletionContext(),
3535                             Results.data(),Results.size());
3536 }
3537 
3538 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3539   if (!CodeCompleter)
3540     return;
3541 
3542   typedef CodeCompletionResult Result;
3543   ResultBuilder::LookupFilter Filter = 0;
3544   enum CodeCompletionContext::Kind ContextKind
3545     = CodeCompletionContext::CCC_Other;
3546   switch ((DeclSpec::TST)TagSpec) {
3547   case DeclSpec::TST_enum:
3548     Filter = &ResultBuilder::IsEnum;
3549     ContextKind = CodeCompletionContext::CCC_EnumTag;
3550     break;
3551 
3552   case DeclSpec::TST_union:
3553     Filter = &ResultBuilder::IsUnion;
3554     ContextKind = CodeCompletionContext::CCC_UnionTag;
3555     break;
3556 
3557   case DeclSpec::TST_struct:
3558   case DeclSpec::TST_class:
3559     Filter = &ResultBuilder::IsClassOrStruct;
3560     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3561     break;
3562 
3563   default:
3564     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
3565   }
3566 
3567   ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
3568   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3569 
3570   // First pass: look for tags.
3571   Results.setFilter(Filter);
3572   LookupVisibleDecls(S, LookupTagName, Consumer,
3573                      CodeCompleter->includeGlobals());
3574 
3575   if (CodeCompleter->includeGlobals()) {
3576     // Second pass: look for nested name specifiers.
3577     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3578     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3579   }
3580 
3581   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3582                             Results.data(),Results.size());
3583 }
3584 
3585 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3586   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3587                         CodeCompletionContext::CCC_TypeQualifiers);
3588   Results.EnterNewScope();
3589   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3590     Results.AddResult("const");
3591   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3592     Results.AddResult("volatile");
3593   if (getLangOpts().C99 &&
3594       !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3595     Results.AddResult("restrict");
3596   Results.ExitScope();
3597   HandleCodeCompleteResults(this, CodeCompleter,
3598                             Results.getCompletionContext(),
3599                             Results.data(), Results.size());
3600 }
3601 
3602 void Sema::CodeCompleteCase(Scope *S) {
3603   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3604     return;
3605 
3606   SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3607   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3608   if (!type->isEnumeralType()) {
3609     CodeCompleteExpressionData Data(type);
3610     Data.IntegralConstantExpression = true;
3611     CodeCompleteExpression(S, Data);
3612     return;
3613   }
3614 
3615   // Code-complete the cases of a switch statement over an enumeration type
3616   // by providing the list of
3617   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
3618 
3619   // Determine which enumerators we have already seen in the switch statement.
3620   // FIXME: Ideally, we would also be able to look *past* the code-completion
3621   // token, in case we are code-completing in the middle of the switch and not
3622   // at the end. However, we aren't able to do so at the moment.
3623   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3624   NestedNameSpecifier *Qualifier = 0;
3625   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3626        SC = SC->getNextSwitchCase()) {
3627     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3628     if (!Case)
3629       continue;
3630 
3631     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3632     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3633       if (EnumConstantDecl *Enumerator
3634             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3635         // We look into the AST of the case statement to determine which
3636         // enumerator was named. Alternatively, we could compute the value of
3637         // the integral constant expression, then compare it against the
3638         // values of each enumerator. However, value-based approach would not
3639         // work as well with C++ templates where enumerators declared within a
3640         // template are type- and value-dependent.
3641         EnumeratorsSeen.insert(Enumerator);
3642 
3643         // If this is a qualified-id, keep track of the nested-name-specifier
3644         // so that we can reproduce it as part of code completion, e.g.,
3645         //
3646         //   switch (TagD.getKind()) {
3647         //     case TagDecl::TK_enum:
3648         //       break;
3649         //     case XXX
3650         //
3651         // At the XXX, our completions are TagDecl::TK_union,
3652         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3653         // TK_struct, and TK_class.
3654         Qualifier = DRE->getQualifier();
3655       }
3656   }
3657 
3658   if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3659     // If there are no prior enumerators in C++, check whether we have to
3660     // qualify the names of the enumerators that we suggest, because they
3661     // may not be visible in this scope.
3662     Qualifier = getRequiredQualification(Context, CurContext, Enum);
3663   }
3664 
3665   // Add any enumerators that have not yet been mentioned.
3666   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3667                         CodeCompletionContext::CCC_Expression);
3668   Results.EnterNewScope();
3669   for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3670                                   EEnd = Enum->enumerator_end();
3671        E != EEnd; ++E) {
3672     if (EnumeratorsSeen.count(*E))
3673       continue;
3674 
3675     CodeCompletionResult R(*E, Qualifier);
3676     R.Priority = CCP_EnumInCase;
3677     Results.AddResult(R, CurContext, 0, false);
3678   }
3679   Results.ExitScope();
3680 
3681   //We need to make sure we're setting the right context,
3682   //so only say we include macros if the code completer says we do
3683   enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3684   if (CodeCompleter->includeMacros()) {
3685     AddMacroResults(PP, Results);
3686     kind = CodeCompletionContext::CCC_OtherWithMacros;
3687   }
3688 
3689   HandleCodeCompleteResults(this, CodeCompleter,
3690                             kind,
3691                             Results.data(),Results.size());
3692 }
3693 
3694 namespace {
3695   struct IsBetterOverloadCandidate {
3696     Sema &S;
3697     SourceLocation Loc;
3698 
3699   public:
3700     explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3701       : S(S), Loc(Loc) { }
3702 
3703     bool
3704     operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
3705       return isBetterOverloadCandidate(S, X, Y, Loc);
3706     }
3707   };
3708 }
3709 
3710 static bool anyNullArguments(llvm::ArrayRef<Expr*> Args) {
3711   if (Args.size() && !Args.data())
3712     return true;
3713 
3714   for (unsigned I = 0; I != Args.size(); ++I)
3715     if (!Args[I])
3716       return true;
3717 
3718   return false;
3719 }
3720 
3721 void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3722                             llvm::ArrayRef<Expr *> Args) {
3723   if (!CodeCompleter)
3724     return;
3725 
3726   // When we're code-completing for a call, we fall back to ordinary
3727   // name code-completion whenever we can't produce specific
3728   // results. We may want to revisit this strategy in the future,
3729   // e.g., by merging the two kinds of results.
3730 
3731   Expr *Fn = (Expr *)FnIn;
3732 
3733   // Ignore type-dependent call expressions entirely.
3734   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3735       Expr::hasAnyTypeDependentArguments(Args)) {
3736     CodeCompleteOrdinaryName(S, PCC_Expression);
3737     return;
3738   }
3739 
3740   // Build an overload candidate set based on the functions we find.
3741   SourceLocation Loc = Fn->getExprLoc();
3742   OverloadCandidateSet CandidateSet(Loc);
3743 
3744   // FIXME: What if we're calling something that isn't a function declaration?
3745   // FIXME: What if we're calling a pseudo-destructor?
3746   // FIXME: What if we're calling a member function?
3747 
3748   typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3749   SmallVector<ResultCandidate, 8> Results;
3750 
3751   Expr *NakedFn = Fn->IgnoreParenCasts();
3752   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3753     AddOverloadedCallCandidates(ULE, Args, CandidateSet,
3754                                 /*PartialOverloading=*/ true);
3755   else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3756     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
3757     if (FDecl) {
3758       if (!getLangOpts().CPlusPlus ||
3759           !FDecl->getType()->getAs<FunctionProtoType>())
3760         Results.push_back(ResultCandidate(FDecl));
3761       else
3762         // FIXME: access?
3763         AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
3764                              CandidateSet, false, /*PartialOverloading*/true);
3765     }
3766   }
3767 
3768   QualType ParamType;
3769 
3770   if (!CandidateSet.empty()) {
3771     // Sort the overload candidate set by placing the best overloads first.
3772     std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
3773                      IsBetterOverloadCandidate(*this, Loc));
3774 
3775     // Add the remaining viable overload candidates as code-completion reslults.
3776     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3777                                      CandEnd = CandidateSet.end();
3778          Cand != CandEnd; ++Cand) {
3779       if (Cand->Viable)
3780         Results.push_back(ResultCandidate(Cand->Function));
3781     }
3782 
3783     // From the viable candidates, try to determine the type of this parameter.
3784     for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3785       if (const FunctionType *FType = Results[I].getFunctionType())
3786         if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3787           if (Args.size() < Proto->getNumArgs()) {
3788             if (ParamType.isNull())
3789               ParamType = Proto->getArgType(Args.size());
3790             else if (!Context.hasSameUnqualifiedType(
3791                                             ParamType.getNonReferenceType(),
3792                        Proto->getArgType(Args.size()).getNonReferenceType())) {
3793               ParamType = QualType();
3794               break;
3795             }
3796           }
3797     }
3798   } else {
3799     // Try to determine the parameter type from the type of the expression
3800     // being called.
3801     QualType FunctionType = Fn->getType();
3802     if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3803       FunctionType = Ptr->getPointeeType();
3804     else if (const BlockPointerType *BlockPtr
3805                                     = FunctionType->getAs<BlockPointerType>())
3806       FunctionType = BlockPtr->getPointeeType();
3807     else if (const MemberPointerType *MemPtr
3808                                     = FunctionType->getAs<MemberPointerType>())
3809       FunctionType = MemPtr->getPointeeType();
3810 
3811     if (const FunctionProtoType *Proto
3812                                   = FunctionType->getAs<FunctionProtoType>()) {
3813       if (Args.size() < Proto->getNumArgs())
3814         ParamType = Proto->getArgType(Args.size());
3815     }
3816   }
3817 
3818   if (ParamType.isNull())
3819     CodeCompleteOrdinaryName(S, PCC_Expression);
3820   else
3821     CodeCompleteExpression(S, ParamType);
3822 
3823   if (!Results.empty())
3824     CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
3825                                              Results.size());
3826 }
3827 
3828 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3829   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3830   if (!VD) {
3831     CodeCompleteOrdinaryName(S, PCC_Expression);
3832     return;
3833   }
3834 
3835   CodeCompleteExpression(S, VD->getType());
3836 }
3837 
3838 void Sema::CodeCompleteReturn(Scope *S) {
3839   QualType ResultType;
3840   if (isa<BlockDecl>(CurContext)) {
3841     if (BlockScopeInfo *BSI = getCurBlock())
3842       ResultType = BSI->ReturnType;
3843   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3844     ResultType = Function->getResultType();
3845   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3846     ResultType = Method->getResultType();
3847 
3848   if (ResultType.isNull())
3849     CodeCompleteOrdinaryName(S, PCC_Expression);
3850   else
3851     CodeCompleteExpression(S, ResultType);
3852 }
3853 
3854 void Sema::CodeCompleteAfterIf(Scope *S) {
3855   typedef CodeCompletionResult Result;
3856   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3857                         mapCodeCompletionContext(*this, PCC_Statement));
3858   Results.setFilter(&ResultBuilder::IsOrdinaryName);
3859   Results.EnterNewScope();
3860 
3861   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3862   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3863                      CodeCompleter->includeGlobals());
3864 
3865   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3866 
3867   // "else" block
3868   CodeCompletionBuilder Builder(Results.getAllocator());
3869   Builder.AddTypedTextChunk("else");
3870   if (Results.includeCodePatterns()) {
3871     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3872     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3873     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3874     Builder.AddPlaceholderChunk("statements");
3875     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3876     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3877   }
3878   Results.AddResult(Builder.TakeString());
3879 
3880   // "else if" block
3881   Builder.AddTypedTextChunk("else");
3882   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3883   Builder.AddTextChunk("if");
3884   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3885   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3886   if (getLangOpts().CPlusPlus)
3887     Builder.AddPlaceholderChunk("condition");
3888   else
3889     Builder.AddPlaceholderChunk("expression");
3890   Builder.AddChunk(CodeCompletionString::CK_RightParen);
3891   if (Results.includeCodePatterns()) {
3892     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3893     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3894     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3895     Builder.AddPlaceholderChunk("statements");
3896     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3897     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3898   }
3899   Results.AddResult(Builder.TakeString());
3900 
3901   Results.ExitScope();
3902 
3903   if (S->getFnParent())
3904     AddPrettyFunctionResults(PP.getLangOpts(), Results);
3905 
3906   if (CodeCompleter->includeMacros())
3907     AddMacroResults(PP, Results);
3908 
3909   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3910                             Results.data(),Results.size());
3911 }
3912 
3913 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
3914   if (LHS)
3915     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3916   else
3917     CodeCompleteOrdinaryName(S, PCC_Expression);
3918 }
3919 
3920 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
3921                                    bool EnteringContext) {
3922   if (!SS.getScopeRep() || !CodeCompleter)
3923     return;
3924 
3925   DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3926   if (!Ctx)
3927     return;
3928 
3929   // Try to instantiate any non-dependent declaration contexts before
3930   // we look in them.
3931   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
3932     return;
3933 
3934   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3935                         CodeCompletionContext::CCC_Name);
3936   Results.EnterNewScope();
3937 
3938   // The "template" keyword can follow "::" in the grammar, but only
3939   // put it into the grammar if the nested-name-specifier is dependent.
3940   NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3941   if (!Results.empty() && NNS->isDependent())
3942     Results.AddResult("template");
3943 
3944   // Add calls to overridden virtual functions, if there are any.
3945   //
3946   // FIXME: This isn't wonderful, because we don't know whether we're actually
3947   // in a context that permits expressions. This is a general issue with
3948   // qualified-id completions.
3949   if (!EnteringContext)
3950     MaybeAddOverrideCalls(*this, Ctx, Results);
3951   Results.ExitScope();
3952 
3953   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3954   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3955 
3956   HandleCodeCompleteResults(this, CodeCompleter,
3957                             Results.getCompletionContext(),
3958                             Results.data(),Results.size());
3959 }
3960 
3961 void Sema::CodeCompleteUsing(Scope *S) {
3962   if (!CodeCompleter)
3963     return;
3964 
3965   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3966                         CodeCompletionContext::CCC_PotentiallyQualifiedName,
3967                         &ResultBuilder::IsNestedNameSpecifier);
3968   Results.EnterNewScope();
3969 
3970   // If we aren't in class scope, we could see the "namespace" keyword.
3971   if (!S->isClassScope())
3972     Results.AddResult(CodeCompletionResult("namespace"));
3973 
3974   // After "using", we can see anything that would start a
3975   // nested-name-specifier.
3976   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3977   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3978                      CodeCompleter->includeGlobals());
3979   Results.ExitScope();
3980 
3981   HandleCodeCompleteResults(this, CodeCompleter,
3982                             CodeCompletionContext::CCC_PotentiallyQualifiedName,
3983                             Results.data(),Results.size());
3984 }
3985 
3986 void Sema::CodeCompleteUsingDirective(Scope *S) {
3987   if (!CodeCompleter)
3988     return;
3989 
3990   // After "using namespace", we expect to see a namespace name or namespace
3991   // alias.
3992   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3993                         CodeCompletionContext::CCC_Namespace,
3994                         &ResultBuilder::IsNamespaceOrAlias);
3995   Results.EnterNewScope();
3996   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3997   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3998                      CodeCompleter->includeGlobals());
3999   Results.ExitScope();
4000   HandleCodeCompleteResults(this, CodeCompleter,
4001                             CodeCompletionContext::CCC_Namespace,
4002                             Results.data(),Results.size());
4003 }
4004 
4005 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
4006   if (!CodeCompleter)
4007     return;
4008 
4009   DeclContext *Ctx = (DeclContext *)S->getEntity();
4010   if (!S->getParent())
4011     Ctx = Context.getTranslationUnitDecl();
4012 
4013   bool SuppressedGlobalResults
4014     = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4015 
4016   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4017                         SuppressedGlobalResults
4018                           ? CodeCompletionContext::CCC_Namespace
4019                           : CodeCompletionContext::CCC_Other,
4020                         &ResultBuilder::IsNamespace);
4021 
4022   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4023     // We only want to see those namespaces that have already been defined
4024     // within this scope, because its likely that the user is creating an
4025     // extended namespace declaration. Keep track of the most recent
4026     // definition of each namespace.
4027     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4028     for (DeclContext::specific_decl_iterator<NamespaceDecl>
4029          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4030          NS != NSEnd; ++NS)
4031       OrigToLatest[NS->getOriginalNamespace()] = *NS;
4032 
4033     // Add the most recent definition (or extended definition) of each
4034     // namespace to the list of results.
4035     Results.EnterNewScope();
4036     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4037          NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
4038          NS != NSEnd; ++NS)
4039       Results.AddResult(CodeCompletionResult(NS->second, 0),
4040                         CurContext, 0, false);
4041     Results.ExitScope();
4042   }
4043 
4044   HandleCodeCompleteResults(this, CodeCompleter,
4045                             Results.getCompletionContext(),
4046                             Results.data(),Results.size());
4047 }
4048 
4049 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
4050   if (!CodeCompleter)
4051     return;
4052 
4053   // After "namespace", we expect to see a namespace or alias.
4054   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4055                         CodeCompletionContext::CCC_Namespace,
4056                         &ResultBuilder::IsNamespaceOrAlias);
4057   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4058   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4059                      CodeCompleter->includeGlobals());
4060   HandleCodeCompleteResults(this, CodeCompleter,
4061                             Results.getCompletionContext(),
4062                             Results.data(),Results.size());
4063 }
4064 
4065 void Sema::CodeCompleteOperatorName(Scope *S) {
4066   if (!CodeCompleter)
4067     return;
4068 
4069   typedef CodeCompletionResult Result;
4070   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4071                         CodeCompletionContext::CCC_Type,
4072                         &ResultBuilder::IsType);
4073   Results.EnterNewScope();
4074 
4075   // Add the names of overloadable operators.
4076 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
4077   if (std::strcmp(Spelling, "?"))                                                  \
4078     Results.AddResult(Result(Spelling));
4079 #include "clang/Basic/OperatorKinds.def"
4080 
4081   // Add any type names visible from the current scope
4082   Results.allowNestedNameSpecifiers();
4083   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4084   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4085                      CodeCompleter->includeGlobals());
4086 
4087   // Add any type specifiers
4088   AddTypeSpecifierResults(getLangOpts(), Results);
4089   Results.ExitScope();
4090 
4091   HandleCodeCompleteResults(this, CodeCompleter,
4092                             CodeCompletionContext::CCC_Type,
4093                             Results.data(),Results.size());
4094 }
4095 
4096 void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
4097                                               CXXCtorInitializer** Initializers,
4098                                               unsigned NumInitializers) {
4099   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4100   CXXConstructorDecl *Constructor
4101     = static_cast<CXXConstructorDecl *>(ConstructorD);
4102   if (!Constructor)
4103     return;
4104 
4105   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4106                         CodeCompletionContext::CCC_PotentiallyQualifiedName);
4107   Results.EnterNewScope();
4108 
4109   // Fill in any already-initialized fields or base classes.
4110   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4111   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4112   for (unsigned I = 0; I != NumInitializers; ++I) {
4113     if (Initializers[I]->isBaseInitializer())
4114       InitializedBases.insert(
4115         Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4116     else
4117       InitializedFields.insert(cast<FieldDecl>(
4118                                Initializers[I]->getAnyMember()));
4119   }
4120 
4121   // Add completions for base classes.
4122   CodeCompletionBuilder Builder(Results.getAllocator());
4123   bool SawLastInitializer = (NumInitializers == 0);
4124   CXXRecordDecl *ClassDecl = Constructor->getParent();
4125   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4126                                        BaseEnd = ClassDecl->bases_end();
4127        Base != BaseEnd; ++Base) {
4128     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4129       SawLastInitializer
4130         = NumInitializers > 0 &&
4131           Initializers[NumInitializers - 1]->isBaseInitializer() &&
4132           Context.hasSameUnqualifiedType(Base->getType(),
4133                QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
4134       continue;
4135     }
4136 
4137     Builder.AddTypedTextChunk(
4138                Results.getAllocator().CopyString(
4139                           Base->getType().getAsString(Policy)));
4140     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4141     Builder.AddPlaceholderChunk("args");
4142     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4143     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4144                                    SawLastInitializer? CCP_NextInitializer
4145                                                      : CCP_MemberDeclaration));
4146     SawLastInitializer = false;
4147   }
4148 
4149   // Add completions for virtual base classes.
4150   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4151                                        BaseEnd = ClassDecl->vbases_end();
4152        Base != BaseEnd; ++Base) {
4153     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4154       SawLastInitializer
4155         = NumInitializers > 0 &&
4156           Initializers[NumInitializers - 1]->isBaseInitializer() &&
4157           Context.hasSameUnqualifiedType(Base->getType(),
4158                QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
4159       continue;
4160     }
4161 
4162     Builder.AddTypedTextChunk(
4163                Builder.getAllocator().CopyString(
4164                           Base->getType().getAsString(Policy)));
4165     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4166     Builder.AddPlaceholderChunk("args");
4167     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4168     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4169                                    SawLastInitializer? CCP_NextInitializer
4170                                                      : CCP_MemberDeclaration));
4171     SawLastInitializer = false;
4172   }
4173 
4174   // Add completions for members.
4175   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4176                                   FieldEnd = ClassDecl->field_end();
4177        Field != FieldEnd; ++Field) {
4178     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4179       SawLastInitializer
4180         = NumInitializers > 0 &&
4181           Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4182           Initializers[NumInitializers - 1]->getAnyMember() == *Field;
4183       continue;
4184     }
4185 
4186     if (!Field->getDeclName())
4187       continue;
4188 
4189     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4190                                          Field->getIdentifier()->getName()));
4191     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4192     Builder.AddPlaceholderChunk("args");
4193     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4194     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4195                                    SawLastInitializer? CCP_NextInitializer
4196                                                      : CCP_MemberDeclaration,
4197                                            CXCursor_MemberRef));
4198     SawLastInitializer = false;
4199   }
4200   Results.ExitScope();
4201 
4202   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4203                             Results.data(), Results.size());
4204 }
4205 
4206 /// \brief Determine whether this scope denotes a namespace.
4207 static bool isNamespaceScope(Scope *S) {
4208   DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
4209   if (!DC)
4210     return false;
4211 
4212   return DC->isFileContext();
4213 }
4214 
4215 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4216                                         bool AfterAmpersand) {
4217   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4218                         CodeCompletionContext::CCC_Other);
4219   Results.EnterNewScope();
4220 
4221   // Note what has already been captured.
4222   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4223   bool IncludedThis = false;
4224   for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4225                                              CEnd = Intro.Captures.end();
4226        C != CEnd; ++C) {
4227     if (C->Kind == LCK_This) {
4228       IncludedThis = true;
4229       continue;
4230     }
4231 
4232     Known.insert(C->Id);
4233   }
4234 
4235   // Look for other capturable variables.
4236   for (; S && !isNamespaceScope(S); S = S->getParent()) {
4237     for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4238          D != DEnd; ++D) {
4239       VarDecl *Var = dyn_cast<VarDecl>(*D);
4240       if (!Var ||
4241           !Var->hasLocalStorage() ||
4242           Var->hasAttr<BlocksAttr>())
4243         continue;
4244 
4245       if (Known.insert(Var->getIdentifier()))
4246         Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
4247     }
4248   }
4249 
4250   // Add 'this', if it would be valid.
4251   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4252     addThisCompletion(*this, Results);
4253 
4254   Results.ExitScope();
4255 
4256   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4257                             Results.data(), Results.size());
4258 }
4259 
4260 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4261 // true or false.
4262 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
4263 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4264                                          ResultBuilder &Results,
4265                                          bool NeedAt) {
4266   typedef CodeCompletionResult Result;
4267   // Since we have an implementation, we can end it.
4268   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
4269 
4270   CodeCompletionBuilder Builder(Results.getAllocator());
4271   if (LangOpts.ObjC2) {
4272     // @dynamic
4273     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4274     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4275     Builder.AddPlaceholderChunk("property");
4276     Results.AddResult(Result(Builder.TakeString()));
4277 
4278     // @synthesize
4279     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4280     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4281     Builder.AddPlaceholderChunk("property");
4282     Results.AddResult(Result(Builder.TakeString()));
4283   }
4284 }
4285 
4286 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4287                                     ResultBuilder &Results,
4288                                     bool NeedAt) {
4289   typedef CodeCompletionResult Result;
4290 
4291   // Since we have an interface or protocol, we can end it.
4292   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
4293 
4294   if (LangOpts.ObjC2) {
4295     // @property
4296     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
4297 
4298     // @required
4299     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
4300 
4301     // @optional
4302     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
4303   }
4304 }
4305 
4306 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4307   typedef CodeCompletionResult Result;
4308   CodeCompletionBuilder Builder(Results.getAllocator());
4309 
4310   // @class name ;
4311   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4312   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4313   Builder.AddPlaceholderChunk("name");
4314   Results.AddResult(Result(Builder.TakeString()));
4315 
4316   if (Results.includeCodePatterns()) {
4317     // @interface name
4318     // FIXME: Could introduce the whole pattern, including superclasses and
4319     // such.
4320     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4321     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4322     Builder.AddPlaceholderChunk("class");
4323     Results.AddResult(Result(Builder.TakeString()));
4324 
4325     // @protocol name
4326     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4327     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4328     Builder.AddPlaceholderChunk("protocol");
4329     Results.AddResult(Result(Builder.TakeString()));
4330 
4331     // @implementation name
4332     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4333     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4334     Builder.AddPlaceholderChunk("class");
4335     Results.AddResult(Result(Builder.TakeString()));
4336   }
4337 
4338   // @compatibility_alias name
4339   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4340   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4341   Builder.AddPlaceholderChunk("alias");
4342   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4343   Builder.AddPlaceholderChunk("class");
4344   Results.AddResult(Result(Builder.TakeString()));
4345 }
4346 
4347 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4348   typedef CodeCompletionResult Result;
4349   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4350                         CodeCompletionContext::CCC_Other);
4351   Results.EnterNewScope();
4352   if (isa<ObjCImplDecl>(CurContext))
4353     AddObjCImplementationResults(getLangOpts(), Results, false);
4354   else if (CurContext->isObjCContainer())
4355     AddObjCInterfaceResults(getLangOpts(), Results, false);
4356   else
4357     AddObjCTopLevelResults(Results, false);
4358   Results.ExitScope();
4359   HandleCodeCompleteResults(this, CodeCompleter,
4360                             CodeCompletionContext::CCC_Other,
4361                             Results.data(),Results.size());
4362 }
4363 
4364 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
4365   typedef CodeCompletionResult Result;
4366   CodeCompletionBuilder Builder(Results.getAllocator());
4367 
4368   // @encode ( type-name )
4369   const char *EncodeType = "char[]";
4370   if (Results.getSema().getLangOpts().CPlusPlus ||
4371       Results.getSema().getLangOpts().ConstStrings)
4372     EncodeType = " const char[]";
4373   Builder.AddResultTypeChunk(EncodeType);
4374   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4375   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4376   Builder.AddPlaceholderChunk("type-name");
4377   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4378   Results.AddResult(Result(Builder.TakeString()));
4379 
4380   // @protocol ( protocol-name )
4381   Builder.AddResultTypeChunk("Protocol *");
4382   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4383   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4384   Builder.AddPlaceholderChunk("protocol-name");
4385   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4386   Results.AddResult(Result(Builder.TakeString()));
4387 
4388   // @selector ( selector )
4389   Builder.AddResultTypeChunk("SEL");
4390   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4391   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4392   Builder.AddPlaceholderChunk("selector");
4393   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4394   Results.AddResult(Result(Builder.TakeString()));
4395 
4396   // @[ objects, ... ]
4397   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,[));
4398   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4399   Builder.AddPlaceholderChunk("objects, ...");
4400   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4401   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4402   Results.AddResult(Result(Builder.TakeString()));
4403 
4404   // @{ key : object, ... }
4405   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,{));
4406   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4407   Builder.AddPlaceholderChunk("key");
4408   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4409   Builder.AddChunk(CodeCompletionString::CK_Colon);
4410   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4411   Builder.AddPlaceholderChunk("object, ...");
4412   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4413   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4414   Results.AddResult(Result(Builder.TakeString()));
4415 }
4416 
4417 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
4418   typedef CodeCompletionResult Result;
4419   CodeCompletionBuilder Builder(Results.getAllocator());
4420 
4421   if (Results.includeCodePatterns()) {
4422     // @try { statements } @catch ( declaration ) { statements } @finally
4423     //   { statements }
4424     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4425     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4426     Builder.AddPlaceholderChunk("statements");
4427     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4428     Builder.AddTextChunk("@catch");
4429     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4430     Builder.AddPlaceholderChunk("parameter");
4431     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4432     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4433     Builder.AddPlaceholderChunk("statements");
4434     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4435     Builder.AddTextChunk("@finally");
4436     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4437     Builder.AddPlaceholderChunk("statements");
4438     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4439     Results.AddResult(Result(Builder.TakeString()));
4440   }
4441 
4442   // @throw
4443   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4444   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4445   Builder.AddPlaceholderChunk("expression");
4446   Results.AddResult(Result(Builder.TakeString()));
4447 
4448   if (Results.includeCodePatterns()) {
4449     // @synchronized ( expression ) { statements }
4450     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4451     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4452     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4453     Builder.AddPlaceholderChunk("expression");
4454     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4455     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4456     Builder.AddPlaceholderChunk("statements");
4457     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4458     Results.AddResult(Result(Builder.TakeString()));
4459   }
4460 }
4461 
4462 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
4463                                      ResultBuilder &Results,
4464                                      bool NeedAt) {
4465   typedef CodeCompletionResult Result;
4466   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4467   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4468   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
4469   if (LangOpts.ObjC2)
4470     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
4471 }
4472 
4473 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
4474   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4475                         CodeCompletionContext::CCC_Other);
4476   Results.EnterNewScope();
4477   AddObjCVisibilityResults(getLangOpts(), Results, false);
4478   Results.ExitScope();
4479   HandleCodeCompleteResults(this, CodeCompleter,
4480                             CodeCompletionContext::CCC_Other,
4481                             Results.data(),Results.size());
4482 }
4483 
4484 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
4485   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4486                         CodeCompletionContext::CCC_Other);
4487   Results.EnterNewScope();
4488   AddObjCStatementResults(Results, false);
4489   AddObjCExpressionResults(Results, false);
4490   Results.ExitScope();
4491   HandleCodeCompleteResults(this, CodeCompleter,
4492                             CodeCompletionContext::CCC_Other,
4493                             Results.data(),Results.size());
4494 }
4495 
4496 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
4497   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4498                         CodeCompletionContext::CCC_Other);
4499   Results.EnterNewScope();
4500   AddObjCExpressionResults(Results, false);
4501   Results.ExitScope();
4502   HandleCodeCompleteResults(this, CodeCompleter,
4503                             CodeCompletionContext::CCC_Other,
4504                             Results.data(),Results.size());
4505 }
4506 
4507 /// \brief Determine whether the addition of the given flag to an Objective-C
4508 /// property's attributes will cause a conflict.
4509 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4510   // Check if we've already added this flag.
4511   if (Attributes & NewFlag)
4512     return true;
4513 
4514   Attributes |= NewFlag;
4515 
4516   // Check for collisions with "readonly".
4517   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4518       (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4519                      ObjCDeclSpec::DQ_PR_assign |
4520                      ObjCDeclSpec::DQ_PR_unsafe_unretained |
4521                      ObjCDeclSpec::DQ_PR_copy |
4522                      ObjCDeclSpec::DQ_PR_retain |
4523                      ObjCDeclSpec::DQ_PR_strong)))
4524     return true;
4525 
4526   // Check for more than one of { assign, copy, retain, strong }.
4527   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4528                                          ObjCDeclSpec::DQ_PR_unsafe_unretained |
4529                                              ObjCDeclSpec::DQ_PR_copy |
4530                                              ObjCDeclSpec::DQ_PR_retain|
4531                                              ObjCDeclSpec::DQ_PR_strong);
4532   if (AssignCopyRetMask &&
4533       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4534       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
4535       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4536       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4537       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
4538     return true;
4539 
4540   return false;
4541 }
4542 
4543 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
4544   if (!CodeCompleter)
4545     return;
4546 
4547   unsigned Attributes = ODS.getPropertyAttributes();
4548 
4549   typedef CodeCompletionResult Result;
4550   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4551                         CodeCompletionContext::CCC_Other);
4552   Results.EnterNewScope();
4553   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
4554     Results.AddResult(CodeCompletionResult("readonly"));
4555   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
4556     Results.AddResult(CodeCompletionResult("assign"));
4557   if (!ObjCPropertyFlagConflicts(Attributes,
4558                                  ObjCDeclSpec::DQ_PR_unsafe_unretained))
4559     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
4560   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
4561     Results.AddResult(CodeCompletionResult("readwrite"));
4562   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
4563     Results.AddResult(CodeCompletionResult("retain"));
4564   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4565     Results.AddResult(CodeCompletionResult("strong"));
4566   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
4567     Results.AddResult(CodeCompletionResult("copy"));
4568   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
4569     Results.AddResult(CodeCompletionResult("nonatomic"));
4570   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4571     Results.AddResult(CodeCompletionResult("atomic"));
4572   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
4573     CodeCompletionBuilder Setter(Results.getAllocator());
4574     Setter.AddTypedTextChunk("setter");
4575     Setter.AddTextChunk(" = ");
4576     Setter.AddPlaceholderChunk("method");
4577     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
4578   }
4579   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4580     CodeCompletionBuilder Getter(Results.getAllocator());
4581     Getter.AddTypedTextChunk("getter");
4582     Getter.AddTextChunk(" = ");
4583     Getter.AddPlaceholderChunk("method");
4584     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
4585   }
4586   Results.ExitScope();
4587   HandleCodeCompleteResults(this, CodeCompleter,
4588                             CodeCompletionContext::CCC_Other,
4589                             Results.data(),Results.size());
4590 }
4591 
4592 /// \brief Descripts the kind of Objective-C method that we want to find
4593 /// via code completion.
4594 enum ObjCMethodKind {
4595   MK_Any, //< Any kind of method, provided it means other specified criteria.
4596   MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4597   MK_OneArgSelector //< One-argument selector.
4598 };
4599 
4600 static bool isAcceptableObjCSelector(Selector Sel,
4601                                      ObjCMethodKind WantKind,
4602                                      IdentifierInfo **SelIdents,
4603                                      unsigned NumSelIdents,
4604                                      bool AllowSameLength = true) {
4605   if (NumSelIdents > Sel.getNumArgs())
4606     return false;
4607 
4608   switch (WantKind) {
4609     case MK_Any:             break;
4610     case MK_ZeroArgSelector: return Sel.isUnarySelector();
4611     case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
4612   }
4613 
4614   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4615     return false;
4616 
4617   for (unsigned I = 0; I != NumSelIdents; ++I)
4618     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4619       return false;
4620 
4621   return true;
4622 }
4623 
4624 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4625                                    ObjCMethodKind WantKind,
4626                                    IdentifierInfo **SelIdents,
4627                                    unsigned NumSelIdents,
4628                                    bool AllowSameLength = true) {
4629   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4630                                   NumSelIdents, AllowSameLength);
4631 }
4632 
4633 namespace {
4634   /// \brief A set of selectors, which is used to avoid introducing multiple
4635   /// completions with the same selector into the result set.
4636   typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4637 }
4638 
4639 /// \brief Add all of the Objective-C methods in the given Objective-C
4640 /// container to the set of results.
4641 ///
4642 /// The container will be a class, protocol, category, or implementation of
4643 /// any of the above. This mether will recurse to include methods from
4644 /// the superclasses of classes along with their categories, protocols, and
4645 /// implementations.
4646 ///
4647 /// \param Container the container in which we'll look to find methods.
4648 ///
4649 /// \param WantInstance whether to add instance methods (only); if false, this
4650 /// routine will add factory methods (only).
4651 ///
4652 /// \param CurContext the context in which we're performing the lookup that
4653 /// finds methods.
4654 ///
4655 /// \param AllowSameLength Whether we allow a method to be added to the list
4656 /// when it has the same number of parameters as we have selector identifiers.
4657 ///
4658 /// \param Results the structure into which we'll add results.
4659 static void AddObjCMethods(ObjCContainerDecl *Container,
4660                            bool WantInstanceMethods,
4661                            ObjCMethodKind WantKind,
4662                            IdentifierInfo **SelIdents,
4663                            unsigned NumSelIdents,
4664                            DeclContext *CurContext,
4665                            VisitedSelectorSet &Selectors,
4666                            bool AllowSameLength,
4667                            ResultBuilder &Results,
4668                            bool InOriginalClass = true) {
4669   typedef CodeCompletionResult Result;
4670   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4671                                        MEnd = Container->meth_end();
4672        M != MEnd; ++M) {
4673     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4674       // Check whether the selector identifiers we've been given are a
4675       // subset of the identifiers for this particular method.
4676       if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4677                                   AllowSameLength))
4678         continue;
4679 
4680       if (!Selectors.insert((*M)->getSelector()))
4681         continue;
4682 
4683       Result R = Result(*M, 0);
4684       R.StartParameter = NumSelIdents;
4685       R.AllParametersAreInformative = (WantKind != MK_Any);
4686       if (!InOriginalClass)
4687         R.Priority += CCD_InBaseClass;
4688       Results.MaybeAddResult(R, CurContext);
4689     }
4690   }
4691 
4692   // Visit the protocols of protocols.
4693   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4694     if (Protocol->hasDefinition()) {
4695       const ObjCList<ObjCProtocolDecl> &Protocols
4696         = Protocol->getReferencedProtocols();
4697       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4698                                                 E = Protocols.end();
4699            I != E; ++I)
4700         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4701                        NumSelIdents, CurContext, Selectors, AllowSameLength,
4702                        Results, false);
4703     }
4704   }
4705 
4706   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4707   if (!IFace || !IFace->hasDefinition())
4708     return;
4709 
4710   // Add methods in protocols.
4711   for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
4712                                             E = IFace->protocol_end();
4713        I != E; ++I)
4714     AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
4715                    CurContext, Selectors, AllowSameLength, Results, false);
4716 
4717   // Add methods in categories.
4718   for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4719        CatDecl = CatDecl->getNextClassCategory()) {
4720     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
4721                    NumSelIdents, CurContext, Selectors, AllowSameLength,
4722                    Results, InOriginalClass);
4723 
4724     // Add a categories protocol methods.
4725     const ObjCList<ObjCProtocolDecl> &Protocols
4726       = CatDecl->getReferencedProtocols();
4727     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4728                                               E = Protocols.end();
4729          I != E; ++I)
4730       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4731                      NumSelIdents, CurContext, Selectors, AllowSameLength,
4732                      Results, false);
4733 
4734     // Add methods in category implementations.
4735     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
4736       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4737                      NumSelIdents, CurContext, Selectors, AllowSameLength,
4738                      Results, InOriginalClass);
4739   }
4740 
4741   // Add methods in superclass.
4742   if (IFace->getSuperClass())
4743     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
4744                    SelIdents, NumSelIdents, CurContext, Selectors,
4745                    AllowSameLength, Results, false);
4746 
4747   // Add methods in our implementation, if any.
4748   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4749     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4750                    NumSelIdents, CurContext, Selectors, AllowSameLength,
4751                    Results, InOriginalClass);
4752 }
4753 
4754 
4755 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
4756   typedef CodeCompletionResult Result;
4757 
4758   // Try to find the interface where getters might live.
4759   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4760   if (!Class) {
4761     if (ObjCCategoryDecl *Category
4762           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4763       Class = Category->getClassInterface();
4764 
4765     if (!Class)
4766       return;
4767   }
4768 
4769   // Find all of the potential getters.
4770   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4771                         CodeCompletionContext::CCC_Other);
4772   Results.EnterNewScope();
4773 
4774   VisitedSelectorSet Selectors;
4775   AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
4776                  /*AllowSameLength=*/true, Results);
4777   Results.ExitScope();
4778   HandleCodeCompleteResults(this, CodeCompleter,
4779                             CodeCompletionContext::CCC_Other,
4780                             Results.data(),Results.size());
4781 }
4782 
4783 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
4784   typedef CodeCompletionResult Result;
4785 
4786   // Try to find the interface where setters might live.
4787   ObjCInterfaceDecl *Class
4788     = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4789   if (!Class) {
4790     if (ObjCCategoryDecl *Category
4791           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4792       Class = Category->getClassInterface();
4793 
4794     if (!Class)
4795       return;
4796   }
4797 
4798   // Find all of the potential getters.
4799   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4800                         CodeCompletionContext::CCC_Other);
4801   Results.EnterNewScope();
4802 
4803   VisitedSelectorSet Selectors;
4804   AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4805                  Selectors, /*AllowSameLength=*/true, Results);
4806 
4807   Results.ExitScope();
4808   HandleCodeCompleteResults(this, CodeCompleter,
4809                             CodeCompletionContext::CCC_Other,
4810                             Results.data(),Results.size());
4811 }
4812 
4813 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4814                                        bool IsParameter) {
4815   typedef CodeCompletionResult Result;
4816   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4817                         CodeCompletionContext::CCC_Type);
4818   Results.EnterNewScope();
4819 
4820   // Add context-sensitive, Objective-C parameter-passing keywords.
4821   bool AddedInOut = false;
4822   if ((DS.getObjCDeclQualifier() &
4823        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4824     Results.AddResult("in");
4825     Results.AddResult("inout");
4826     AddedInOut = true;
4827   }
4828   if ((DS.getObjCDeclQualifier() &
4829        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4830     Results.AddResult("out");
4831     if (!AddedInOut)
4832       Results.AddResult("inout");
4833   }
4834   if ((DS.getObjCDeclQualifier() &
4835        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4836         ObjCDeclSpec::DQ_Oneway)) == 0) {
4837      Results.AddResult("bycopy");
4838      Results.AddResult("byref");
4839      Results.AddResult("oneway");
4840   }
4841 
4842   // If we're completing the return type of an Objective-C method and the
4843   // identifier IBAction refers to a macro, provide a completion item for
4844   // an action, e.g.,
4845   //   IBAction)<#selector#>:(id)sender
4846   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4847       Context.Idents.get("IBAction").hasMacroDefinition()) {
4848     typedef CodeCompletionString::Chunk Chunk;
4849     CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4850                                   CXAvailability_Available);
4851     Builder.AddTypedTextChunk("IBAction");
4852     Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4853     Builder.AddPlaceholderChunk("selector");
4854     Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4855     Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4856     Builder.AddTextChunk("id");
4857     Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4858     Builder.AddTextChunk("sender");
4859     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4860   }
4861 
4862   // Add various builtin type names and specifiers.
4863   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4864   Results.ExitScope();
4865 
4866   // Add the various type names
4867   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4868   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4869   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4870                      CodeCompleter->includeGlobals());
4871 
4872   if (CodeCompleter->includeMacros())
4873     AddMacroResults(PP, Results);
4874 
4875   HandleCodeCompleteResults(this, CodeCompleter,
4876                             CodeCompletionContext::CCC_Type,
4877                             Results.data(), Results.size());
4878 }
4879 
4880 /// \brief When we have an expression with type "id", we may assume
4881 /// that it has some more-specific class type based on knowledge of
4882 /// common uses of Objective-C. This routine returns that class type,
4883 /// or NULL if no better result could be determined.
4884 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
4885   ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
4886   if (!Msg)
4887     return 0;
4888 
4889   Selector Sel = Msg->getSelector();
4890   if (Sel.isNull())
4891     return 0;
4892 
4893   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4894   if (!Id)
4895     return 0;
4896 
4897   ObjCMethodDecl *Method = Msg->getMethodDecl();
4898   if (!Method)
4899     return 0;
4900 
4901   // Determine the class that we're sending the message to.
4902   ObjCInterfaceDecl *IFace = 0;
4903   switch (Msg->getReceiverKind()) {
4904   case ObjCMessageExpr::Class:
4905     if (const ObjCObjectType *ObjType
4906                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4907       IFace = ObjType->getInterface();
4908     break;
4909 
4910   case ObjCMessageExpr::Instance: {
4911     QualType T = Msg->getInstanceReceiver()->getType();
4912     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4913       IFace = Ptr->getInterfaceDecl();
4914     break;
4915   }
4916 
4917   case ObjCMessageExpr::SuperInstance:
4918   case ObjCMessageExpr::SuperClass:
4919     break;
4920   }
4921 
4922   if (!IFace)
4923     return 0;
4924 
4925   ObjCInterfaceDecl *Super = IFace->getSuperClass();
4926   if (Method->isInstanceMethod())
4927     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4928       .Case("retain", IFace)
4929       .Case("strong", IFace)
4930       .Case("autorelease", IFace)
4931       .Case("copy", IFace)
4932       .Case("copyWithZone", IFace)
4933       .Case("mutableCopy", IFace)
4934       .Case("mutableCopyWithZone", IFace)
4935       .Case("awakeFromCoder", IFace)
4936       .Case("replacementObjectFromCoder", IFace)
4937       .Case("class", IFace)
4938       .Case("classForCoder", IFace)
4939       .Case("superclass", Super)
4940       .Default(0);
4941 
4942   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4943     .Case("new", IFace)
4944     .Case("alloc", IFace)
4945     .Case("allocWithZone", IFace)
4946     .Case("class", IFace)
4947     .Case("superclass", Super)
4948     .Default(0);
4949 }
4950 
4951 // Add a special completion for a message send to "super", which fills in the
4952 // most likely case of forwarding all of our arguments to the superclass
4953 // function.
4954 ///
4955 /// \param S The semantic analysis object.
4956 ///
4957 /// \param S NeedSuperKeyword Whether we need to prefix this completion with
4958 /// the "super" keyword. Otherwise, we just need to provide the arguments.
4959 ///
4960 /// \param SelIdents The identifiers in the selector that have already been
4961 /// provided as arguments for a send to "super".
4962 ///
4963 /// \param NumSelIdents The number of identifiers in \p SelIdents.
4964 ///
4965 /// \param Results The set of results to augment.
4966 ///
4967 /// \returns the Objective-C method declaration that would be invoked by
4968 /// this "super" completion. If NULL, no completion was added.
4969 static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4970                                               IdentifierInfo **SelIdents,
4971                                               unsigned NumSelIdents,
4972                                               ResultBuilder &Results) {
4973   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4974   if (!CurMethod)
4975     return 0;
4976 
4977   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4978   if (!Class)
4979     return 0;
4980 
4981   // Try to find a superclass method with the same selector.
4982   ObjCMethodDecl *SuperMethod = 0;
4983   while ((Class = Class->getSuperClass()) && !SuperMethod) {
4984     // Check in the class
4985     SuperMethod = Class->getMethod(CurMethod->getSelector(),
4986                                    CurMethod->isInstanceMethod());
4987 
4988     // Check in categories or class extensions.
4989     if (!SuperMethod) {
4990       for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4991            Category = Category->getNextClassCategory())
4992         if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4993                                                CurMethod->isInstanceMethod())))
4994           break;
4995     }
4996   }
4997 
4998   if (!SuperMethod)
4999     return 0;
5000 
5001   // Check whether the superclass method has the same signature.
5002   if (CurMethod->param_size() != SuperMethod->param_size() ||
5003       CurMethod->isVariadic() != SuperMethod->isVariadic())
5004     return 0;
5005 
5006   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5007                                    CurPEnd = CurMethod->param_end(),
5008                                     SuperP = SuperMethod->param_begin();
5009        CurP != CurPEnd; ++CurP, ++SuperP) {
5010     // Make sure the parameter types are compatible.
5011     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5012                                           (*SuperP)->getType()))
5013       return 0;
5014 
5015     // Make sure we have a parameter name to forward!
5016     if (!(*CurP)->getIdentifier())
5017       return 0;
5018   }
5019 
5020   // We have a superclass method. Now, form the send-to-super completion.
5021   CodeCompletionBuilder Builder(Results.getAllocator());
5022 
5023   // Give this completion a return type.
5024   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5025                      Builder);
5026 
5027   // If we need the "super" keyword, add it (plus some spacing).
5028   if (NeedSuperKeyword) {
5029     Builder.AddTypedTextChunk("super");
5030     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5031   }
5032 
5033   Selector Sel = CurMethod->getSelector();
5034   if (Sel.isUnarySelector()) {
5035     if (NeedSuperKeyword)
5036       Builder.AddTextChunk(Builder.getAllocator().CopyString(
5037                                   Sel.getNameForSlot(0)));
5038     else
5039       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5040                                    Sel.getNameForSlot(0)));
5041   } else {
5042     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5043     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5044       if (I > NumSelIdents)
5045         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5046 
5047       if (I < NumSelIdents)
5048         Builder.AddInformativeChunk(
5049                    Builder.getAllocator().CopyString(
5050                                                  Sel.getNameForSlot(I) + ":"));
5051       else if (NeedSuperKeyword || I > NumSelIdents) {
5052         Builder.AddTextChunk(
5053                  Builder.getAllocator().CopyString(
5054                                                   Sel.getNameForSlot(I) + ":"));
5055         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5056                                          (*CurP)->getIdentifier()->getName()));
5057       } else {
5058         Builder.AddTypedTextChunk(
5059                   Builder.getAllocator().CopyString(
5060                                                   Sel.getNameForSlot(I) + ":"));
5061         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5062                                          (*CurP)->getIdentifier()->getName()));
5063       }
5064     }
5065   }
5066 
5067   Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
5068                                          SuperMethod->isInstanceMethod()
5069                                            ? CXCursor_ObjCInstanceMethodDecl
5070                                            : CXCursor_ObjCClassMethodDecl));
5071   return SuperMethod;
5072 }
5073 
5074 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5075   typedef CodeCompletionResult Result;
5076   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5077                         CodeCompletionContext::CCC_ObjCMessageReceiver,
5078                         getLangOpts().CPlusPlus0x
5079                           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5080                           : &ResultBuilder::IsObjCMessageReceiver);
5081 
5082   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5083   Results.EnterNewScope();
5084   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5085                      CodeCompleter->includeGlobals());
5086 
5087   // If we are in an Objective-C method inside a class that has a superclass,
5088   // add "super" as an option.
5089   if (ObjCMethodDecl *Method = getCurMethodDecl())
5090     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5091       if (Iface->getSuperClass()) {
5092         Results.AddResult(Result("super"));
5093 
5094         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
5095       }
5096 
5097   if (getLangOpts().CPlusPlus0x)
5098     addThisCompletion(*this, Results);
5099 
5100   Results.ExitScope();
5101 
5102   if (CodeCompleter->includeMacros())
5103     AddMacroResults(PP, Results);
5104   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5105                             Results.data(), Results.size());
5106 
5107 }
5108 
5109 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5110                                         IdentifierInfo **SelIdents,
5111                                         unsigned NumSelIdents,
5112                                         bool AtArgumentExpression) {
5113   ObjCInterfaceDecl *CDecl = 0;
5114   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5115     // Figure out which interface we're in.
5116     CDecl = CurMethod->getClassInterface();
5117     if (!CDecl)
5118       return;
5119 
5120     // Find the superclass of this class.
5121     CDecl = CDecl->getSuperClass();
5122     if (!CDecl)
5123       return;
5124 
5125     if (CurMethod->isInstanceMethod()) {
5126       // We are inside an instance method, which means that the message
5127       // send [super ...] is actually calling an instance method on the
5128       // current object.
5129       return CodeCompleteObjCInstanceMessage(S, 0,
5130                                              SelIdents, NumSelIdents,
5131                                              AtArgumentExpression,
5132                                              CDecl);
5133     }
5134 
5135     // Fall through to send to the superclass in CDecl.
5136   } else {
5137     // "super" may be the name of a type or variable. Figure out which
5138     // it is.
5139     IdentifierInfo *Super = &Context.Idents.get("super");
5140     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5141                                      LookupOrdinaryName);
5142     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5143       // "super" names an interface. Use it.
5144     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5145       if (const ObjCObjectType *Iface
5146             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5147         CDecl = Iface->getInterface();
5148     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5149       // "super" names an unresolved type; we can't be more specific.
5150     } else {
5151       // Assume that "super" names some kind of value and parse that way.
5152       CXXScopeSpec SS;
5153       SourceLocation TemplateKWLoc;
5154       UnqualifiedId id;
5155       id.setIdentifier(Super, SuperLoc);
5156       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5157                                                false, false);
5158       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5159                                              SelIdents, NumSelIdents,
5160                                              AtArgumentExpression);
5161     }
5162 
5163     // Fall through
5164   }
5165 
5166   ParsedType Receiver;
5167   if (CDecl)
5168     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5169   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5170                                       NumSelIdents, AtArgumentExpression,
5171                                       /*IsSuper=*/true);
5172 }
5173 
5174 /// \brief Given a set of code-completion results for the argument of a message
5175 /// send, determine the preferred type (if any) for that argument expression.
5176 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5177                                                        unsigned NumSelIdents) {
5178   typedef CodeCompletionResult Result;
5179   ASTContext &Context = Results.getSema().Context;
5180 
5181   QualType PreferredType;
5182   unsigned BestPriority = CCP_Unlikely * 2;
5183   Result *ResultsData = Results.data();
5184   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5185     Result &R = ResultsData[I];
5186     if (R.Kind == Result::RK_Declaration &&
5187         isa<ObjCMethodDecl>(R.Declaration)) {
5188       if (R.Priority <= BestPriority) {
5189         ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5190         if (NumSelIdents <= Method->param_size()) {
5191           QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5192                                        ->getType();
5193           if (R.Priority < BestPriority || PreferredType.isNull()) {
5194             BestPriority = R.Priority;
5195             PreferredType = MyPreferredType;
5196           } else if (!Context.hasSameUnqualifiedType(PreferredType,
5197                                                      MyPreferredType)) {
5198             PreferredType = QualType();
5199           }
5200         }
5201       }
5202     }
5203   }
5204 
5205   return PreferredType;
5206 }
5207 
5208 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5209                                        ParsedType Receiver,
5210                                        IdentifierInfo **SelIdents,
5211                                        unsigned NumSelIdents,
5212                                        bool AtArgumentExpression,
5213                                        bool IsSuper,
5214                                        ResultBuilder &Results) {
5215   typedef CodeCompletionResult Result;
5216   ObjCInterfaceDecl *CDecl = 0;
5217 
5218   // If the given name refers to an interface type, retrieve the
5219   // corresponding declaration.
5220   if (Receiver) {
5221     QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
5222     if (!T.isNull())
5223       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5224         CDecl = Interface->getInterface();
5225   }
5226 
5227   // Add all of the factory methods in this Objective-C class, its protocols,
5228   // superclasses, categories, implementation, etc.
5229   Results.EnterNewScope();
5230 
5231   // If this is a send-to-super, try to add the special "super" send
5232   // completion.
5233   if (IsSuper) {
5234     if (ObjCMethodDecl *SuperMethod
5235         = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5236                                  Results))
5237       Results.Ignore(SuperMethod);
5238   }
5239 
5240   // If we're inside an Objective-C method definition, prefer its selector to
5241   // others.
5242   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5243     Results.setPreferredSelector(CurMethod->getSelector());
5244 
5245   VisitedSelectorSet Selectors;
5246   if (CDecl)
5247     AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
5248                    SemaRef.CurContext, Selectors, AtArgumentExpression,
5249                    Results);
5250   else {
5251     // We're messaging "id" as a type; provide all class/factory methods.
5252 
5253     // If we have an external source, load the entire class method
5254     // pool from the AST file.
5255     if (SemaRef.ExternalSource) {
5256       for (uint32_t I = 0,
5257                     N = SemaRef.ExternalSource->GetNumExternalSelectors();
5258            I != N; ++I) {
5259         Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5260         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5261           continue;
5262 
5263         SemaRef.ReadMethodPool(Sel);
5264       }
5265     }
5266 
5267     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5268                                        MEnd = SemaRef.MethodPool.end();
5269          M != MEnd; ++M) {
5270       for (ObjCMethodList *MethList = &M->second.second;
5271            MethList && MethList->Method;
5272            MethList = MethList->Next) {
5273         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5274                                     NumSelIdents))
5275           continue;
5276 
5277         Result R(MethList->Method, 0);
5278         R.StartParameter = NumSelIdents;
5279         R.AllParametersAreInformative = false;
5280         Results.MaybeAddResult(R, SemaRef.CurContext);
5281       }
5282     }
5283   }
5284 
5285   Results.ExitScope();
5286 }
5287 
5288 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5289                                         IdentifierInfo **SelIdents,
5290                                         unsigned NumSelIdents,
5291                                         bool AtArgumentExpression,
5292                                         bool IsSuper) {
5293 
5294   QualType T = this->GetTypeFromParser(Receiver);
5295 
5296   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5297               CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5298                                     T, SelIdents, NumSelIdents));
5299 
5300   AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5301                              AtArgumentExpression, IsSuper, Results);
5302 
5303   // If we're actually at the argument expression (rather than prior to the
5304   // selector), we're actually performing code completion for an expression.
5305   // Determine whether we have a single, best method. If so, we can
5306   // code-complete the expression using the corresponding parameter type as
5307   // our preferred type, improving completion results.
5308   if (AtArgumentExpression) {
5309     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5310                                                                   NumSelIdents);
5311     if (PreferredType.isNull())
5312       CodeCompleteOrdinaryName(S, PCC_Expression);
5313     else
5314       CodeCompleteExpression(S, PreferredType);
5315     return;
5316   }
5317 
5318   HandleCodeCompleteResults(this, CodeCompleter,
5319                             Results.getCompletionContext(),
5320                             Results.data(), Results.size());
5321 }
5322 
5323 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5324                                            IdentifierInfo **SelIdents,
5325                                            unsigned NumSelIdents,
5326                                            bool AtArgumentExpression,
5327                                            ObjCInterfaceDecl *Super) {
5328   typedef CodeCompletionResult Result;
5329 
5330   Expr *RecExpr = static_cast<Expr *>(Receiver);
5331 
5332   // If necessary, apply function/array conversion to the receiver.
5333   // C99 6.7.5.3p[7,8].
5334   if (RecExpr) {
5335     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5336     if (Conv.isInvalid()) // conversion failed. bail.
5337       return;
5338     RecExpr = Conv.take();
5339   }
5340   QualType ReceiverType = RecExpr? RecExpr->getType()
5341                           : Super? Context.getObjCObjectPointerType(
5342                                             Context.getObjCInterfaceType(Super))
5343                                  : Context.getObjCIdType();
5344 
5345   // If we're messaging an expression with type "id" or "Class", check
5346   // whether we know something special about the receiver that allows
5347   // us to assume a more-specific receiver type.
5348   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5349     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5350       if (ReceiverType->isObjCClassType())
5351         return CodeCompleteObjCClassMessage(S,
5352                        ParsedType::make(Context.getObjCInterfaceType(IFace)),
5353                                             SelIdents, NumSelIdents,
5354                                             AtArgumentExpression, Super);
5355 
5356       ReceiverType = Context.getObjCObjectPointerType(
5357                                           Context.getObjCInterfaceType(IFace));
5358     }
5359 
5360   // Build the set of methods we can see.
5361   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5362            CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
5363                                  ReceiverType, SelIdents, NumSelIdents));
5364 
5365   Results.EnterNewScope();
5366 
5367   // If this is a send-to-super, try to add the special "super" send
5368   // completion.
5369   if (Super) {
5370     if (ObjCMethodDecl *SuperMethod
5371           = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5372                                    Results))
5373       Results.Ignore(SuperMethod);
5374   }
5375 
5376   // If we're inside an Objective-C method definition, prefer its selector to
5377   // others.
5378   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5379     Results.setPreferredSelector(CurMethod->getSelector());
5380 
5381   // Keep track of the selectors we've already added.
5382   VisitedSelectorSet Selectors;
5383 
5384   // Handle messages to Class. This really isn't a message to an instance
5385   // method, so we treat it the same way we would treat a message send to a
5386   // class method.
5387   if (ReceiverType->isObjCClassType() ||
5388       ReceiverType->isObjCQualifiedClassType()) {
5389     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5390       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
5391         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
5392                        CurContext, Selectors, AtArgumentExpression, Results);
5393     }
5394   }
5395   // Handle messages to a qualified ID ("id<foo>").
5396   else if (const ObjCObjectPointerType *QualID
5397              = ReceiverType->getAsObjCQualifiedIdType()) {
5398     // Search protocols for instance methods.
5399     for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5400                                               E = QualID->qual_end();
5401          I != E; ++I)
5402       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
5403                      Selectors, AtArgumentExpression, Results);
5404   }
5405   // Handle messages to a pointer to interface type.
5406   else if (const ObjCObjectPointerType *IFacePtr
5407                               = ReceiverType->getAsObjCInterfacePointerType()) {
5408     // Search the class, its superclasses, etc., for instance methods.
5409     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
5410                    NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5411                    Results);
5412 
5413     // Search protocols for instance methods.
5414     for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5415          E = IFacePtr->qual_end();
5416          I != E; ++I)
5417       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
5418                      Selectors, AtArgumentExpression, Results);
5419   }
5420   // Handle messages to "id".
5421   else if (ReceiverType->isObjCIdType()) {
5422     // We're messaging "id", so provide all instance methods we know
5423     // about as code-completion results.
5424 
5425     // If we have an external source, load the entire class method
5426     // pool from the AST file.
5427     if (ExternalSource) {
5428       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5429            I != N; ++I) {
5430         Selector Sel = ExternalSource->GetExternalSelector(I);
5431         if (Sel.isNull() || MethodPool.count(Sel))
5432           continue;
5433 
5434         ReadMethodPool(Sel);
5435       }
5436     }
5437 
5438     for (GlobalMethodPool::iterator M = MethodPool.begin(),
5439                                     MEnd = MethodPool.end();
5440          M != MEnd; ++M) {
5441       for (ObjCMethodList *MethList = &M->second.first;
5442            MethList && MethList->Method;
5443            MethList = MethList->Next) {
5444         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5445                                     NumSelIdents))
5446           continue;
5447 
5448         if (!Selectors.insert(MethList->Method->getSelector()))
5449           continue;
5450 
5451         Result R(MethList->Method, 0);
5452         R.StartParameter = NumSelIdents;
5453         R.AllParametersAreInformative = false;
5454         Results.MaybeAddResult(R, CurContext);
5455       }
5456     }
5457   }
5458   Results.ExitScope();
5459 
5460 
5461   // If we're actually at the argument expression (rather than prior to the
5462   // selector), we're actually performing code completion for an expression.
5463   // Determine whether we have a single, best method. If so, we can
5464   // code-complete the expression using the corresponding parameter type as
5465   // our preferred type, improving completion results.
5466   if (AtArgumentExpression) {
5467     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5468                                                                   NumSelIdents);
5469     if (PreferredType.isNull())
5470       CodeCompleteOrdinaryName(S, PCC_Expression);
5471     else
5472       CodeCompleteExpression(S, PreferredType);
5473     return;
5474   }
5475 
5476   HandleCodeCompleteResults(this, CodeCompleter,
5477                             Results.getCompletionContext(),
5478                             Results.data(),Results.size());
5479 }
5480 
5481 void Sema::CodeCompleteObjCForCollection(Scope *S,
5482                                          DeclGroupPtrTy IterationVar) {
5483   CodeCompleteExpressionData Data;
5484   Data.ObjCCollection = true;
5485 
5486   if (IterationVar.getAsOpaquePtr()) {
5487     DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5488     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5489       if (*I)
5490         Data.IgnoreDecls.push_back(*I);
5491     }
5492   }
5493 
5494   CodeCompleteExpression(S, Data);
5495 }
5496 
5497 void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5498                                     unsigned NumSelIdents) {
5499   // If we have an external source, load the entire class method
5500   // pool from the AST file.
5501   if (ExternalSource) {
5502     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5503          I != N; ++I) {
5504       Selector Sel = ExternalSource->GetExternalSelector(I);
5505       if (Sel.isNull() || MethodPool.count(Sel))
5506         continue;
5507 
5508       ReadMethodPool(Sel);
5509     }
5510   }
5511 
5512   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5513                         CodeCompletionContext::CCC_SelectorName);
5514   Results.EnterNewScope();
5515   for (GlobalMethodPool::iterator M = MethodPool.begin(),
5516                                MEnd = MethodPool.end();
5517        M != MEnd; ++M) {
5518 
5519     Selector Sel = M->first;
5520     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5521       continue;
5522 
5523     CodeCompletionBuilder Builder(Results.getAllocator());
5524     if (Sel.isUnarySelector()) {
5525       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5526                                                        Sel.getNameForSlot(0)));
5527       Results.AddResult(Builder.TakeString());
5528       continue;
5529     }
5530 
5531     std::string Accumulator;
5532     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
5533       if (I == NumSelIdents) {
5534         if (!Accumulator.empty()) {
5535           Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
5536                                                  Accumulator));
5537           Accumulator.clear();
5538         }
5539       }
5540 
5541       Accumulator += Sel.getNameForSlot(I);
5542       Accumulator += ':';
5543     }
5544     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
5545     Results.AddResult(Builder.TakeString());
5546   }
5547   Results.ExitScope();
5548 
5549   HandleCodeCompleteResults(this, CodeCompleter,
5550                             CodeCompletionContext::CCC_SelectorName,
5551                             Results.data(), Results.size());
5552 }
5553 
5554 /// \brief Add all of the protocol declarations that we find in the given
5555 /// (translation unit) context.
5556 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
5557                                bool OnlyForwardDeclarations,
5558                                ResultBuilder &Results) {
5559   typedef CodeCompletionResult Result;
5560 
5561   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5562                                DEnd = Ctx->decls_end();
5563        D != DEnd; ++D) {
5564     // Record any protocols we find.
5565     if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
5566       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
5567         Results.AddResult(Result(Proto, 0), CurContext, 0, false);
5568   }
5569 }
5570 
5571 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5572                                               unsigned NumProtocols) {
5573   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5574                         CodeCompletionContext::CCC_ObjCProtocolName);
5575 
5576   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5577     Results.EnterNewScope();
5578 
5579     // Tell the result set to ignore all of the protocols we have
5580     // already seen.
5581     // FIXME: This doesn't work when caching code-completion results.
5582     for (unsigned I = 0; I != NumProtocols; ++I)
5583       if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5584                                                       Protocols[I].second))
5585         Results.Ignore(Protocol);
5586 
5587     // Add all protocols.
5588     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5589                        Results);
5590 
5591     Results.ExitScope();
5592   }
5593 
5594   HandleCodeCompleteResults(this, CodeCompleter,
5595                             CodeCompletionContext::CCC_ObjCProtocolName,
5596                             Results.data(),Results.size());
5597 }
5598 
5599 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
5600   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5601                         CodeCompletionContext::CCC_ObjCProtocolName);
5602 
5603   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5604     Results.EnterNewScope();
5605 
5606     // Add all protocols.
5607     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5608                        Results);
5609 
5610     Results.ExitScope();
5611   }
5612 
5613   HandleCodeCompleteResults(this, CodeCompleter,
5614                             CodeCompletionContext::CCC_ObjCProtocolName,
5615                             Results.data(),Results.size());
5616 }
5617 
5618 /// \brief Add all of the Objective-C interface declarations that we find in
5619 /// the given (translation unit) context.
5620 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5621                                 bool OnlyForwardDeclarations,
5622                                 bool OnlyUnimplemented,
5623                                 ResultBuilder &Results) {
5624   typedef CodeCompletionResult Result;
5625 
5626   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5627                                DEnd = Ctx->decls_end();
5628        D != DEnd; ++D) {
5629     // Record any interfaces we find.
5630     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5631       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
5632           (!OnlyUnimplemented || !Class->getImplementation()))
5633         Results.AddResult(Result(Class, 0), CurContext, 0, false);
5634   }
5635 }
5636 
5637 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5638   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5639                         CodeCompletionContext::CCC_Other);
5640   Results.EnterNewScope();
5641 
5642   if (CodeCompleter->includeGlobals()) {
5643     // Add all classes.
5644     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5645                         false, Results);
5646   }
5647 
5648   Results.ExitScope();
5649 
5650   HandleCodeCompleteResults(this, CodeCompleter,
5651                             CodeCompletionContext::CCC_ObjCInterfaceName,
5652                             Results.data(),Results.size());
5653 }
5654 
5655 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5656                                       SourceLocation ClassNameLoc) {
5657   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5658                         CodeCompletionContext::CCC_ObjCInterfaceName);
5659   Results.EnterNewScope();
5660 
5661   // Make sure that we ignore the class we're currently defining.
5662   NamedDecl *CurClass
5663     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5664   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
5665     Results.Ignore(CurClass);
5666 
5667   if (CodeCompleter->includeGlobals()) {
5668     // Add all classes.
5669     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5670                         false, Results);
5671   }
5672 
5673   Results.ExitScope();
5674 
5675   HandleCodeCompleteResults(this, CodeCompleter,
5676                             CodeCompletionContext::CCC_ObjCInterfaceName,
5677                             Results.data(),Results.size());
5678 }
5679 
5680 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
5681   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5682                         CodeCompletionContext::CCC_Other);
5683   Results.EnterNewScope();
5684 
5685   if (CodeCompleter->includeGlobals()) {
5686     // Add all unimplemented classes.
5687     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5688                         true, Results);
5689   }
5690 
5691   Results.ExitScope();
5692 
5693   HandleCodeCompleteResults(this, CodeCompleter,
5694                             CodeCompletionContext::CCC_ObjCInterfaceName,
5695                             Results.data(),Results.size());
5696 }
5697 
5698 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
5699                                              IdentifierInfo *ClassName,
5700                                              SourceLocation ClassNameLoc) {
5701   typedef CodeCompletionResult Result;
5702 
5703   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5704                         CodeCompletionContext::CCC_ObjCCategoryName);
5705 
5706   // Ignore any categories we find that have already been implemented by this
5707   // interface.
5708   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5709   NamedDecl *CurClass
5710     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5711   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5712     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5713          Category = Category->getNextClassCategory())
5714       CategoryNames.insert(Category->getIdentifier());
5715 
5716   // Add all of the categories we know about.
5717   Results.EnterNewScope();
5718   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5719   for (DeclContext::decl_iterator D = TU->decls_begin(),
5720                                DEnd = TU->decls_end();
5721        D != DEnd; ++D)
5722     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5723       if (CategoryNames.insert(Category->getIdentifier()))
5724         Results.AddResult(Result(Category, 0), CurContext, 0, false);
5725   Results.ExitScope();
5726 
5727   HandleCodeCompleteResults(this, CodeCompleter,
5728                             CodeCompletionContext::CCC_ObjCCategoryName,
5729                             Results.data(),Results.size());
5730 }
5731 
5732 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
5733                                                   IdentifierInfo *ClassName,
5734                                                   SourceLocation ClassNameLoc) {
5735   typedef CodeCompletionResult Result;
5736 
5737   // Find the corresponding interface. If we couldn't find the interface, the
5738   // program itself is ill-formed. However, we'll try to be helpful still by
5739   // providing the list of all of the categories we know about.
5740   NamedDecl *CurClass
5741     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5742   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5743   if (!Class)
5744     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
5745 
5746   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5747                         CodeCompletionContext::CCC_ObjCCategoryName);
5748 
5749   // Add all of the categories that have have corresponding interface
5750   // declarations in this class and any of its superclasses, except for
5751   // already-implemented categories in the class itself.
5752   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5753   Results.EnterNewScope();
5754   bool IgnoreImplemented = true;
5755   while (Class) {
5756     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5757          Category = Category->getNextClassCategory())
5758       if ((!IgnoreImplemented || !Category->getImplementation()) &&
5759           CategoryNames.insert(Category->getIdentifier()))
5760         Results.AddResult(Result(Category, 0), CurContext, 0, false);
5761 
5762     Class = Class->getSuperClass();
5763     IgnoreImplemented = false;
5764   }
5765   Results.ExitScope();
5766 
5767   HandleCodeCompleteResults(this, CodeCompleter,
5768                             CodeCompletionContext::CCC_ObjCCategoryName,
5769                             Results.data(),Results.size());
5770 }
5771 
5772 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
5773   typedef CodeCompletionResult Result;
5774   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5775                         CodeCompletionContext::CCC_Other);
5776 
5777   // Figure out where this @synthesize lives.
5778   ObjCContainerDecl *Container
5779     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
5780   if (!Container ||
5781       (!isa<ObjCImplementationDecl>(Container) &&
5782        !isa<ObjCCategoryImplDecl>(Container)))
5783     return;
5784 
5785   // Ignore any properties that have already been implemented.
5786   for (DeclContext::decl_iterator D = Container->decls_begin(),
5787                                DEnd = Container->decls_end();
5788        D != DEnd; ++D)
5789     if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5790       Results.Ignore(PropertyImpl->getPropertyDecl());
5791 
5792   // Add any properties that we find.
5793   AddedPropertiesSet AddedProperties;
5794   Results.EnterNewScope();
5795   if (ObjCImplementationDecl *ClassImpl
5796         = dyn_cast<ObjCImplementationDecl>(Container))
5797     AddObjCProperties(ClassImpl->getClassInterface(), false,
5798                       /*AllowNullaryMethods=*/false, CurContext,
5799                       AddedProperties, Results);
5800   else
5801     AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
5802                       false, /*AllowNullaryMethods=*/false, CurContext,
5803                       AddedProperties, Results);
5804   Results.ExitScope();
5805 
5806   HandleCodeCompleteResults(this, CodeCompleter,
5807                             CodeCompletionContext::CCC_Other,
5808                             Results.data(),Results.size());
5809 }
5810 
5811 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5812                                                   IdentifierInfo *PropertyName) {
5813   typedef CodeCompletionResult Result;
5814   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5815                         CodeCompletionContext::CCC_Other);
5816 
5817   // Figure out where this @synthesize lives.
5818   ObjCContainerDecl *Container
5819     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
5820   if (!Container ||
5821       (!isa<ObjCImplementationDecl>(Container) &&
5822        !isa<ObjCCategoryImplDecl>(Container)))
5823     return;
5824 
5825   // Figure out which interface we're looking into.
5826   ObjCInterfaceDecl *Class = 0;
5827   if (ObjCImplementationDecl *ClassImpl
5828                                  = dyn_cast<ObjCImplementationDecl>(Container))
5829     Class = ClassImpl->getClassInterface();
5830   else
5831     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5832                                                           ->getClassInterface();
5833 
5834   // Determine the type of the property we're synthesizing.
5835   QualType PropertyType = Context.getObjCIdType();
5836   if (Class) {
5837     if (ObjCPropertyDecl *Property
5838                               = Class->FindPropertyDeclaration(PropertyName)) {
5839       PropertyType
5840         = Property->getType().getNonReferenceType().getUnqualifiedType();
5841 
5842       // Give preference to ivars
5843       Results.setPreferredType(PropertyType);
5844     }
5845   }
5846 
5847   // Add all of the instance variables in this class and its superclasses.
5848   Results.EnterNewScope();
5849   bool SawSimilarlyNamedIvar = false;
5850   std::string NameWithPrefix;
5851   NameWithPrefix += '_';
5852   NameWithPrefix += PropertyName->getName();
5853   std::string NameWithSuffix = PropertyName->getName().str();
5854   NameWithSuffix += '_';
5855   for(; Class; Class = Class->getSuperClass()) {
5856     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5857          Ivar = Ivar->getNextIvar()) {
5858       Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5859 
5860       // Determine whether we've seen an ivar with a name similar to the
5861       // property.
5862       if ((PropertyName == Ivar->getIdentifier() ||
5863            NameWithPrefix == Ivar->getName() ||
5864            NameWithSuffix == Ivar->getName())) {
5865         SawSimilarlyNamedIvar = true;
5866 
5867         // Reduce the priority of this result by one, to give it a slight
5868         // advantage over other results whose names don't match so closely.
5869         if (Results.size() &&
5870             Results.data()[Results.size() - 1].Kind
5871                                       == CodeCompletionResult::RK_Declaration &&
5872             Results.data()[Results.size() - 1].Declaration == Ivar)
5873           Results.data()[Results.size() - 1].Priority--;
5874       }
5875     }
5876   }
5877 
5878   if (!SawSimilarlyNamedIvar) {
5879     // Create ivar result _propName, that the user can use to synthesize
5880     // an ivar of the appropriate type.
5881     unsigned Priority = CCP_MemberDeclaration + 1;
5882     typedef CodeCompletionResult Result;
5883     CodeCompletionAllocator &Allocator = Results.getAllocator();
5884     CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5885 
5886     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
5887     Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5888                                                        Policy, Allocator));
5889     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5890     Results.AddResult(Result(Builder.TakeString(), Priority,
5891                              CXCursor_ObjCIvarDecl));
5892   }
5893 
5894   Results.ExitScope();
5895 
5896   HandleCodeCompleteResults(this, CodeCompleter,
5897                             CodeCompletionContext::CCC_Other,
5898                             Results.data(),Results.size());
5899 }
5900 
5901 // Mapping from selectors to the methods that implement that selector, along
5902 // with the "in original class" flag.
5903 typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5904   KnownMethodsMap;
5905 
5906 /// \brief Find all of the methods that reside in the given container
5907 /// (and its superclasses, protocols, etc.) that meet the given
5908 /// criteria. Insert those methods into the map of known methods,
5909 /// indexed by selector so they can be easily found.
5910 static void FindImplementableMethods(ASTContext &Context,
5911                                      ObjCContainerDecl *Container,
5912                                      bool WantInstanceMethods,
5913                                      QualType ReturnType,
5914                                      KnownMethodsMap &KnownMethods,
5915                                      bool InOriginalClass = true) {
5916   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5917     // Recurse into protocols.
5918     if (!IFace->hasDefinition())
5919       return;
5920 
5921     const ObjCList<ObjCProtocolDecl> &Protocols
5922       = IFace->getReferencedProtocols();
5923     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5924                                               E = Protocols.end();
5925          I != E; ++I)
5926       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5927                                KnownMethods, InOriginalClass);
5928 
5929     // Add methods from any class extensions and categories.
5930     for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5931          Cat = Cat->getNextClassCategory())
5932       FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5933                                WantInstanceMethods, ReturnType,
5934                                KnownMethods, false);
5935 
5936     // Visit the superclass.
5937     if (IFace->getSuperClass())
5938       FindImplementableMethods(Context, IFace->getSuperClass(),
5939                                WantInstanceMethods, ReturnType,
5940                                KnownMethods, false);
5941   }
5942 
5943   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5944     // Recurse into protocols.
5945     const ObjCList<ObjCProtocolDecl> &Protocols
5946       = Category->getReferencedProtocols();
5947     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5948                                               E = Protocols.end();
5949          I != E; ++I)
5950       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5951                                KnownMethods, InOriginalClass);
5952 
5953     // If this category is the original class, jump to the interface.
5954     if (InOriginalClass && Category->getClassInterface())
5955       FindImplementableMethods(Context, Category->getClassInterface(),
5956                                WantInstanceMethods, ReturnType, KnownMethods,
5957                                false);
5958   }
5959 
5960   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5961     if (Protocol->hasDefinition()) {
5962       // Recurse into protocols.
5963       const ObjCList<ObjCProtocolDecl> &Protocols
5964         = Protocol->getReferencedProtocols();
5965       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5966              E = Protocols.end();
5967            I != E; ++I)
5968         FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5969                                  KnownMethods, false);
5970     }
5971   }
5972 
5973   // Add methods in this container. This operation occurs last because
5974   // we want the methods from this container to override any methods
5975   // we've previously seen with the same selector.
5976   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5977                                        MEnd = Container->meth_end();
5978        M != MEnd; ++M) {
5979     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5980       if (!ReturnType.isNull() &&
5981           !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5982         continue;
5983 
5984       KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
5985     }
5986   }
5987 }
5988 
5989 /// \brief Add the parenthesized return or parameter type chunk to a code
5990 /// completion string.
5991 static void AddObjCPassingTypeChunk(QualType Type,
5992                                     ASTContext &Context,
5993                                     const PrintingPolicy &Policy,
5994                                     CodeCompletionBuilder &Builder) {
5995   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5996   Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
5997                                                Builder.getAllocator()));
5998   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5999 }
6000 
6001 /// \brief Determine whether the given class is or inherits from a class by
6002 /// the given name.
6003 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6004                                    StringRef Name) {
6005   if (!Class)
6006     return false;
6007 
6008   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6009     return true;
6010 
6011   return InheritsFromClassNamed(Class->getSuperClass(), Name);
6012 }
6013 
6014 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6015 /// Key-Value Observing (KVO).
6016 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6017                                        bool IsInstanceMethod,
6018                                        QualType ReturnType,
6019                                        ASTContext &Context,
6020                                        VisitedSelectorSet &KnownSelectors,
6021                                        ResultBuilder &Results) {
6022   IdentifierInfo *PropName = Property->getIdentifier();
6023   if (!PropName || PropName->getLength() == 0)
6024     return;
6025 
6026   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6027 
6028   // Builder that will create each code completion.
6029   typedef CodeCompletionResult Result;
6030   CodeCompletionAllocator &Allocator = Results.getAllocator();
6031   CodeCompletionBuilder Builder(Allocator);
6032 
6033   // The selector table.
6034   SelectorTable &Selectors = Context.Selectors;
6035 
6036   // The property name, copied into the code completion allocation region
6037   // on demand.
6038   struct KeyHolder {
6039     CodeCompletionAllocator &Allocator;
6040     StringRef Key;
6041     const char *CopiedKey;
6042 
6043     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6044     : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6045 
6046     operator const char *() {
6047       if (CopiedKey)
6048         return CopiedKey;
6049 
6050       return CopiedKey = Allocator.CopyString(Key);
6051     }
6052   } Key(Allocator, PropName->getName());
6053 
6054   // The uppercased name of the property name.
6055   std::string UpperKey = PropName->getName();
6056   if (!UpperKey.empty())
6057     UpperKey[0] = toupper(UpperKey[0]);
6058 
6059   bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6060     Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6061                                    Property->getType());
6062   bool ReturnTypeMatchesVoid
6063     = ReturnType.isNull() || ReturnType->isVoidType();
6064 
6065   // Add the normal accessor -(type)key.
6066   if (IsInstanceMethod &&
6067       KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
6068       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6069     if (ReturnType.isNull())
6070       AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
6071 
6072     Builder.AddTypedTextChunk(Key);
6073     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6074                              CXCursor_ObjCInstanceMethodDecl));
6075   }
6076 
6077   // If we have an integral or boolean property (or the user has provided
6078   // an integral or boolean return type), add the accessor -(type)isKey.
6079   if (IsInstanceMethod &&
6080       ((!ReturnType.isNull() &&
6081         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6082        (ReturnType.isNull() &&
6083         (Property->getType()->isIntegerType() ||
6084          Property->getType()->isBooleanType())))) {
6085     std::string SelectorName = (Twine("is") + UpperKey).str();
6086     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6087     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6088       if (ReturnType.isNull()) {
6089         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6090         Builder.AddTextChunk("BOOL");
6091         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6092       }
6093 
6094       Builder.AddTypedTextChunk(
6095                                 Allocator.CopyString(SelectorId->getName()));
6096       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6097                                CXCursor_ObjCInstanceMethodDecl));
6098     }
6099   }
6100 
6101   // Add the normal mutator.
6102   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6103       !Property->getSetterMethodDecl()) {
6104     std::string SelectorName = (Twine("set") + UpperKey).str();
6105     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6106     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6107       if (ReturnType.isNull()) {
6108         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6109         Builder.AddTextChunk("void");
6110         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6111       }
6112 
6113       Builder.AddTypedTextChunk(
6114                                 Allocator.CopyString(SelectorId->getName()));
6115       Builder.AddTypedTextChunk(":");
6116       AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
6117       Builder.AddTextChunk(Key);
6118       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6119                                CXCursor_ObjCInstanceMethodDecl));
6120     }
6121   }
6122 
6123   // Indexed and unordered accessors
6124   unsigned IndexedGetterPriority = CCP_CodePattern;
6125   unsigned IndexedSetterPriority = CCP_CodePattern;
6126   unsigned UnorderedGetterPriority = CCP_CodePattern;
6127   unsigned UnorderedSetterPriority = CCP_CodePattern;
6128   if (const ObjCObjectPointerType *ObjCPointer
6129                     = Property->getType()->getAs<ObjCObjectPointerType>()) {
6130     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6131       // If this interface type is not provably derived from a known
6132       // collection, penalize the corresponding completions.
6133       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6134         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6135         if (!InheritsFromClassNamed(IFace, "NSArray"))
6136           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6137       }
6138 
6139       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6140         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6141         if (!InheritsFromClassNamed(IFace, "NSSet"))
6142           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6143       }
6144     }
6145   } else {
6146     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6147     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6148     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6149     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6150   }
6151 
6152   // Add -(NSUInteger)countOf<key>
6153   if (IsInstanceMethod &&
6154       (ReturnType.isNull() || ReturnType->isIntegerType())) {
6155     std::string SelectorName = (Twine("countOf") + UpperKey).str();
6156     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6157     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6158       if (ReturnType.isNull()) {
6159         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6160         Builder.AddTextChunk("NSUInteger");
6161         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6162       }
6163 
6164       Builder.AddTypedTextChunk(
6165                                 Allocator.CopyString(SelectorId->getName()));
6166       Results.AddResult(Result(Builder.TakeString(),
6167                                std::min(IndexedGetterPriority,
6168                                         UnorderedGetterPriority),
6169                                CXCursor_ObjCInstanceMethodDecl));
6170     }
6171   }
6172 
6173   // Indexed getters
6174   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6175   if (IsInstanceMethod &&
6176       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6177     std::string SelectorName
6178       = (Twine("objectIn") + UpperKey + "AtIndex").str();
6179     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6180     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6181       if (ReturnType.isNull()) {
6182         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6183         Builder.AddTextChunk("id");
6184         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6185       }
6186 
6187       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6188       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6189       Builder.AddTextChunk("NSUInteger");
6190       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6191       Builder.AddTextChunk("index");
6192       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6193                                CXCursor_ObjCInstanceMethodDecl));
6194     }
6195   }
6196 
6197   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6198   if (IsInstanceMethod &&
6199       (ReturnType.isNull() ||
6200        (ReturnType->isObjCObjectPointerType() &&
6201         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6202         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6203                                                 ->getName() == "NSArray"))) {
6204     std::string SelectorName
6205       = (Twine(Property->getName()) + "AtIndexes").str();
6206     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6207     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6208       if (ReturnType.isNull()) {
6209         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6210         Builder.AddTextChunk("NSArray *");
6211         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6212       }
6213 
6214       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6215       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6216       Builder.AddTextChunk("NSIndexSet *");
6217       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6218       Builder.AddTextChunk("indexes");
6219       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6220                                CXCursor_ObjCInstanceMethodDecl));
6221     }
6222   }
6223 
6224   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6225   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6226     std::string SelectorName = (Twine("get") + UpperKey).str();
6227     IdentifierInfo *SelectorIds[2] = {
6228       &Context.Idents.get(SelectorName),
6229       &Context.Idents.get("range")
6230     };
6231 
6232     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6233       if (ReturnType.isNull()) {
6234         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6235         Builder.AddTextChunk("void");
6236         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6237       }
6238 
6239       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6240       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6241       Builder.AddPlaceholderChunk("object-type");
6242       Builder.AddTextChunk(" **");
6243       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6244       Builder.AddTextChunk("buffer");
6245       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6246       Builder.AddTypedTextChunk("range:");
6247       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6248       Builder.AddTextChunk("NSRange");
6249       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6250       Builder.AddTextChunk("inRange");
6251       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6252                                CXCursor_ObjCInstanceMethodDecl));
6253     }
6254   }
6255 
6256   // Mutable indexed accessors
6257 
6258   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6259   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6260     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6261     IdentifierInfo *SelectorIds[2] = {
6262       &Context.Idents.get("insertObject"),
6263       &Context.Idents.get(SelectorName)
6264     };
6265 
6266     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6267       if (ReturnType.isNull()) {
6268         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6269         Builder.AddTextChunk("void");
6270         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6271       }
6272 
6273       Builder.AddTypedTextChunk("insertObject:");
6274       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6275       Builder.AddPlaceholderChunk("object-type");
6276       Builder.AddTextChunk(" *");
6277       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6278       Builder.AddTextChunk("object");
6279       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6280       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6281       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6282       Builder.AddPlaceholderChunk("NSUInteger");
6283       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6284       Builder.AddTextChunk("index");
6285       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6286                                CXCursor_ObjCInstanceMethodDecl));
6287     }
6288   }
6289 
6290   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6291   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6292     std::string SelectorName = (Twine("insert") + UpperKey).str();
6293     IdentifierInfo *SelectorIds[2] = {
6294       &Context.Idents.get(SelectorName),
6295       &Context.Idents.get("atIndexes")
6296     };
6297 
6298     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6299       if (ReturnType.isNull()) {
6300         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6301         Builder.AddTextChunk("void");
6302         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6303       }
6304 
6305       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6306       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6307       Builder.AddTextChunk("NSArray *");
6308       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6309       Builder.AddTextChunk("array");
6310       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6311       Builder.AddTypedTextChunk("atIndexes:");
6312       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6313       Builder.AddPlaceholderChunk("NSIndexSet *");
6314       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6315       Builder.AddTextChunk("indexes");
6316       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6317                                CXCursor_ObjCInstanceMethodDecl));
6318     }
6319   }
6320 
6321   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6322   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6323     std::string SelectorName
6324       = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
6325     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6326     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6327       if (ReturnType.isNull()) {
6328         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6329         Builder.AddTextChunk("void");
6330         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6331       }
6332 
6333       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6334       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6335       Builder.AddTextChunk("NSUInteger");
6336       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6337       Builder.AddTextChunk("index");
6338       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6339                                CXCursor_ObjCInstanceMethodDecl));
6340     }
6341   }
6342 
6343   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6344   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6345     std::string SelectorName
6346       = (Twine("remove") + UpperKey + "AtIndexes").str();
6347     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6348     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6349       if (ReturnType.isNull()) {
6350         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6351         Builder.AddTextChunk("void");
6352         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6353       }
6354 
6355       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6356       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6357       Builder.AddTextChunk("NSIndexSet *");
6358       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6359       Builder.AddTextChunk("indexes");
6360       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6361                                CXCursor_ObjCInstanceMethodDecl));
6362     }
6363   }
6364 
6365   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6366   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6367     std::string SelectorName
6368       = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
6369     IdentifierInfo *SelectorIds[2] = {
6370       &Context.Idents.get(SelectorName),
6371       &Context.Idents.get("withObject")
6372     };
6373 
6374     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6375       if (ReturnType.isNull()) {
6376         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6377         Builder.AddTextChunk("void");
6378         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6379       }
6380 
6381       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6382       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383       Builder.AddPlaceholderChunk("NSUInteger");
6384       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385       Builder.AddTextChunk("index");
6386       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6387       Builder.AddTypedTextChunk("withObject:");
6388       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389       Builder.AddTextChunk("id");
6390       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391       Builder.AddTextChunk("object");
6392       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6393                                CXCursor_ObjCInstanceMethodDecl));
6394     }
6395   }
6396 
6397   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6398   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6399     std::string SelectorName1
6400       = (Twine("replace") + UpperKey + "AtIndexes").str();
6401     std::string SelectorName2 = (Twine("with") + UpperKey).str();
6402     IdentifierInfo *SelectorIds[2] = {
6403       &Context.Idents.get(SelectorName1),
6404       &Context.Idents.get(SelectorName2)
6405     };
6406 
6407     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6408       if (ReturnType.isNull()) {
6409         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6410         Builder.AddTextChunk("void");
6411         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6412       }
6413 
6414       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6415       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6416       Builder.AddPlaceholderChunk("NSIndexSet *");
6417       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6418       Builder.AddTextChunk("indexes");
6419       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6420       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6421       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6422       Builder.AddTextChunk("NSArray *");
6423       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6424       Builder.AddTextChunk("array");
6425       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6426                                CXCursor_ObjCInstanceMethodDecl));
6427     }
6428   }
6429 
6430   // Unordered getters
6431   // - (NSEnumerator *)enumeratorOfKey
6432   if (IsInstanceMethod &&
6433       (ReturnType.isNull() ||
6434        (ReturnType->isObjCObjectPointerType() &&
6435         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6436         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6437           ->getName() == "NSEnumerator"))) {
6438     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
6439     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6440     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6441       if (ReturnType.isNull()) {
6442         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6443         Builder.AddTextChunk("NSEnumerator *");
6444         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6445       }
6446 
6447       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6448       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6449                               CXCursor_ObjCInstanceMethodDecl));
6450     }
6451   }
6452 
6453   // - (type *)memberOfKey:(type *)object
6454   if (IsInstanceMethod &&
6455       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6456     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
6457     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6458     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6459       if (ReturnType.isNull()) {
6460         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6461         Builder.AddPlaceholderChunk("object-type");
6462         Builder.AddTextChunk(" *");
6463         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6464       }
6465 
6466       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6467       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6468       if (ReturnType.isNull()) {
6469         Builder.AddPlaceholderChunk("object-type");
6470         Builder.AddTextChunk(" *");
6471       } else {
6472         Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6473                                                      Policy,
6474                                                      Builder.getAllocator()));
6475       }
6476       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6477       Builder.AddTextChunk("object");
6478       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6479                                CXCursor_ObjCInstanceMethodDecl));
6480     }
6481   }
6482 
6483   // Mutable unordered accessors
6484   // - (void)addKeyObject:(type *)object
6485   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6486     std::string SelectorName
6487       = (Twine("add") + UpperKey + Twine("Object")).str();
6488     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6489     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6490       if (ReturnType.isNull()) {
6491         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6492         Builder.AddTextChunk("void");
6493         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6494       }
6495 
6496       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6497       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6498       Builder.AddPlaceholderChunk("object-type");
6499       Builder.AddTextChunk(" *");
6500       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6501       Builder.AddTextChunk("object");
6502       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6503                                CXCursor_ObjCInstanceMethodDecl));
6504     }
6505   }
6506 
6507   // - (void)addKey:(NSSet *)objects
6508   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6509     std::string SelectorName = (Twine("add") + UpperKey).str();
6510     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6511     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6512       if (ReturnType.isNull()) {
6513         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6514         Builder.AddTextChunk("void");
6515         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6516       }
6517 
6518       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6519       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6520       Builder.AddTextChunk("NSSet *");
6521       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6522       Builder.AddTextChunk("objects");
6523       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6524                                CXCursor_ObjCInstanceMethodDecl));
6525     }
6526   }
6527 
6528   // - (void)removeKeyObject:(type *)object
6529   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6530     std::string SelectorName
6531       = (Twine("remove") + UpperKey + Twine("Object")).str();
6532     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6533     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6534       if (ReturnType.isNull()) {
6535         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6536         Builder.AddTextChunk("void");
6537         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6538       }
6539 
6540       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6541       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6542       Builder.AddPlaceholderChunk("object-type");
6543       Builder.AddTextChunk(" *");
6544       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6545       Builder.AddTextChunk("object");
6546       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6547                                CXCursor_ObjCInstanceMethodDecl));
6548     }
6549   }
6550 
6551   // - (void)removeKey:(NSSet *)objects
6552   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6553     std::string SelectorName = (Twine("remove") + UpperKey).str();
6554     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6555     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6556       if (ReturnType.isNull()) {
6557         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6558         Builder.AddTextChunk("void");
6559         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6560       }
6561 
6562       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6563       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564       Builder.AddTextChunk("NSSet *");
6565       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6566       Builder.AddTextChunk("objects");
6567       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6568                                CXCursor_ObjCInstanceMethodDecl));
6569     }
6570   }
6571 
6572   // - (void)intersectKey:(NSSet *)objects
6573   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6574     std::string SelectorName = (Twine("intersect") + UpperKey).str();
6575     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6576     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6577       if (ReturnType.isNull()) {
6578         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6579         Builder.AddTextChunk("void");
6580         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6581       }
6582 
6583       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6584       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6585       Builder.AddTextChunk("NSSet *");
6586       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6587       Builder.AddTextChunk("objects");
6588       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6589                                CXCursor_ObjCInstanceMethodDecl));
6590     }
6591   }
6592 
6593   // Key-Value Observing
6594   // + (NSSet *)keyPathsForValuesAffectingKey
6595   if (!IsInstanceMethod &&
6596       (ReturnType.isNull() ||
6597        (ReturnType->isObjCObjectPointerType() &&
6598         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6599         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6600                                                     ->getName() == "NSSet"))) {
6601     std::string SelectorName
6602       = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
6603     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6604     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6605       if (ReturnType.isNull()) {
6606         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6607         Builder.AddTextChunk("NSSet *");
6608         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6609       }
6610 
6611       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6612       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6613                               CXCursor_ObjCClassMethodDecl));
6614     }
6615   }
6616 
6617   // + (BOOL)automaticallyNotifiesObserversForKey
6618   if (!IsInstanceMethod &&
6619       (ReturnType.isNull() ||
6620        ReturnType->isIntegerType() ||
6621        ReturnType->isBooleanType())) {
6622     std::string SelectorName
6623       = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
6624     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6625     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6626       if (ReturnType.isNull()) {
6627         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6628         Builder.AddTextChunk("BOOL");
6629         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6630       }
6631 
6632       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6633       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6634                               CXCursor_ObjCClassMethodDecl));
6635     }
6636   }
6637 }
6638 
6639 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6640                                       bool IsInstanceMethod,
6641                                       ParsedType ReturnTy) {
6642   // Determine the return type of the method we're declaring, if
6643   // provided.
6644   QualType ReturnType = GetTypeFromParser(ReturnTy);
6645   Decl *IDecl = 0;
6646   if (CurContext->isObjCContainer()) {
6647       ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6648       IDecl = cast<Decl>(OCD);
6649   }
6650   // Determine where we should start searching for methods.
6651   ObjCContainerDecl *SearchDecl = 0;
6652   bool IsInImplementation = false;
6653   if (Decl *D = IDecl) {
6654     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6655       SearchDecl = Impl->getClassInterface();
6656       IsInImplementation = true;
6657     } else if (ObjCCategoryImplDecl *CatImpl
6658                                          = dyn_cast<ObjCCategoryImplDecl>(D)) {
6659       SearchDecl = CatImpl->getCategoryDecl();
6660       IsInImplementation = true;
6661     } else
6662       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
6663   }
6664 
6665   if (!SearchDecl && S) {
6666     if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
6667       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
6668   }
6669 
6670   if (!SearchDecl) {
6671     HandleCodeCompleteResults(this, CodeCompleter,
6672                               CodeCompletionContext::CCC_Other,
6673                               0, 0);
6674     return;
6675   }
6676 
6677   // Find all of the methods that we could declare/implement here.
6678   KnownMethodsMap KnownMethods;
6679   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
6680                            ReturnType, KnownMethods);
6681 
6682   // Add declarations or definitions for each of the known methods.
6683   typedef CodeCompletionResult Result;
6684   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6685                         CodeCompletionContext::CCC_Other);
6686   Results.EnterNewScope();
6687   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6688   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6689                               MEnd = KnownMethods.end();
6690        M != MEnd; ++M) {
6691     ObjCMethodDecl *Method = M->second.first;
6692     CodeCompletionBuilder Builder(Results.getAllocator());
6693 
6694     // If the result type was not already provided, add it to the
6695     // pattern as (type).
6696     if (ReturnType.isNull())
6697       AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6698                               Builder);
6699 
6700     Selector Sel = Method->getSelector();
6701 
6702     // Add the first part of the selector to the pattern.
6703     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6704                                                        Sel.getNameForSlot(0)));
6705 
6706     // Add parameters to the pattern.
6707     unsigned I = 0;
6708     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6709                                      PEnd = Method->param_end();
6710          P != PEnd; (void)++P, ++I) {
6711       // Add the part of the selector name.
6712       if (I == 0)
6713         Builder.AddTypedTextChunk(":");
6714       else if (I < Sel.getNumArgs()) {
6715         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6716         Builder.AddTypedTextChunk(
6717                 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6718       } else
6719         break;
6720 
6721       // Add the parameter type.
6722       AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6723                               Builder);
6724 
6725       if (IdentifierInfo *Id = (*P)->getIdentifier())
6726         Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
6727     }
6728 
6729     if (Method->isVariadic()) {
6730       if (Method->param_size() > 0)
6731         Builder.AddChunk(CodeCompletionString::CK_Comma);
6732       Builder.AddTextChunk("...");
6733     }
6734 
6735     if (IsInImplementation && Results.includeCodePatterns()) {
6736       // We will be defining the method here, so add a compound statement.
6737       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6738       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6739       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6740       if (!Method->getResultType()->isVoidType()) {
6741         // If the result type is not void, add a return clause.
6742         Builder.AddTextChunk("return");
6743         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6744         Builder.AddPlaceholderChunk("expression");
6745         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6746       } else
6747         Builder.AddPlaceholderChunk("statements");
6748 
6749       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6750       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6751     }
6752 
6753     unsigned Priority = CCP_CodePattern;
6754     if (!M->second.second)
6755       Priority += CCD_InBaseClass;
6756 
6757     Results.AddResult(Result(Builder.TakeString(), Priority,
6758                              Method->isInstanceMethod()
6759                                ? CXCursor_ObjCInstanceMethodDecl
6760                                : CXCursor_ObjCClassMethodDecl));
6761   }
6762 
6763   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6764   // the properties in this class and its categories.
6765   if (Context.getLangOpts().ObjC2) {
6766     SmallVector<ObjCContainerDecl *, 4> Containers;
6767     Containers.push_back(SearchDecl);
6768 
6769     VisitedSelectorSet KnownSelectors;
6770     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6771                                 MEnd = KnownMethods.end();
6772          M != MEnd; ++M)
6773       KnownSelectors.insert(M->first);
6774 
6775 
6776     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6777     if (!IFace)
6778       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6779         IFace = Category->getClassInterface();
6780 
6781     if (IFace) {
6782       for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6783            Category = Category->getNextClassCategory())
6784         Containers.push_back(Category);
6785     }
6786 
6787     for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6788       for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6789                                          PEnd = Containers[I]->prop_end();
6790            P != PEnd; ++P) {
6791         AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
6792                                    KnownSelectors, Results);
6793       }
6794     }
6795   }
6796 
6797   Results.ExitScope();
6798 
6799   HandleCodeCompleteResults(this, CodeCompleter,
6800                             CodeCompletionContext::CCC_Other,
6801                             Results.data(),Results.size());
6802 }
6803 
6804 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6805                                               bool IsInstanceMethod,
6806                                               bool AtParameterName,
6807                                               ParsedType ReturnTy,
6808                                               IdentifierInfo **SelIdents,
6809                                               unsigned NumSelIdents) {
6810   // If we have an external source, load the entire class method
6811   // pool from the AST file.
6812   if (ExternalSource) {
6813     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6814          I != N; ++I) {
6815       Selector Sel = ExternalSource->GetExternalSelector(I);
6816       if (Sel.isNull() || MethodPool.count(Sel))
6817         continue;
6818 
6819       ReadMethodPool(Sel);
6820     }
6821   }
6822 
6823   // Build the set of methods we can see.
6824   typedef CodeCompletionResult Result;
6825   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6826                         CodeCompletionContext::CCC_Other);
6827 
6828   if (ReturnTy)
6829     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
6830 
6831   Results.EnterNewScope();
6832   for (GlobalMethodPool::iterator M = MethodPool.begin(),
6833                                   MEnd = MethodPool.end();
6834        M != MEnd; ++M) {
6835     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6836                                                        &M->second.second;
6837          MethList && MethList->Method;
6838          MethList = MethList->Next) {
6839       if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6840                                   NumSelIdents))
6841         continue;
6842 
6843       if (AtParameterName) {
6844         // Suggest parameter names we've seen before.
6845         if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6846           ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6847           if (Param->getIdentifier()) {
6848             CodeCompletionBuilder Builder(Results.getAllocator());
6849             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6850                                            Param->getIdentifier()->getName()));
6851             Results.AddResult(Builder.TakeString());
6852           }
6853         }
6854 
6855         continue;
6856       }
6857 
6858       Result R(MethList->Method, 0);
6859       R.StartParameter = NumSelIdents;
6860       R.AllParametersAreInformative = false;
6861       R.DeclaringEntity = true;
6862       Results.MaybeAddResult(R, CurContext);
6863     }
6864   }
6865 
6866   Results.ExitScope();
6867   HandleCodeCompleteResults(this, CodeCompleter,
6868                             CodeCompletionContext::CCC_Other,
6869                             Results.data(),Results.size());
6870 }
6871 
6872 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
6873   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6874                         CodeCompletionContext::CCC_PreprocessorDirective);
6875   Results.EnterNewScope();
6876 
6877   // #if <condition>
6878   CodeCompletionBuilder Builder(Results.getAllocator());
6879   Builder.AddTypedTextChunk("if");
6880   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6881   Builder.AddPlaceholderChunk("condition");
6882   Results.AddResult(Builder.TakeString());
6883 
6884   // #ifdef <macro>
6885   Builder.AddTypedTextChunk("ifdef");
6886   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6887   Builder.AddPlaceholderChunk("macro");
6888   Results.AddResult(Builder.TakeString());
6889 
6890   // #ifndef <macro>
6891   Builder.AddTypedTextChunk("ifndef");
6892   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6893   Builder.AddPlaceholderChunk("macro");
6894   Results.AddResult(Builder.TakeString());
6895 
6896   if (InConditional) {
6897     // #elif <condition>
6898     Builder.AddTypedTextChunk("elif");
6899     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6900     Builder.AddPlaceholderChunk("condition");
6901     Results.AddResult(Builder.TakeString());
6902 
6903     // #else
6904     Builder.AddTypedTextChunk("else");
6905     Results.AddResult(Builder.TakeString());
6906 
6907     // #endif
6908     Builder.AddTypedTextChunk("endif");
6909     Results.AddResult(Builder.TakeString());
6910   }
6911 
6912   // #include "header"
6913   Builder.AddTypedTextChunk("include");
6914   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6915   Builder.AddTextChunk("\"");
6916   Builder.AddPlaceholderChunk("header");
6917   Builder.AddTextChunk("\"");
6918   Results.AddResult(Builder.TakeString());
6919 
6920   // #include <header>
6921   Builder.AddTypedTextChunk("include");
6922   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6923   Builder.AddTextChunk("<");
6924   Builder.AddPlaceholderChunk("header");
6925   Builder.AddTextChunk(">");
6926   Results.AddResult(Builder.TakeString());
6927 
6928   // #define <macro>
6929   Builder.AddTypedTextChunk("define");
6930   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6931   Builder.AddPlaceholderChunk("macro");
6932   Results.AddResult(Builder.TakeString());
6933 
6934   // #define <macro>(<args>)
6935   Builder.AddTypedTextChunk("define");
6936   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6937   Builder.AddPlaceholderChunk("macro");
6938   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6939   Builder.AddPlaceholderChunk("args");
6940   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6941   Results.AddResult(Builder.TakeString());
6942 
6943   // #undef <macro>
6944   Builder.AddTypedTextChunk("undef");
6945   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6946   Builder.AddPlaceholderChunk("macro");
6947   Results.AddResult(Builder.TakeString());
6948 
6949   // #line <number>
6950   Builder.AddTypedTextChunk("line");
6951   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6952   Builder.AddPlaceholderChunk("number");
6953   Results.AddResult(Builder.TakeString());
6954 
6955   // #line <number> "filename"
6956   Builder.AddTypedTextChunk("line");
6957   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6958   Builder.AddPlaceholderChunk("number");
6959   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6960   Builder.AddTextChunk("\"");
6961   Builder.AddPlaceholderChunk("filename");
6962   Builder.AddTextChunk("\"");
6963   Results.AddResult(Builder.TakeString());
6964 
6965   // #error <message>
6966   Builder.AddTypedTextChunk("error");
6967   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6968   Builder.AddPlaceholderChunk("message");
6969   Results.AddResult(Builder.TakeString());
6970 
6971   // #pragma <arguments>
6972   Builder.AddTypedTextChunk("pragma");
6973   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6974   Builder.AddPlaceholderChunk("arguments");
6975   Results.AddResult(Builder.TakeString());
6976 
6977   if (getLangOpts().ObjC1) {
6978     // #import "header"
6979     Builder.AddTypedTextChunk("import");
6980     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6981     Builder.AddTextChunk("\"");
6982     Builder.AddPlaceholderChunk("header");
6983     Builder.AddTextChunk("\"");
6984     Results.AddResult(Builder.TakeString());
6985 
6986     // #import <header>
6987     Builder.AddTypedTextChunk("import");
6988     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6989     Builder.AddTextChunk("<");
6990     Builder.AddPlaceholderChunk("header");
6991     Builder.AddTextChunk(">");
6992     Results.AddResult(Builder.TakeString());
6993   }
6994 
6995   // #include_next "header"
6996   Builder.AddTypedTextChunk("include_next");
6997   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6998   Builder.AddTextChunk("\"");
6999   Builder.AddPlaceholderChunk("header");
7000   Builder.AddTextChunk("\"");
7001   Results.AddResult(Builder.TakeString());
7002 
7003   // #include_next <header>
7004   Builder.AddTypedTextChunk("include_next");
7005   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7006   Builder.AddTextChunk("<");
7007   Builder.AddPlaceholderChunk("header");
7008   Builder.AddTextChunk(">");
7009   Results.AddResult(Builder.TakeString());
7010 
7011   // #warning <message>
7012   Builder.AddTypedTextChunk("warning");
7013   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7014   Builder.AddPlaceholderChunk("message");
7015   Results.AddResult(Builder.TakeString());
7016 
7017   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7018   // completions for them. And __include_macros is a Clang-internal extension
7019   // that we don't want to encourage anyone to use.
7020 
7021   // FIXME: we don't support #assert or #unassert, so don't suggest them.
7022   Results.ExitScope();
7023 
7024   HandleCodeCompleteResults(this, CodeCompleter,
7025                             CodeCompletionContext::CCC_PreprocessorDirective,
7026                             Results.data(), Results.size());
7027 }
7028 
7029 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7030   CodeCompleteOrdinaryName(S,
7031                            S->getFnParent()? Sema::PCC_RecoveryInFunction
7032                                            : Sema::PCC_Namespace);
7033 }
7034 
7035 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7036   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7037                         IsDefinition? CodeCompletionContext::CCC_MacroName
7038                                     : CodeCompletionContext::CCC_MacroNameUse);
7039   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7040     // Add just the names of macros, not their arguments.
7041     CodeCompletionBuilder Builder(Results.getAllocator());
7042     Results.EnterNewScope();
7043     for (Preprocessor::macro_iterator M = PP.macro_begin(),
7044                                    MEnd = PP.macro_end();
7045          M != MEnd; ++M) {
7046       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7047                                            M->first->getName()));
7048       Results.AddResult(Builder.TakeString());
7049     }
7050     Results.ExitScope();
7051   } else if (IsDefinition) {
7052     // FIXME: Can we detect when the user just wrote an include guard above?
7053   }
7054 
7055   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7056                             Results.data(), Results.size());
7057 }
7058 
7059 void Sema::CodeCompletePreprocessorExpression() {
7060   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7061                         CodeCompletionContext::CCC_PreprocessorExpression);
7062 
7063   if (!CodeCompleter || CodeCompleter->includeMacros())
7064     AddMacroResults(PP, Results);
7065 
7066     // defined (<macro>)
7067   Results.EnterNewScope();
7068   CodeCompletionBuilder Builder(Results.getAllocator());
7069   Builder.AddTypedTextChunk("defined");
7070   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7071   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7072   Builder.AddPlaceholderChunk("macro");
7073   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7074   Results.AddResult(Builder.TakeString());
7075   Results.ExitScope();
7076 
7077   HandleCodeCompleteResults(this, CodeCompleter,
7078                             CodeCompletionContext::CCC_PreprocessorExpression,
7079                             Results.data(), Results.size());
7080 }
7081 
7082 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7083                                                  IdentifierInfo *Macro,
7084                                                  MacroInfo *MacroInfo,
7085                                                  unsigned Argument) {
7086   // FIXME: In the future, we could provide "overload" results, much like we
7087   // do for function calls.
7088 
7089   // Now just ignore this. There will be another code-completion callback
7090   // for the expanded tokens.
7091 }
7092 
7093 void Sema::CodeCompleteNaturalLanguage() {
7094   HandleCodeCompleteResults(this, CodeCompleter,
7095                             CodeCompletionContext::CCC_NaturalLanguage,
7096                             0, 0);
7097 }
7098 
7099 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7100                  SmallVectorImpl<CodeCompletionResult> &Results) {
7101   ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
7102   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7103     CodeCompletionDeclConsumer Consumer(Builder,
7104                                         Context.getTranslationUnitDecl());
7105     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7106                        Consumer);
7107   }
7108 
7109   if (!CodeCompleter || CodeCompleter->includeMacros())
7110     AddMacroResults(PP, Builder);
7111 
7112   Results.clear();
7113   Results.insert(Results.end(),
7114                  Builder.data(), Builder.data() + Builder.size());
7115 }
7116