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