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