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