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