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