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