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