1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the code-completion semantic actions.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/Sema/Lookup.h"
15 #include "clang/Sema/Overload.h"
16 #include "clang/Sema/CodeCompleteConsumer.h"
17 #include "clang/Sema/ExternalSemaSource.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Twine.h"
29 #include <list>
30 #include <map>
31 #include <vector>
32 
33 using namespace clang;
34 using namespace sema;
35 
36 namespace {
37   /// \brief A container of code-completion results.
38   class ResultBuilder {
39   public:
40     /// \brief The type of a name-lookup filter, which can be provided to the
41     /// name-lookup routines to specify which declarations should be included in
42     /// the result set (when it returns true) and which declarations should be
43     /// filtered out (returns false).
44     typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
45 
46     typedef CodeCompletionResult Result;
47 
48   private:
49     /// \brief The actual results we have found.
50     std::vector<Result> Results;
51 
52     /// \brief A record of all of the declarations we have found and placed
53     /// into the result set, used to ensure that no declaration ever gets into
54     /// the result set twice.
55     llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
56 
57     typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
58 
59     /// \brief An entry in the shadow map, which is optimized to store
60     /// a single (declaration, index) mapping (the common case) but
61     /// can also store a list of (declaration, index) mappings.
62     class ShadowMapEntry {
63       typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
64 
65       /// \brief Contains either the solitary NamedDecl * or a vector
66       /// of (declaration, index) pairs.
67       llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
68 
69       /// \brief When the entry contains a single declaration, this is
70       /// the index associated with that entry.
71       unsigned SingleDeclIndex;
72 
73     public:
74       ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
75 
76       void Add(NamedDecl *ND, unsigned Index) {
77         if (DeclOrVector.isNull()) {
78           // 0 - > 1 elements: just set the single element information.
79           DeclOrVector = ND;
80           SingleDeclIndex = Index;
81           return;
82         }
83 
84         if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
85           // 1 -> 2 elements: create the vector of results and push in the
86           // existing declaration.
87           DeclIndexPairVector *Vec = new DeclIndexPairVector;
88           Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
89           DeclOrVector = Vec;
90         }
91 
92         // Add the new element to the end of the vector.
93         DeclOrVector.get<DeclIndexPairVector*>()->push_back(
94                                                     DeclIndexPair(ND, Index));
95       }
96 
97       void Destroy() {
98         if (DeclIndexPairVector *Vec
99               = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
100           delete Vec;
101           DeclOrVector = ((NamedDecl *)0);
102         }
103       }
104 
105       // Iteration.
106       class iterator;
107       iterator begin() const;
108       iterator end() const;
109     };
110 
111     /// \brief A mapping from declaration names to the declarations that have
112     /// this name within a particular scope and their index within the list of
113     /// results.
114     typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
115 
116     /// \brief The semantic analysis object for which results are being
117     /// produced.
118     Sema &SemaRef;
119 
120     /// \brief If non-NULL, a filter function used to remove any code-completion
121     /// results that are not desirable.
122     LookupFilter Filter;
123 
124     /// \brief Whether we should allow declarations as
125     /// nested-name-specifiers that would otherwise be filtered out.
126     bool AllowNestedNameSpecifiers;
127 
128     /// \brief If set, the type that we would prefer our resulting value
129     /// declarations to have.
130     ///
131     /// Closely matching the preferred type gives a boost to a result's
132     /// priority.
133     CanQualType PreferredType;
134 
135     /// \brief A list of shadow maps, which is used to model name hiding at
136     /// different levels of, e.g., the inheritance hierarchy.
137     std::list<ShadowMap> ShadowMaps;
138 
139     /// \brief If we're potentially referring to a C++ member function, the set
140     /// of qualifiers applied to the object type.
141     Qualifiers ObjectTypeQualifiers;
142 
143     /// \brief Whether the \p ObjectTypeQualifiers field is active.
144     bool HasObjectTypeQualifiers;
145 
146     /// \brief The selector that we prefer.
147     Selector PreferredSelector;
148 
149     void AdjustResultPriorityForPreferredType(Result &R);
150 
151   public:
152     explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
153       : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
154         HasObjectTypeQualifiers(false) { }
155 
156     /// \brief Whether we should include code patterns in the completion
157     /// results.
158     bool includeCodePatterns() const {
159       return SemaRef.CodeCompleter &&
160              SemaRef.CodeCompleter->includeCodePatterns();
161     }
162 
163     /// \brief Set the filter used for code-completion results.
164     void setFilter(LookupFilter Filter) {
165       this->Filter = Filter;
166     }
167 
168     typedef std::vector<Result>::iterator iterator;
169     iterator begin() { return Results.begin(); }
170     iterator end() { return Results.end(); }
171 
172     Result *data() { return Results.empty()? 0 : &Results.front(); }
173     unsigned size() const { return Results.size(); }
174     bool empty() const { return Results.empty(); }
175 
176     /// \brief Specify the preferred type.
177     void setPreferredType(QualType T) {
178       PreferredType = SemaRef.Context.getCanonicalType(T);
179     }
180 
181     /// \brief Set the cv-qualifiers on the object type, for us in filtering
182     /// calls to member functions.
183     ///
184     /// When there are qualifiers in this set, they will be used to filter
185     /// out member functions that aren't available (because there will be a
186     /// cv-qualifier mismatch) or prefer functions with an exact qualifier
187     /// match.
188     void setObjectTypeQualifiers(Qualifiers Quals) {
189       ObjectTypeQualifiers = Quals;
190       HasObjectTypeQualifiers = true;
191     }
192 
193     /// \brief Set the preferred selector.
194     ///
195     /// When an Objective-C method declaration result is added, and that
196     /// method's selector matches this preferred selector, we give that method
197     /// a slight priority boost.
198     void setPreferredSelector(Selector Sel) {
199       PreferredSelector = Sel;
200     }
201 
202     /// \brief Specify whether nested-name-specifiers are allowed.
203     void allowNestedNameSpecifiers(bool Allow = true) {
204       AllowNestedNameSpecifiers = Allow;
205     }
206 
207     /// \brief Determine whether the given declaration is at all interesting
208     /// as a code-completion result.
209     ///
210     /// \param ND the declaration that we are inspecting.
211     ///
212     /// \param AsNestedNameSpecifier will be set true if this declaration is
213     /// only interesting when it is a nested-name-specifier.
214     bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
215 
216     /// \brief Check whether the result is hidden by the Hiding declaration.
217     ///
218     /// \returns true if the result is hidden and cannot be found, false if
219     /// the hidden result could still be found. When false, \p R may be
220     /// modified to describe how the result can be found (e.g., via extra
221     /// qualification).
222     bool CheckHiddenResult(Result &R, DeclContext *CurContext,
223                            NamedDecl *Hiding);
224 
225     /// \brief Add a new result to this result set (if it isn't already in one
226     /// of the shadow maps), or replace an existing result (for, e.g., a
227     /// redeclaration).
228     ///
229     /// \param CurContext the result to add (if it is unique).
230     ///
231     /// \param R the context in which this result will be named.
232     void MaybeAddResult(Result R, DeclContext *CurContext = 0);
233 
234     /// \brief Add a new result to this result set, where we already know
235     /// the hiding declation (if any).
236     ///
237     /// \param R the result to add (if it is unique).
238     ///
239     /// \param CurContext the context in which this result will be named.
240     ///
241     /// \param Hiding the declaration that hides the result.
242     ///
243     /// \param InBaseClass whether the result was found in a base
244     /// class of the searched context.
245     void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
246                    bool InBaseClass);
247 
248     /// \brief Add a new non-declaration result to this result set.
249     void AddResult(Result R);
250 
251     /// \brief Enter into a new scope.
252     void EnterNewScope();
253 
254     /// \brief Exit from the current scope.
255     void ExitScope();
256 
257     /// \brief Ignore this declaration, if it is seen again.
258     void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
259 
260     /// \name Name lookup predicates
261     ///
262     /// These predicates can be passed to the name lookup functions to filter the
263     /// results of name lookup. All of the predicates have the same type, so that
264     ///
265     //@{
266     bool IsOrdinaryName(NamedDecl *ND) const;
267     bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
268     bool IsIntegralConstantValue(NamedDecl *ND) const;
269     bool IsOrdinaryNonValueName(NamedDecl *ND) const;
270     bool IsNestedNameSpecifier(NamedDecl *ND) const;
271     bool IsEnum(NamedDecl *ND) const;
272     bool IsClassOrStruct(NamedDecl *ND) const;
273     bool IsUnion(NamedDecl *ND) const;
274     bool IsNamespace(NamedDecl *ND) const;
275     bool IsNamespaceOrAlias(NamedDecl *ND) const;
276     bool IsType(NamedDecl *ND) const;
277     bool IsMember(NamedDecl *ND) const;
278     bool IsObjCIvar(NamedDecl *ND) const;
279     bool IsObjCMessageReceiver(NamedDecl *ND) const;
280     bool IsObjCCollection(NamedDecl *ND) const;
281     //@}
282   };
283 }
284 
285 class ResultBuilder::ShadowMapEntry::iterator {
286   llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
287   unsigned SingleDeclIndex;
288 
289 public:
290   typedef DeclIndexPair value_type;
291   typedef value_type reference;
292   typedef std::ptrdiff_t difference_type;
293   typedef std::input_iterator_tag iterator_category;
294 
295   class pointer {
296     DeclIndexPair Value;
297 
298   public:
299     pointer(const DeclIndexPair &Value) : Value(Value) { }
300 
301     const DeclIndexPair *operator->() const {
302       return &Value;
303     }
304   };
305 
306   iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
307 
308   iterator(NamedDecl *SingleDecl, unsigned Index)
309     : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
310 
311   iterator(const DeclIndexPair *Iterator)
312     : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
313 
314   iterator &operator++() {
315     if (DeclOrIterator.is<NamedDecl *>()) {
316       DeclOrIterator = (NamedDecl *)0;
317       SingleDeclIndex = 0;
318       return *this;
319     }
320 
321     const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
322     ++I;
323     DeclOrIterator = I;
324     return *this;
325   }
326 
327   iterator operator++(int) {
328     iterator tmp(*this);
329     ++(*this);
330     return tmp;
331   }
332 
333   reference operator*() const {
334     if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
335       return reference(ND, SingleDeclIndex);
336 
337     return *DeclOrIterator.get<const DeclIndexPair*>();
338   }
339 
340   pointer operator->() const {
341     return pointer(**this);
342   }
343 
344   friend bool operator==(const iterator &X, const iterator &Y) {
345     return X.DeclOrIterator.getOpaqueValue()
346                                   == Y.DeclOrIterator.getOpaqueValue() &&
347       X.SingleDeclIndex == Y.SingleDeclIndex;
348   }
349 
350   friend bool operator!=(const iterator &X, const iterator &Y) {
351     return !(X == Y);
352   }
353 };
354 
355 ResultBuilder::ShadowMapEntry::iterator
356 ResultBuilder::ShadowMapEntry::begin() const {
357   if (DeclOrVector.isNull())
358     return iterator();
359 
360   if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
361     return iterator(ND, SingleDeclIndex);
362 
363   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
364 }
365 
366 ResultBuilder::ShadowMapEntry::iterator
367 ResultBuilder::ShadowMapEntry::end() const {
368   if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
369     return iterator();
370 
371   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
372 }
373 
374 /// \brief Compute the qualification required to get from the current context
375 /// (\p CurContext) to the target context (\p TargetContext).
376 ///
377 /// \param Context the AST context in which the qualification will be used.
378 ///
379 /// \param CurContext the context where an entity is being named, which is
380 /// typically based on the current scope.
381 ///
382 /// \param TargetContext the context in which the named entity actually
383 /// resides.
384 ///
385 /// \returns a nested name specifier that refers into the target context, or
386 /// NULL if no qualification is needed.
387 static NestedNameSpecifier *
388 getRequiredQualification(ASTContext &Context,
389                          DeclContext *CurContext,
390                          DeclContext *TargetContext) {
391   llvm::SmallVector<DeclContext *, 4> TargetParents;
392 
393   for (DeclContext *CommonAncestor = TargetContext;
394        CommonAncestor && !CommonAncestor->Encloses(CurContext);
395        CommonAncestor = CommonAncestor->getLookupParent()) {
396     if (CommonAncestor->isTransparentContext() ||
397         CommonAncestor->isFunctionOrMethod())
398       continue;
399 
400     TargetParents.push_back(CommonAncestor);
401   }
402 
403   NestedNameSpecifier *Result = 0;
404   while (!TargetParents.empty()) {
405     DeclContext *Parent = TargetParents.back();
406     TargetParents.pop_back();
407 
408     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
409       if (!Namespace->getIdentifier())
410         continue;
411 
412       Result = NestedNameSpecifier::Create(Context, Result, Namespace);
413     }
414     else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
415       Result = NestedNameSpecifier::Create(Context, Result,
416                                            false,
417                                      Context.getTypeDeclType(TD).getTypePtr());
418   }
419   return Result;
420 }
421 
422 bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
423                                       bool &AsNestedNameSpecifier) const {
424   AsNestedNameSpecifier = false;
425 
426   ND = ND->getUnderlyingDecl();
427   unsigned IDNS = ND->getIdentifierNamespace();
428 
429   // Skip unnamed entities.
430   if (!ND->getDeclName())
431     return false;
432 
433   // Friend declarations and declarations introduced due to friends are never
434   // added as results.
435   if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
436     return false;
437 
438   // Class template (partial) specializations are never added as results.
439   if (isa<ClassTemplateSpecializationDecl>(ND) ||
440       isa<ClassTemplatePartialSpecializationDecl>(ND))
441     return false;
442 
443   // Using declarations themselves are never added as results.
444   if (isa<UsingDecl>(ND))
445     return false;
446 
447   // Some declarations have reserved names that we don't want to ever show.
448   if (const IdentifierInfo *Id = ND->getIdentifier()) {
449     // __va_list_tag is a freak of nature. Find it and skip it.
450     if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
451       return false;
452 
453     // Filter out names reserved for the implementation (C99 7.1.3,
454     // C++ [lib.global.names]) if they come from a system header.
455     //
456     // FIXME: Add predicate for this.
457     if (Id->getLength() >= 2) {
458       const char *Name = Id->getNameStart();
459       if (Name[0] == '_' &&
460           (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
461           (ND->getLocation().isInvalid() ||
462            SemaRef.SourceMgr.isInSystemHeader(
463                           SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
464         return false;
465     }
466   }
467 
468   // C++ constructors are never found by name lookup.
469   if (isa<CXXConstructorDecl>(ND))
470     return false;
471 
472   if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
473       ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
474        Filter != &ResultBuilder::IsNamespace &&
475        Filter != &ResultBuilder::IsNamespaceOrAlias))
476     AsNestedNameSpecifier = true;
477 
478   // Filter out any unwanted results.
479   if (Filter && !(this->*Filter)(ND)) {
480     // Check whether it is interesting as a nested-name-specifier.
481     if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
482         IsNestedNameSpecifier(ND) &&
483         (Filter != &ResultBuilder::IsMember ||
484          (isa<CXXRecordDecl>(ND) &&
485           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
486       AsNestedNameSpecifier = true;
487       return true;
488     }
489 
490     return false;
491   }
492   // ... then it must be interesting!
493   return true;
494 }
495 
496 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
497                                       NamedDecl *Hiding) {
498   // In C, there is no way to refer to a hidden name.
499   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
500   // name if we introduce the tag type.
501   if (!SemaRef.getLangOptions().CPlusPlus)
502     return true;
503 
504   DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
505 
506   // There is no way to qualify a name declared in a function or method.
507   if (HiddenCtx->isFunctionOrMethod())
508     return true;
509 
510   if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
511     return true;
512 
513   // We can refer to the result with the appropriate qualification. Do it.
514   R.Hidden = true;
515   R.QualifierIsInformative = false;
516 
517   if (!R.Qualifier)
518     R.Qualifier = getRequiredQualification(SemaRef.Context,
519                                            CurContext,
520                                            R.Declaration->getDeclContext());
521   return false;
522 }
523 
524 /// \brief A simplified classification of types used to determine whether two
525 /// types are "similar enough" when adjusting priorities.
526 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
527   switch (T->getTypeClass()) {
528   case Type::Builtin:
529     switch (cast<BuiltinType>(T)->getKind()) {
530       case BuiltinType::Void:
531         return STC_Void;
532 
533       case BuiltinType::NullPtr:
534         return STC_Pointer;
535 
536       case BuiltinType::Overload:
537       case BuiltinType::Dependent:
538       case BuiltinType::UndeducedAuto:
539         return STC_Other;
540 
541       case BuiltinType::ObjCId:
542       case BuiltinType::ObjCClass:
543       case BuiltinType::ObjCSel:
544         return STC_ObjectiveC;
545 
546       default:
547         return STC_Arithmetic;
548     }
549     return STC_Other;
550 
551   case Type::Complex:
552     return STC_Arithmetic;
553 
554   case Type::Pointer:
555     return STC_Pointer;
556 
557   case Type::BlockPointer:
558     return STC_Block;
559 
560   case Type::LValueReference:
561   case Type::RValueReference:
562     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
563 
564   case Type::ConstantArray:
565   case Type::IncompleteArray:
566   case Type::VariableArray:
567   case Type::DependentSizedArray:
568     return STC_Array;
569 
570   case Type::DependentSizedExtVector:
571   case Type::Vector:
572   case Type::ExtVector:
573     return STC_Arithmetic;
574 
575   case Type::FunctionProto:
576   case Type::FunctionNoProto:
577     return STC_Function;
578 
579   case Type::Record:
580     return STC_Record;
581 
582   case Type::Enum:
583     return STC_Arithmetic;
584 
585   case Type::ObjCObject:
586   case Type::ObjCInterface:
587   case Type::ObjCObjectPointer:
588     return STC_ObjectiveC;
589 
590   default:
591     return STC_Other;
592   }
593 }
594 
595 /// \brief Get the type that a given expression will have if this declaration
596 /// is used as an expression in its "typical" code-completion form.
597 QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
598   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
599 
600   if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
601     return C.getTypeDeclType(Type);
602   if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
603     return C.getObjCInterfaceType(Iface);
604 
605   QualType T;
606   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
607     T = Function->getCallResultType();
608   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
609     T = Method->getSendResultType();
610   else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
611     T = FunTmpl->getTemplatedDecl()->getCallResultType();
612   else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
613     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
614   else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
615     T = Property->getType();
616   else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
617     T = Value->getType();
618   else
619     return QualType();
620 
621   return T.getNonReferenceType();
622 }
623 
624 void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
625   QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
626   if (T.isNull())
627     return;
628 
629   CanQualType TC = SemaRef.Context.getCanonicalType(T);
630   // Check for exactly-matching types (modulo qualifiers).
631   if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) {
632     if (PreferredType->isVoidType())
633       R.Priority += CCD_VoidMatch;
634     else
635       R.Priority /= CCF_ExactTypeMatch;
636   } // Check for nearly-matching types, based on classification of each.
637   else if ((getSimplifiedTypeClass(PreferredType)
638                                                == getSimplifiedTypeClass(TC)) &&
639            !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
640     R.Priority /= CCF_SimilarTypeMatch;
641 }
642 
643 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
644   assert(!ShadowMaps.empty() && "Must enter into a results scope");
645 
646   if (R.Kind != Result::RK_Declaration) {
647     // For non-declaration results, just add the result.
648     Results.push_back(R);
649     return;
650   }
651 
652   // Look through using declarations.
653   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
654     MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
655     return;
656   }
657 
658   Decl *CanonDecl = R.Declaration->getCanonicalDecl();
659   unsigned IDNS = CanonDecl->getIdentifierNamespace();
660 
661   bool AsNestedNameSpecifier = false;
662   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
663     return;
664 
665   ShadowMap &SMap = ShadowMaps.back();
666   ShadowMapEntry::iterator I, IEnd;
667   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
668   if (NamePos != SMap.end()) {
669     I = NamePos->second.begin();
670     IEnd = NamePos->second.end();
671   }
672 
673   for (; I != IEnd; ++I) {
674     NamedDecl *ND = I->first;
675     unsigned Index = I->second;
676     if (ND->getCanonicalDecl() == CanonDecl) {
677       // This is a redeclaration. Always pick the newer declaration.
678       Results[Index].Declaration = R.Declaration;
679 
680       // We're done.
681       return;
682     }
683   }
684 
685   // This is a new declaration in this scope. However, check whether this
686   // declaration name is hidden by a similarly-named declaration in an outer
687   // scope.
688   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
689   --SMEnd;
690   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
691     ShadowMapEntry::iterator I, IEnd;
692     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
693     if (NamePos != SM->end()) {
694       I = NamePos->second.begin();
695       IEnd = NamePos->second.end();
696     }
697     for (; I != IEnd; ++I) {
698       // A tag declaration does not hide a non-tag declaration.
699       if (I->first->hasTagIdentifierNamespace() &&
700           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
701                    Decl::IDNS_ObjCProtocol)))
702         continue;
703 
704       // Protocols are in distinct namespaces from everything else.
705       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
706            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
707           I->first->getIdentifierNamespace() != IDNS)
708         continue;
709 
710       // The newly-added result is hidden by an entry in the shadow map.
711       if (CheckHiddenResult(R, CurContext, I->first))
712         return;
713 
714       break;
715     }
716   }
717 
718   // Make sure that any given declaration only shows up in the result set once.
719   if (!AllDeclsFound.insert(CanonDecl))
720     return;
721 
722   // If this is an Objective-C method declaration whose selector matches our
723   // preferred selector, give it a priority boost.
724   if (!PreferredSelector.isNull())
725     if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
726       if (PreferredSelector == Method->getSelector())
727         R.Priority += CCD_SelectorMatch;
728 
729   // If the filter is for nested-name-specifiers, then this result starts a
730   // nested-name-specifier.
731   if (AsNestedNameSpecifier) {
732     R.StartsNestedNameSpecifier = true;
733     R.Priority = CCP_NestedNameSpecifier;
734   } else if (!PreferredType.isNull())
735       AdjustResultPriorityForPreferredType(R);
736 
737   // If this result is supposed to have an informative qualifier, add one.
738   if (R.QualifierIsInformative && !R.Qualifier &&
739       !R.StartsNestedNameSpecifier) {
740     DeclContext *Ctx = R.Declaration->getDeclContext();
741     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
742       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
743     else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
744       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
745                              SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
746     else
747       R.QualifierIsInformative = false;
748   }
749 
750   // Insert this result into the set of results and into the current shadow
751   // map.
752   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
753   Results.push_back(R);
754 }
755 
756 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
757                               NamedDecl *Hiding, bool InBaseClass = false) {
758   if (R.Kind != Result::RK_Declaration) {
759     // For non-declaration results, just add the result.
760     Results.push_back(R);
761     return;
762   }
763 
764   // Look through using declarations.
765   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
766     AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
767     return;
768   }
769 
770   bool AsNestedNameSpecifier = false;
771   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
772     return;
773 
774   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
775     return;
776 
777   // Make sure that any given declaration only shows up in the result set once.
778   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
779     return;
780 
781   // If the filter is for nested-name-specifiers, then this result starts a
782   // nested-name-specifier.
783   if (AsNestedNameSpecifier) {
784     R.StartsNestedNameSpecifier = true;
785     R.Priority = CCP_NestedNameSpecifier;
786   }
787   else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
788            isa<CXXRecordDecl>(R.Declaration->getDeclContext()
789                                                   ->getRedeclContext()))
790     R.QualifierIsInformative = true;
791 
792   // If this result is supposed to have an informative qualifier, add one.
793   if (R.QualifierIsInformative && !R.Qualifier &&
794       !R.StartsNestedNameSpecifier) {
795     DeclContext *Ctx = R.Declaration->getDeclContext();
796     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
797       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
798     else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
799       R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
800                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
801     else
802       R.QualifierIsInformative = false;
803   }
804 
805   // Adjust the priority if this result comes from a base class.
806   if (InBaseClass)
807     R.Priority += CCD_InBaseClass;
808 
809   // If this is an Objective-C method declaration whose selector matches our
810   // preferred selector, give it a priority boost.
811   if (!PreferredSelector.isNull())
812     if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
813       if (PreferredSelector == Method->getSelector())
814         R.Priority += CCD_SelectorMatch;
815 
816   if (!PreferredType.isNull())
817     AdjustResultPriorityForPreferredType(R);
818 
819   if (HasObjectTypeQualifiers)
820     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
821       if (Method->isInstance()) {
822         Qualifiers MethodQuals
823                         = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
824         if (ObjectTypeQualifiers == MethodQuals)
825           R.Priority += CCD_ObjectQualifierMatch;
826         else if (ObjectTypeQualifiers - MethodQuals) {
827           // The method cannot be invoked, because doing so would drop
828           // qualifiers.
829           return;
830         }
831       }
832 
833   // Insert this result into the set of results.
834   Results.push_back(R);
835 }
836 
837 void ResultBuilder::AddResult(Result R) {
838   assert(R.Kind != Result::RK_Declaration &&
839           "Declaration results need more context");
840   Results.push_back(R);
841 }
842 
843 /// \brief Enter into a new scope.
844 void ResultBuilder::EnterNewScope() {
845   ShadowMaps.push_back(ShadowMap());
846 }
847 
848 /// \brief Exit from the current scope.
849 void ResultBuilder::ExitScope() {
850   for (ShadowMap::iterator E = ShadowMaps.back().begin(),
851                         EEnd = ShadowMaps.back().end();
852        E != EEnd;
853        ++E)
854     E->second.Destroy();
855 
856   ShadowMaps.pop_back();
857 }
858 
859 /// \brief Determines whether this given declaration will be found by
860 /// ordinary name lookup.
861 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
862   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
863 
864   unsigned IDNS = Decl::IDNS_Ordinary;
865   if (SemaRef.getLangOptions().CPlusPlus)
866     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
867   else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
868     return true;
869 
870   return ND->getIdentifierNamespace() & IDNS;
871 }
872 
873 /// \brief Determines whether this given declaration will be found by
874 /// ordinary name lookup but is not a type name.
875 bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
876   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
877   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
878     return false;
879 
880   unsigned IDNS = Decl::IDNS_Ordinary;
881   if (SemaRef.getLangOptions().CPlusPlus)
882     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
883   else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
884     return true;
885 
886   return ND->getIdentifierNamespace() & IDNS;
887 }
888 
889 bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
890   if (!IsOrdinaryNonTypeName(ND))
891     return 0;
892 
893   if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
894     if (VD->getType()->isIntegralOrEnumerationType())
895       return true;
896 
897   return false;
898 }
899 
900 /// \brief Determines whether this given declaration will be found by
901 /// ordinary name lookup.
902 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
903   ND = cast<NamedDecl>(ND->getUnderlyingDecl());
904 
905   unsigned IDNS = Decl::IDNS_Ordinary;
906   if (SemaRef.getLangOptions().CPlusPlus)
907     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
908 
909   return (ND->getIdentifierNamespace() & IDNS) &&
910     !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
911     !isa<ObjCPropertyDecl>(ND);
912 }
913 
914 /// \brief Determines whether the given declaration is suitable as the
915 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
916 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
917   // Allow us to find class templates, too.
918   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
919     ND = ClassTemplate->getTemplatedDecl();
920 
921   return SemaRef.isAcceptableNestedNameSpecifier(ND);
922 }
923 
924 /// \brief Determines whether the given declaration is an enumeration.
925 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
926   return isa<EnumDecl>(ND);
927 }
928 
929 /// \brief Determines whether the given declaration is a class or struct.
930 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
931   // Allow us to find class templates, too.
932   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
933     ND = ClassTemplate->getTemplatedDecl();
934 
935   if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
936     return RD->getTagKind() == TTK_Class ||
937     RD->getTagKind() == TTK_Struct;
938 
939   return false;
940 }
941 
942 /// \brief Determines whether the given declaration is a union.
943 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
944   // Allow us to find class templates, too.
945   if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
946     ND = ClassTemplate->getTemplatedDecl();
947 
948   if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
949     return RD->getTagKind() == TTK_Union;
950 
951   return false;
952 }
953 
954 /// \brief Determines whether the given declaration is a namespace.
955 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
956   return isa<NamespaceDecl>(ND);
957 }
958 
959 /// \brief Determines whether the given declaration is a namespace or
960 /// namespace alias.
961 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
962   return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
963 }
964 
965 /// \brief Determines whether the given declaration is a type.
966 bool ResultBuilder::IsType(NamedDecl *ND) const {
967   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
968     ND = Using->getTargetDecl();
969 
970   return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
971 }
972 
973 /// \brief Determines which members of a class should be visible via
974 /// "." or "->".  Only value declarations, nested name specifiers, and
975 /// using declarations thereof should show up.
976 bool ResultBuilder::IsMember(NamedDecl *ND) const {
977   if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
978     ND = Using->getTargetDecl();
979 
980   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
981     isa<ObjCPropertyDecl>(ND);
982 }
983 
984 static bool isObjCReceiverType(ASTContext &C, QualType T) {
985   T = C.getCanonicalType(T);
986   switch (T->getTypeClass()) {
987   case Type::ObjCObject:
988   case Type::ObjCInterface:
989   case Type::ObjCObjectPointer:
990     return true;
991 
992   case Type::Builtin:
993     switch (cast<BuiltinType>(T)->getKind()) {
994     case BuiltinType::ObjCId:
995     case BuiltinType::ObjCClass:
996     case BuiltinType::ObjCSel:
997       return true;
998 
999     default:
1000       break;
1001     }
1002     return false;
1003 
1004   default:
1005     break;
1006   }
1007 
1008   if (!C.getLangOptions().CPlusPlus)
1009     return false;
1010 
1011   // FIXME: We could perform more analysis here to determine whether a
1012   // particular class type has any conversions to Objective-C types. For now,
1013   // just accept all class types.
1014   return T->isDependentType() || T->isRecordType();
1015 }
1016 
1017 bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1018   QualType T = getDeclUsageType(SemaRef.Context, ND);
1019   if (T.isNull())
1020     return false;
1021 
1022   T = SemaRef.Context.getBaseElementType(T);
1023   return isObjCReceiverType(SemaRef.Context, T);
1024 }
1025 
1026 bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1027   if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1028       (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1029     return false;
1030 
1031   QualType T = getDeclUsageType(SemaRef.Context, ND);
1032   if (T.isNull())
1033     return false;
1034 
1035   T = SemaRef.Context.getBaseElementType(T);
1036   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1037          T->isObjCIdType() ||
1038          (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1039 }
1040 
1041 /// \rief Determines whether the given declaration is an Objective-C
1042 /// instance variable.
1043 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1044   return isa<ObjCIvarDecl>(ND);
1045 }
1046 
1047 namespace {
1048   /// \brief Visible declaration consumer that adds a code-completion result
1049   /// for each visible declaration.
1050   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1051     ResultBuilder &Results;
1052     DeclContext *CurContext;
1053 
1054   public:
1055     CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1056       : Results(Results), CurContext(CurContext) { }
1057 
1058     virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1059       Results.AddResult(ND, CurContext, Hiding, InBaseClass);
1060     }
1061   };
1062 }
1063 
1064 /// \brief Add type specifiers for the current language as keyword results.
1065 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1066                                     ResultBuilder &Results) {
1067   typedef CodeCompletionResult Result;
1068   Results.AddResult(Result("short", CCP_Type));
1069   Results.AddResult(Result("long", CCP_Type));
1070   Results.AddResult(Result("signed", CCP_Type));
1071   Results.AddResult(Result("unsigned", CCP_Type));
1072   Results.AddResult(Result("void", CCP_Type));
1073   Results.AddResult(Result("char", CCP_Type));
1074   Results.AddResult(Result("int", CCP_Type));
1075   Results.AddResult(Result("float", CCP_Type));
1076   Results.AddResult(Result("double", CCP_Type));
1077   Results.AddResult(Result("enum", CCP_Type));
1078   Results.AddResult(Result("struct", CCP_Type));
1079   Results.AddResult(Result("union", CCP_Type));
1080   Results.AddResult(Result("const", CCP_Type));
1081   Results.AddResult(Result("volatile", CCP_Type));
1082 
1083   if (LangOpts.C99) {
1084     // C99-specific
1085     Results.AddResult(Result("_Complex", CCP_Type));
1086     Results.AddResult(Result("_Imaginary", CCP_Type));
1087     Results.AddResult(Result("_Bool", CCP_Type));
1088     Results.AddResult(Result("restrict", CCP_Type));
1089   }
1090 
1091   if (LangOpts.CPlusPlus) {
1092     // C++-specific
1093     Results.AddResult(Result("bool", CCP_Type));
1094     Results.AddResult(Result("class", CCP_Type));
1095     Results.AddResult(Result("wchar_t", CCP_Type));
1096 
1097     // typename qualified-id
1098     CodeCompletionString *Pattern = new CodeCompletionString;
1099     Pattern->AddTypedTextChunk("typename");
1100     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1101     Pattern->AddPlaceholderChunk("qualifier");
1102     Pattern->AddTextChunk("::");
1103     Pattern->AddPlaceholderChunk("name");
1104     Results.AddResult(Result(Pattern));
1105 
1106     if (LangOpts.CPlusPlus0x) {
1107       Results.AddResult(Result("auto", CCP_Type));
1108       Results.AddResult(Result("char16_t", CCP_Type));
1109       Results.AddResult(Result("char32_t", CCP_Type));
1110 
1111       CodeCompletionString *Pattern = new CodeCompletionString;
1112       Pattern->AddTypedTextChunk("decltype");
1113       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1114       Pattern->AddPlaceholderChunk("expression");
1115       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1116       Results.AddResult(Result(Pattern));
1117     }
1118   }
1119 
1120   // GNU extensions
1121   if (LangOpts.GNUMode) {
1122     // FIXME: Enable when we actually support decimal floating point.
1123     //    Results.AddResult(Result("_Decimal32"));
1124     //    Results.AddResult(Result("_Decimal64"));
1125     //    Results.AddResult(Result("_Decimal128"));
1126 
1127     CodeCompletionString *Pattern = new CodeCompletionString;
1128     Pattern->AddTypedTextChunk("typeof");
1129     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1130     Pattern->AddPlaceholderChunk("expression");
1131     Results.AddResult(Result(Pattern));
1132 
1133     Pattern = new CodeCompletionString;
1134     Pattern->AddTypedTextChunk("typeof");
1135     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1136     Pattern->AddPlaceholderChunk("type");
1137     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1138     Results.AddResult(Result(Pattern));
1139   }
1140 }
1141 
1142 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1143                                  const LangOptions &LangOpts,
1144                                  ResultBuilder &Results) {
1145   typedef CodeCompletionResult Result;
1146   // Note: we don't suggest either "auto" or "register", because both
1147   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1148   // in C++0x as a type specifier.
1149   Results.AddResult(Result("extern"));
1150   Results.AddResult(Result("static"));
1151 }
1152 
1153 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1154                                   const LangOptions &LangOpts,
1155                                   ResultBuilder &Results) {
1156   typedef CodeCompletionResult Result;
1157   switch (CCC) {
1158   case Sema::PCC_Class:
1159   case Sema::PCC_MemberTemplate:
1160     if (LangOpts.CPlusPlus) {
1161       Results.AddResult(Result("explicit"));
1162       Results.AddResult(Result("friend"));
1163       Results.AddResult(Result("mutable"));
1164       Results.AddResult(Result("virtual"));
1165     }
1166     // Fall through
1167 
1168   case Sema::PCC_ObjCInterface:
1169   case Sema::PCC_ObjCImplementation:
1170   case Sema::PCC_Namespace:
1171   case Sema::PCC_Template:
1172     if (LangOpts.CPlusPlus || LangOpts.C99)
1173       Results.AddResult(Result("inline"));
1174     break;
1175 
1176   case Sema::PCC_ObjCInstanceVariableList:
1177   case Sema::PCC_Expression:
1178   case Sema::PCC_Statement:
1179   case Sema::PCC_ForInit:
1180   case Sema::PCC_Condition:
1181   case Sema::PCC_RecoveryInFunction:
1182   case Sema::PCC_Type:
1183     break;
1184   }
1185 }
1186 
1187 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1188 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1189 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1190                                      ResultBuilder &Results,
1191                                      bool NeedAt);
1192 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1193                                          ResultBuilder &Results,
1194                                          bool NeedAt);
1195 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1196                                     ResultBuilder &Results,
1197                                     bool NeedAt);
1198 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1199 
1200 static void AddTypedefResult(ResultBuilder &Results) {
1201   CodeCompletionString *Pattern = new CodeCompletionString;
1202   Pattern->AddTypedTextChunk("typedef");
1203   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1204   Pattern->AddPlaceholderChunk("type");
1205   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1206   Pattern->AddPlaceholderChunk("name");
1207   Results.AddResult(CodeCompletionResult(Pattern));
1208 }
1209 
1210 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1211                                const LangOptions &LangOpts) {
1212   if (LangOpts.CPlusPlus)
1213     return true;
1214 
1215   switch (CCC) {
1216   case Sema::PCC_Namespace:
1217   case Sema::PCC_Class:
1218   case Sema::PCC_ObjCInstanceVariableList:
1219   case Sema::PCC_Template:
1220   case Sema::PCC_MemberTemplate:
1221   case Sema::PCC_Statement:
1222   case Sema::PCC_RecoveryInFunction:
1223   case Sema::PCC_Type:
1224     return true;
1225 
1226   case Sema::PCC_ObjCInterface:
1227   case Sema::PCC_ObjCImplementation:
1228   case Sema::PCC_Expression:
1229   case Sema::PCC_Condition:
1230     return false;
1231 
1232   case Sema::PCC_ForInit:
1233     return LangOpts.ObjC1 || LangOpts.C99;
1234   }
1235 
1236   return false;
1237 }
1238 
1239 /// \brief Add language constructs that show up for "ordinary" names.
1240 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1241                                    Scope *S,
1242                                    Sema &SemaRef,
1243                                    ResultBuilder &Results) {
1244   typedef CodeCompletionResult Result;
1245   switch (CCC) {
1246   case Sema::PCC_Namespace:
1247     if (SemaRef.getLangOptions().CPlusPlus) {
1248       CodeCompletionString *Pattern = 0;
1249 
1250       if (Results.includeCodePatterns()) {
1251         // namespace <identifier> { declarations }
1252         CodeCompletionString *Pattern = new CodeCompletionString;
1253         Pattern->AddTypedTextChunk("namespace");
1254         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1255         Pattern->AddPlaceholderChunk("identifier");
1256         Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1257         Pattern->AddPlaceholderChunk("declarations");
1258         Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1259         Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1260         Results.AddResult(Result(Pattern));
1261       }
1262 
1263       // namespace identifier = identifier ;
1264       Pattern = new CodeCompletionString;
1265       Pattern->AddTypedTextChunk("namespace");
1266       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1267       Pattern->AddPlaceholderChunk("name");
1268       Pattern->AddChunk(CodeCompletionString::CK_Equal);
1269       Pattern->AddPlaceholderChunk("namespace");
1270       Results.AddResult(Result(Pattern));
1271 
1272       // Using directives
1273       Pattern = new CodeCompletionString;
1274       Pattern->AddTypedTextChunk("using");
1275       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1276       Pattern->AddTextChunk("namespace");
1277       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1278       Pattern->AddPlaceholderChunk("identifier");
1279       Results.AddResult(Result(Pattern));
1280 
1281       // asm(string-literal)
1282       Pattern = new CodeCompletionString;
1283       Pattern->AddTypedTextChunk("asm");
1284       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1285       Pattern->AddPlaceholderChunk("string-literal");
1286       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1287       Results.AddResult(Result(Pattern));
1288 
1289       if (Results.includeCodePatterns()) {
1290         // Explicit template instantiation
1291         Pattern = new CodeCompletionString;
1292         Pattern->AddTypedTextChunk("template");
1293         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1294         Pattern->AddPlaceholderChunk("declaration");
1295         Results.AddResult(Result(Pattern));
1296       }
1297     }
1298 
1299     if (SemaRef.getLangOptions().ObjC1)
1300       AddObjCTopLevelResults(Results, true);
1301 
1302     AddTypedefResult(Results);
1303     // Fall through
1304 
1305   case Sema::PCC_Class:
1306     if (SemaRef.getLangOptions().CPlusPlus) {
1307       // Using declaration
1308       CodeCompletionString *Pattern = new CodeCompletionString;
1309       Pattern->AddTypedTextChunk("using");
1310       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1311       Pattern->AddPlaceholderChunk("qualifier");
1312       Pattern->AddTextChunk("::");
1313       Pattern->AddPlaceholderChunk("name");
1314       Results.AddResult(Result(Pattern));
1315 
1316       // using typename qualifier::name (only in a dependent context)
1317       if (SemaRef.CurContext->isDependentContext()) {
1318         Pattern = new CodeCompletionString;
1319         Pattern->AddTypedTextChunk("using");
1320         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1321         Pattern->AddTextChunk("typename");
1322         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1323         Pattern->AddPlaceholderChunk("qualifier");
1324         Pattern->AddTextChunk("::");
1325         Pattern->AddPlaceholderChunk("name");
1326         Results.AddResult(Result(Pattern));
1327       }
1328 
1329       if (CCC == Sema::PCC_Class) {
1330         AddTypedefResult(Results);
1331 
1332         // public:
1333         Pattern = new CodeCompletionString;
1334         Pattern->AddTypedTextChunk("public");
1335         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1336         Results.AddResult(Result(Pattern));
1337 
1338         // protected:
1339         Pattern = new CodeCompletionString;
1340         Pattern->AddTypedTextChunk("protected");
1341         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1342         Results.AddResult(Result(Pattern));
1343 
1344         // private:
1345         Pattern = new CodeCompletionString;
1346         Pattern->AddTypedTextChunk("private");
1347         Pattern->AddChunk(CodeCompletionString::CK_Colon);
1348         Results.AddResult(Result(Pattern));
1349       }
1350     }
1351     // Fall through
1352 
1353   case Sema::PCC_Template:
1354   case Sema::PCC_MemberTemplate:
1355     if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1356       // template < parameters >
1357       CodeCompletionString *Pattern = new CodeCompletionString;
1358       Pattern->AddTypedTextChunk("template");
1359       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1360       Pattern->AddPlaceholderChunk("parameters");
1361       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1362       Results.AddResult(Result(Pattern));
1363     }
1364 
1365     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1366     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1367     break;
1368 
1369   case Sema::PCC_ObjCInterface:
1370     AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1371     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1372     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1373     break;
1374 
1375   case Sema::PCC_ObjCImplementation:
1376     AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1377     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1378     AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1379     break;
1380 
1381   case Sema::PCC_ObjCInstanceVariableList:
1382     AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
1383     break;
1384 
1385   case Sema::PCC_RecoveryInFunction:
1386   case Sema::PCC_Statement: {
1387     AddTypedefResult(Results);
1388 
1389     CodeCompletionString *Pattern = 0;
1390     if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1391       Pattern = new CodeCompletionString;
1392       Pattern->AddTypedTextChunk("try");
1393       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1394       Pattern->AddPlaceholderChunk("statements");
1395       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1396       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1397       Pattern->AddTextChunk("catch");
1398       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1399       Pattern->AddPlaceholderChunk("declaration");
1400       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1401       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1402       Pattern->AddPlaceholderChunk("statements");
1403       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1404       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1405       Results.AddResult(Result(Pattern));
1406     }
1407     if (SemaRef.getLangOptions().ObjC1)
1408       AddObjCStatementResults(Results, true);
1409 
1410     if (Results.includeCodePatterns()) {
1411       // if (condition) { statements }
1412       Pattern = new CodeCompletionString;
1413       Pattern->AddTypedTextChunk("if");
1414       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1415       if (SemaRef.getLangOptions().CPlusPlus)
1416         Pattern->AddPlaceholderChunk("condition");
1417       else
1418         Pattern->AddPlaceholderChunk("expression");
1419       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1420       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1421       Pattern->AddPlaceholderChunk("statements");
1422       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1423       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1424       Results.AddResult(Result(Pattern));
1425 
1426       // switch (condition) { }
1427       Pattern = new CodeCompletionString;
1428       Pattern->AddTypedTextChunk("switch");
1429       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1430       if (SemaRef.getLangOptions().CPlusPlus)
1431         Pattern->AddPlaceholderChunk("condition");
1432       else
1433         Pattern->AddPlaceholderChunk("expression");
1434       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1435       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1436       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1437       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1438       Results.AddResult(Result(Pattern));
1439     }
1440 
1441     // Switch-specific statements.
1442     if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1443       // case expression:
1444       Pattern = new CodeCompletionString;
1445       Pattern->AddTypedTextChunk("case");
1446       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1447       Pattern->AddPlaceholderChunk("expression");
1448       Pattern->AddChunk(CodeCompletionString::CK_Colon);
1449       Results.AddResult(Result(Pattern));
1450 
1451       // default:
1452       Pattern = new CodeCompletionString;
1453       Pattern->AddTypedTextChunk("default");
1454       Pattern->AddChunk(CodeCompletionString::CK_Colon);
1455       Results.AddResult(Result(Pattern));
1456     }
1457 
1458     if (Results.includeCodePatterns()) {
1459       /// while (condition) { statements }
1460       Pattern = new CodeCompletionString;
1461       Pattern->AddTypedTextChunk("while");
1462       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1463       if (SemaRef.getLangOptions().CPlusPlus)
1464         Pattern->AddPlaceholderChunk("condition");
1465       else
1466         Pattern->AddPlaceholderChunk("expression");
1467       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1468       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1469       Pattern->AddPlaceholderChunk("statements");
1470       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1471       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1472       Results.AddResult(Result(Pattern));
1473 
1474       // do { statements } while ( expression );
1475       Pattern = new CodeCompletionString;
1476       Pattern->AddTypedTextChunk("do");
1477       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1478       Pattern->AddPlaceholderChunk("statements");
1479       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1480       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1481       Pattern->AddTextChunk("while");
1482       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1483       Pattern->AddPlaceholderChunk("expression");
1484       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1485       Results.AddResult(Result(Pattern));
1486 
1487       // for ( for-init-statement ; condition ; expression ) { statements }
1488       Pattern = new CodeCompletionString;
1489       Pattern->AddTypedTextChunk("for");
1490       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1491       if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1492         Pattern->AddPlaceholderChunk("init-statement");
1493       else
1494         Pattern->AddPlaceholderChunk("init-expression");
1495       Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1496       Pattern->AddPlaceholderChunk("condition");
1497       Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1498       Pattern->AddPlaceholderChunk("inc-expression");
1499       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1500       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1501       Pattern->AddPlaceholderChunk("statements");
1502       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1503       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1504       Results.AddResult(Result(Pattern));
1505     }
1506 
1507     if (S->getContinueParent()) {
1508       // continue ;
1509       Pattern = new CodeCompletionString;
1510       Pattern->AddTypedTextChunk("continue");
1511       Results.AddResult(Result(Pattern));
1512     }
1513 
1514     if (S->getBreakParent()) {
1515       // break ;
1516       Pattern = new CodeCompletionString;
1517       Pattern->AddTypedTextChunk("break");
1518       Results.AddResult(Result(Pattern));
1519     }
1520 
1521     // "return expression ;" or "return ;", depending on whether we
1522     // know the function is void or not.
1523     bool isVoid = false;
1524     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1525       isVoid = Function->getResultType()->isVoidType();
1526     else if (ObjCMethodDecl *Method
1527                                  = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1528       isVoid = Method->getResultType()->isVoidType();
1529     else if (SemaRef.getCurBlock() &&
1530              !SemaRef.getCurBlock()->ReturnType.isNull())
1531       isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1532     Pattern = new CodeCompletionString;
1533     Pattern->AddTypedTextChunk("return");
1534     if (!isVoid) {
1535       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1536       Pattern->AddPlaceholderChunk("expression");
1537     }
1538     Results.AddResult(Result(Pattern));
1539 
1540     // goto identifier ;
1541     Pattern = new CodeCompletionString;
1542     Pattern->AddTypedTextChunk("goto");
1543     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1544     Pattern->AddPlaceholderChunk("label");
1545     Results.AddResult(Result(Pattern));
1546 
1547     // Using directives
1548     Pattern = new CodeCompletionString;
1549     Pattern->AddTypedTextChunk("using");
1550     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1551     Pattern->AddTextChunk("namespace");
1552     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1553     Pattern->AddPlaceholderChunk("identifier");
1554     Results.AddResult(Result(Pattern));
1555   }
1556 
1557   // Fall through (for statement expressions).
1558   case Sema::PCC_ForInit:
1559   case Sema::PCC_Condition:
1560     AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1561     // Fall through: conditions and statements can have expressions.
1562 
1563   case Sema::PCC_Expression: {
1564     CodeCompletionString *Pattern = 0;
1565     if (SemaRef.getLangOptions().CPlusPlus) {
1566       // 'this', if we're in a non-static member function.
1567       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1568         if (!Method->isStatic())
1569           Results.AddResult(Result("this"));
1570 
1571       // true, false
1572       Results.AddResult(Result("true"));
1573       Results.AddResult(Result("false"));
1574 
1575       // dynamic_cast < type-id > ( expression )
1576       Pattern = new CodeCompletionString;
1577       Pattern->AddTypedTextChunk("dynamic_cast");
1578       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1579       Pattern->AddPlaceholderChunk("type");
1580       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1581       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1582       Pattern->AddPlaceholderChunk("expression");
1583       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1584       Results.AddResult(Result(Pattern));
1585 
1586       // static_cast < type-id > ( expression )
1587       Pattern = new CodeCompletionString;
1588       Pattern->AddTypedTextChunk("static_cast");
1589       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1590       Pattern->AddPlaceholderChunk("type");
1591       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1592       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1593       Pattern->AddPlaceholderChunk("expression");
1594       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1595       Results.AddResult(Result(Pattern));
1596 
1597       // reinterpret_cast < type-id > ( expression )
1598       Pattern = new CodeCompletionString;
1599       Pattern->AddTypedTextChunk("reinterpret_cast");
1600       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1601       Pattern->AddPlaceholderChunk("type");
1602       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1603       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1604       Pattern->AddPlaceholderChunk("expression");
1605       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1606       Results.AddResult(Result(Pattern));
1607 
1608       // const_cast < type-id > ( expression )
1609       Pattern = new CodeCompletionString;
1610       Pattern->AddTypedTextChunk("const_cast");
1611       Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1612       Pattern->AddPlaceholderChunk("type");
1613       Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1614       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1615       Pattern->AddPlaceholderChunk("expression");
1616       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1617       Results.AddResult(Result(Pattern));
1618 
1619       // typeid ( expression-or-type )
1620       Pattern = new CodeCompletionString;
1621       Pattern->AddTypedTextChunk("typeid");
1622       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1623       Pattern->AddPlaceholderChunk("expression-or-type");
1624       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1625       Results.AddResult(Result(Pattern));
1626 
1627       // new T ( ... )
1628       Pattern = new CodeCompletionString;
1629       Pattern->AddTypedTextChunk("new");
1630       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1631       Pattern->AddPlaceholderChunk("type");
1632       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1633       Pattern->AddPlaceholderChunk("expressions");
1634       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1635       Results.AddResult(Result(Pattern));
1636 
1637       // new T [ ] ( ... )
1638       Pattern = new CodeCompletionString;
1639       Pattern->AddTypedTextChunk("new");
1640       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1641       Pattern->AddPlaceholderChunk("type");
1642       Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1643       Pattern->AddPlaceholderChunk("size");
1644       Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1645       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1646       Pattern->AddPlaceholderChunk("expressions");
1647       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1648       Results.AddResult(Result(Pattern));
1649 
1650       // delete expression
1651       Pattern = new CodeCompletionString;
1652       Pattern->AddTypedTextChunk("delete");
1653       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1654       Pattern->AddPlaceholderChunk("expression");
1655       Results.AddResult(Result(Pattern));
1656 
1657       // delete [] expression
1658       Pattern = new CodeCompletionString;
1659       Pattern->AddTypedTextChunk("delete");
1660       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1661       Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1662       Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1663       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1664       Pattern->AddPlaceholderChunk("expression");
1665       Results.AddResult(Result(Pattern));
1666 
1667       // throw expression
1668       Pattern = new CodeCompletionString;
1669       Pattern->AddTypedTextChunk("throw");
1670       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1671       Pattern->AddPlaceholderChunk("expression");
1672       Results.AddResult(Result(Pattern));
1673 
1674       // FIXME: Rethrow?
1675     }
1676 
1677     if (SemaRef.getLangOptions().ObjC1) {
1678       // Add "super", if we're in an Objective-C class with a superclass.
1679       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1680         // The interface can be NULL.
1681         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1682           if (ID->getSuperClass())
1683             Results.AddResult(Result("super"));
1684       }
1685 
1686       AddObjCExpressionResults(Results, true);
1687     }
1688 
1689     // sizeof expression
1690     Pattern = new CodeCompletionString;
1691     Pattern->AddTypedTextChunk("sizeof");
1692     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1693     Pattern->AddPlaceholderChunk("expression-or-type");
1694     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1695     Results.AddResult(Result(Pattern));
1696     break;
1697   }
1698 
1699   case Sema::PCC_Type:
1700     break;
1701   }
1702 
1703   if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1704     AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
1705 
1706   if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
1707     Results.AddResult(Result("operator"));
1708 }
1709 
1710 /// \brief If the given declaration has an associated type, add it as a result
1711 /// type chunk.
1712 static void AddResultTypeChunk(ASTContext &Context,
1713                                NamedDecl *ND,
1714                                CodeCompletionString *Result) {
1715   if (!ND)
1716     return;
1717 
1718   // Determine the type of the declaration (if it has a type).
1719   QualType T;
1720   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1721     T = Function->getResultType();
1722   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1723     T = Method->getResultType();
1724   else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1725     T = FunTmpl->getTemplatedDecl()->getResultType();
1726   else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1727     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1728   else if (isa<UnresolvedUsingValueDecl>(ND)) {
1729     /* Do nothing: ignore unresolved using declarations*/
1730   } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1731     T = Value->getType();
1732   else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1733     T = Property->getType();
1734 
1735   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1736     return;
1737 
1738   PrintingPolicy Policy(Context.PrintingPolicy);
1739   Policy.AnonymousTagLocations = false;
1740 
1741   std::string TypeStr;
1742   T.getAsStringInternal(TypeStr, Policy);
1743   Result->AddResultTypeChunk(TypeStr);
1744 }
1745 
1746 static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1747                              CodeCompletionString *Result) {
1748   if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1749     if (Sentinel->getSentinel() == 0) {
1750       if (Context.getLangOptions().ObjC1 &&
1751           Context.Idents.get("nil").hasMacroDefinition())
1752         Result->AddTextChunk(", nil");
1753       else if (Context.Idents.get("NULL").hasMacroDefinition())
1754         Result->AddTextChunk(", NULL");
1755       else
1756         Result->AddTextChunk(", (void*)0");
1757     }
1758 }
1759 
1760 static std::string FormatFunctionParameter(ASTContext &Context,
1761                                            ParmVarDecl *Param,
1762                                            bool SuppressName = false) {
1763   bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1764   if (Param->getType()->isDependentType() ||
1765       !Param->getType()->isBlockPointerType()) {
1766     // The argument for a dependent or non-block parameter is a placeholder
1767     // containing that parameter's type.
1768     std::string Result;
1769 
1770     if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
1771       Result = Param->getIdentifier()->getName();
1772 
1773     Param->getType().getAsStringInternal(Result,
1774                                          Context.PrintingPolicy);
1775 
1776     if (ObjCMethodParam) {
1777       Result = "(" + Result;
1778       Result += ")";
1779       if (Param->getIdentifier() && !SuppressName)
1780         Result += Param->getIdentifier()->getName();
1781     }
1782     return Result;
1783   }
1784 
1785   // The argument for a block pointer parameter is a block literal with
1786   // the appropriate type.
1787   FunctionProtoTypeLoc *Block = 0;
1788   TypeLoc TL;
1789   if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1790     TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1791     while (true) {
1792       // Look through typedefs.
1793       if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1794         if (TypeSourceInfo *InnerTSInfo
1795             = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1796           TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1797           continue;
1798         }
1799       }
1800 
1801       // Look through qualified types
1802       if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1803         TL = QualifiedTL->getUnqualifiedLoc();
1804         continue;
1805       }
1806 
1807       // Try to get the function prototype behind the block pointer type,
1808       // then we're done.
1809       if (BlockPointerTypeLoc *BlockPtr
1810           = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1811         TL = BlockPtr->getPointeeLoc();
1812         Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1813       }
1814       break;
1815     }
1816   }
1817 
1818   if (!Block) {
1819     // We were unable to find a FunctionProtoTypeLoc with parameter names
1820     // for the block; just use the parameter type as a placeholder.
1821     std::string Result;
1822     Param->getType().getUnqualifiedType().
1823                             getAsStringInternal(Result, Context.PrintingPolicy);
1824 
1825     if (ObjCMethodParam) {
1826       Result = "(" + Result;
1827       Result += ")";
1828       if (Param->getIdentifier())
1829         Result += Param->getIdentifier()->getName();
1830     }
1831 
1832     return Result;
1833   }
1834 
1835   // We have the function prototype behind the block pointer type, as it was
1836   // written in the source.
1837   std::string Result = "(^)(";
1838   for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1839     if (I)
1840       Result += ", ";
1841     Result += FormatFunctionParameter(Context, Block->getArg(I));
1842 
1843     if (I == N - 1 && Block->getTypePtr()->isVariadic())
1844       Result += ", ...";
1845   }
1846   if (Block->getTypePtr()->isVariadic() && Block->getNumArgs() == 0)
1847     Result += "...";
1848   else if (Block->getNumArgs() == 0 && !Context.getLangOptions().CPlusPlus)
1849     Result += "void";
1850 
1851   Result += ")";
1852   Block->getTypePtr()->getResultType().getAsStringInternal(Result,
1853                                                         Context.PrintingPolicy);
1854   return Result;
1855 }
1856 
1857 /// \brief Add function parameter chunks to the given code completion string.
1858 static void AddFunctionParameterChunks(ASTContext &Context,
1859                                        FunctionDecl *Function,
1860                                        CodeCompletionString *Result) {
1861   typedef CodeCompletionString::Chunk Chunk;
1862 
1863   CodeCompletionString *CCStr = Result;
1864 
1865   for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1866     ParmVarDecl *Param = Function->getParamDecl(P);
1867 
1868     if (Param->hasDefaultArg()) {
1869       // When we see an optional default argument, put that argument and
1870       // the remaining default arguments into a new, optional string.
1871       CodeCompletionString *Opt = new CodeCompletionString;
1872       CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1873       CCStr = Opt;
1874     }
1875 
1876     if (P != 0)
1877       CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1878 
1879     // Format the placeholder string.
1880     std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1881 
1882     if (Function->isVariadic() && P == N - 1)
1883       PlaceholderStr += ", ...";
1884 
1885     // Add the placeholder string.
1886     CCStr->AddPlaceholderChunk(PlaceholderStr);
1887   }
1888 
1889   if (const FunctionProtoType *Proto
1890         = Function->getType()->getAs<FunctionProtoType>())
1891     if (Proto->isVariadic()) {
1892       if (Proto->getNumArgs() == 0)
1893         CCStr->AddPlaceholderChunk("...");
1894 
1895       MaybeAddSentinel(Context, Function, CCStr);
1896     }
1897 }
1898 
1899 /// \brief Add template parameter chunks to the given code completion string.
1900 static void AddTemplateParameterChunks(ASTContext &Context,
1901                                        TemplateDecl *Template,
1902                                        CodeCompletionString *Result,
1903                                        unsigned MaxParameters = 0) {
1904   typedef CodeCompletionString::Chunk Chunk;
1905 
1906   CodeCompletionString *CCStr = Result;
1907   bool FirstParameter = true;
1908 
1909   TemplateParameterList *Params = Template->getTemplateParameters();
1910   TemplateParameterList::iterator PEnd = Params->end();
1911   if (MaxParameters)
1912     PEnd = Params->begin() + MaxParameters;
1913   for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1914     bool HasDefaultArg = false;
1915     std::string PlaceholderStr;
1916     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1917       if (TTP->wasDeclaredWithTypename())
1918         PlaceholderStr = "typename";
1919       else
1920         PlaceholderStr = "class";
1921 
1922       if (TTP->getIdentifier()) {
1923         PlaceholderStr += ' ';
1924         PlaceholderStr += TTP->getIdentifier()->getName();
1925       }
1926 
1927       HasDefaultArg = TTP->hasDefaultArgument();
1928     } else if (NonTypeTemplateParmDecl *NTTP
1929                = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1930       if (NTTP->getIdentifier())
1931         PlaceholderStr = NTTP->getIdentifier()->getName();
1932       NTTP->getType().getAsStringInternal(PlaceholderStr,
1933                                           Context.PrintingPolicy);
1934       HasDefaultArg = NTTP->hasDefaultArgument();
1935     } else {
1936       assert(isa<TemplateTemplateParmDecl>(*P));
1937       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1938 
1939       // Since putting the template argument list into the placeholder would
1940       // be very, very long, we just use an abbreviation.
1941       PlaceholderStr = "template<...> class";
1942       if (TTP->getIdentifier()) {
1943         PlaceholderStr += ' ';
1944         PlaceholderStr += TTP->getIdentifier()->getName();
1945       }
1946 
1947       HasDefaultArg = TTP->hasDefaultArgument();
1948     }
1949 
1950     if (HasDefaultArg) {
1951       // When we see an optional default argument, put that argument and
1952       // the remaining default arguments into a new, optional string.
1953       CodeCompletionString *Opt = new CodeCompletionString;
1954       CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1955       CCStr = Opt;
1956     }
1957 
1958     if (FirstParameter)
1959       FirstParameter = false;
1960     else
1961       CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1962 
1963     // Add the placeholder string.
1964     CCStr->AddPlaceholderChunk(PlaceholderStr);
1965   }
1966 }
1967 
1968 /// \brief Add a qualifier to the given code-completion string, if the
1969 /// provided nested-name-specifier is non-NULL.
1970 static void
1971 AddQualifierToCompletionString(CodeCompletionString *Result,
1972                                NestedNameSpecifier *Qualifier,
1973                                bool QualifierIsInformative,
1974                                ASTContext &Context) {
1975   if (!Qualifier)
1976     return;
1977 
1978   std::string PrintedNNS;
1979   {
1980     llvm::raw_string_ostream OS(PrintedNNS);
1981     Qualifier->print(OS, Context.PrintingPolicy);
1982   }
1983   if (QualifierIsInformative)
1984     Result->AddInformativeChunk(PrintedNNS);
1985   else
1986     Result->AddTextChunk(PrintedNNS);
1987 }
1988 
1989 static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1990                                                    FunctionDecl *Function) {
1991   const FunctionProtoType *Proto
1992     = Function->getType()->getAs<FunctionProtoType>();
1993   if (!Proto || !Proto->getTypeQuals())
1994     return;
1995 
1996   std::string QualsStr;
1997   if (Proto->getTypeQuals() & Qualifiers::Const)
1998     QualsStr += " const";
1999   if (Proto->getTypeQuals() & Qualifiers::Volatile)
2000     QualsStr += " volatile";
2001   if (Proto->getTypeQuals() & Qualifiers::Restrict)
2002     QualsStr += " restrict";
2003   Result->AddInformativeChunk(QualsStr);
2004 }
2005 
2006 /// \brief If possible, create a new code completion string for the given
2007 /// result.
2008 ///
2009 /// \returns Either a new, heap-allocated code completion string describing
2010 /// how to use this result, or NULL to indicate that the string or name of the
2011 /// result is all that is needed.
2012 CodeCompletionString *
2013 CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2014                                                CodeCompletionString *Result) {
2015   typedef CodeCompletionString::Chunk Chunk;
2016 
2017   if (Kind == RK_Pattern)
2018     return Pattern->Clone(Result);
2019 
2020   if (!Result)
2021     Result = new CodeCompletionString;
2022 
2023   if (Kind == RK_Keyword) {
2024     Result->AddTypedTextChunk(Keyword);
2025     return Result;
2026   }
2027 
2028   if (Kind == RK_Macro) {
2029     MacroInfo *MI = S.PP.getMacroInfo(Macro);
2030     assert(MI && "Not a macro?");
2031 
2032     Result->AddTypedTextChunk(Macro->getName());
2033 
2034     if (!MI->isFunctionLike())
2035       return Result;
2036 
2037     // Format a function-like macro with placeholders for the arguments.
2038     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2039     for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2040          A != AEnd; ++A) {
2041       if (A != MI->arg_begin())
2042         Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2043 
2044       if (!MI->isVariadic() || A != AEnd - 1) {
2045         // Non-variadic argument.
2046         Result->AddPlaceholderChunk((*A)->getName());
2047         continue;
2048       }
2049 
2050       // Variadic argument; cope with the different between GNU and C99
2051       // variadic macros, providing a single placeholder for the rest of the
2052       // arguments.
2053       if ((*A)->isStr("__VA_ARGS__"))
2054         Result->AddPlaceholderChunk("...");
2055       else {
2056         std::string Arg = (*A)->getName();
2057         Arg += "...";
2058         Result->AddPlaceholderChunk(Arg);
2059       }
2060     }
2061     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2062     return Result;
2063   }
2064 
2065   assert(Kind == RK_Declaration && "Missed a result kind?");
2066   NamedDecl *ND = Declaration;
2067 
2068   if (StartsNestedNameSpecifier) {
2069     Result->AddTypedTextChunk(ND->getNameAsString());
2070     Result->AddTextChunk("::");
2071     return Result;
2072   }
2073 
2074   AddResultTypeChunk(S.Context, ND, Result);
2075 
2076   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2077     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2078                                    S.Context);
2079     Result->AddTypedTextChunk(Function->getNameAsString());
2080     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2081     AddFunctionParameterChunks(S.Context, Function, Result);
2082     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2083     AddFunctionTypeQualsToCompletionString(Result, Function);
2084     return Result;
2085   }
2086 
2087   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2088     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2089                                    S.Context);
2090     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2091     Result->AddTypedTextChunk(Function->getNameAsString());
2092 
2093     // Figure out which template parameters are deduced (or have default
2094     // arguments).
2095     llvm::SmallVector<bool, 16> Deduced;
2096     S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2097     unsigned LastDeducibleArgument;
2098     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2099          --LastDeducibleArgument) {
2100       if (!Deduced[LastDeducibleArgument - 1]) {
2101         // C++0x: Figure out if the template argument has a default. If so,
2102         // the user doesn't need to type this argument.
2103         // FIXME: We need to abstract template parameters better!
2104         bool HasDefaultArg = false;
2105         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2106                                                                       LastDeducibleArgument - 1);
2107         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2108           HasDefaultArg = TTP->hasDefaultArgument();
2109         else if (NonTypeTemplateParmDecl *NTTP
2110                  = dyn_cast<NonTypeTemplateParmDecl>(Param))
2111           HasDefaultArg = NTTP->hasDefaultArgument();
2112         else {
2113           assert(isa<TemplateTemplateParmDecl>(Param));
2114           HasDefaultArg
2115             = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2116         }
2117 
2118         if (!HasDefaultArg)
2119           break;
2120       }
2121     }
2122 
2123     if (LastDeducibleArgument) {
2124       // Some of the function template arguments cannot be deduced from a
2125       // function call, so we introduce an explicit template argument list
2126       // containing all of the arguments up to the first deducible argument.
2127       Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2128       AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2129                                  LastDeducibleArgument);
2130       Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2131     }
2132 
2133     // Add the function parameters
2134     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2135     AddFunctionParameterChunks(S.Context, Function, Result);
2136     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2137     AddFunctionTypeQualsToCompletionString(Result, Function);
2138     return Result;
2139   }
2140 
2141   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2142     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2143                                    S.Context);
2144     Result->AddTypedTextChunk(Template->getNameAsString());
2145     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2146     AddTemplateParameterChunks(S.Context, Template, Result);
2147     Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2148     return Result;
2149   }
2150 
2151   if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2152     Selector Sel = Method->getSelector();
2153     if (Sel.isUnarySelector()) {
2154       Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2155       return Result;
2156     }
2157 
2158     std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2159     SelName += ':';
2160     if (StartParameter == 0)
2161       Result->AddTypedTextChunk(SelName);
2162     else {
2163       Result->AddInformativeChunk(SelName);
2164 
2165       // If there is only one parameter, and we're past it, add an empty
2166       // typed-text chunk since there is nothing to type.
2167       if (Method->param_size() == 1)
2168         Result->AddTypedTextChunk("");
2169     }
2170     unsigned Idx = 0;
2171     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2172                                      PEnd = Method->param_end();
2173          P != PEnd; (void)++P, ++Idx) {
2174       if (Idx > 0) {
2175         std::string Keyword;
2176         if (Idx > StartParameter)
2177           Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2178         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2179           Keyword += II->getName().str();
2180         Keyword += ":";
2181         if (Idx < StartParameter || AllParametersAreInformative)
2182           Result->AddInformativeChunk(Keyword);
2183         else if (Idx == StartParameter)
2184           Result->AddTypedTextChunk(Keyword);
2185         else
2186           Result->AddTextChunk(Keyword);
2187       }
2188 
2189       // If we're before the starting parameter, skip the placeholder.
2190       if (Idx < StartParameter)
2191         continue;
2192 
2193       std::string Arg;
2194 
2195       if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2196         Arg = FormatFunctionParameter(S.Context, *P, true);
2197       else {
2198         (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2199         Arg = "(" + Arg + ")";
2200         if (IdentifierInfo *II = (*P)->getIdentifier())
2201           if (DeclaringEntity || AllParametersAreInformative)
2202             Arg += II->getName().str();
2203       }
2204 
2205       if (Method->isVariadic() && (P + 1) == PEnd)
2206         Arg += ", ...";
2207 
2208       if (DeclaringEntity)
2209         Result->AddTextChunk(Arg);
2210       else if (AllParametersAreInformative)
2211         Result->AddInformativeChunk(Arg);
2212       else
2213         Result->AddPlaceholderChunk(Arg);
2214     }
2215 
2216     if (Method->isVariadic()) {
2217       if (Method->param_size() == 0) {
2218         if (DeclaringEntity)
2219           Result->AddTextChunk(", ...");
2220         else if (AllParametersAreInformative)
2221           Result->AddInformativeChunk(", ...");
2222         else
2223           Result->AddPlaceholderChunk(", ...");
2224       }
2225 
2226       MaybeAddSentinel(S.Context, Method, Result);
2227     }
2228 
2229     return Result;
2230   }
2231 
2232   if (Qualifier)
2233     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2234                                    S.Context);
2235 
2236   Result->AddTypedTextChunk(ND->getNameAsString());
2237   return Result;
2238 }
2239 
2240 CodeCompletionString *
2241 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2242                                                           unsigned CurrentArg,
2243                                                                Sema &S) const {
2244   typedef CodeCompletionString::Chunk Chunk;
2245 
2246   CodeCompletionString *Result = new CodeCompletionString;
2247   FunctionDecl *FDecl = getFunction();
2248   AddResultTypeChunk(S.Context, FDecl, Result);
2249   const FunctionProtoType *Proto
2250     = dyn_cast<FunctionProtoType>(getFunctionType());
2251   if (!FDecl && !Proto) {
2252     // Function without a prototype. Just give the return type and a
2253     // highlighted ellipsis.
2254     const FunctionType *FT = getFunctionType();
2255     Result->AddTextChunk(
2256             FT->getResultType().getAsString(S.Context.PrintingPolicy));
2257     Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2258     Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2259     Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2260     return Result;
2261   }
2262 
2263   if (FDecl)
2264     Result->AddTextChunk(FDecl->getNameAsString());
2265   else
2266     Result->AddTextChunk(
2267          Proto->getResultType().getAsString(S.Context.PrintingPolicy));
2268 
2269   Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2270   unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2271   for (unsigned I = 0; I != NumParams; ++I) {
2272     if (I)
2273       Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2274 
2275     std::string ArgString;
2276     QualType ArgType;
2277 
2278     if (FDecl) {
2279       ArgString = FDecl->getParamDecl(I)->getNameAsString();
2280       ArgType = FDecl->getParamDecl(I)->getOriginalType();
2281     } else {
2282       ArgType = Proto->getArgType(I);
2283     }
2284 
2285     ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2286 
2287     if (I == CurrentArg)
2288       Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
2289                              ArgString));
2290     else
2291       Result->AddTextChunk(ArgString);
2292   }
2293 
2294   if (Proto && Proto->isVariadic()) {
2295     Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2296     if (CurrentArg < NumParams)
2297       Result->AddTextChunk("...");
2298     else
2299       Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2300   }
2301   Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2302 
2303   return Result;
2304 }
2305 
2306 unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2307                                       bool PreferredTypeIsPointer) {
2308   unsigned Priority = CCP_Macro;
2309 
2310   // Treat the "nil" and "NULL" macros as null pointer constants.
2311   if (MacroName.equals("nil") || MacroName.equals("NULL")) {
2312     Priority = CCP_Constant;
2313     if (PreferredTypeIsPointer)
2314       Priority = Priority / CCF_SimilarTypeMatch;
2315   }
2316 
2317   return Priority;
2318 }
2319 
2320 CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2321   if (!D)
2322     return CXCursor_UnexposedDecl;
2323 
2324   switch (D->getKind()) {
2325     case Decl::Enum:               return CXCursor_EnumDecl;
2326     case Decl::EnumConstant:       return CXCursor_EnumConstantDecl;
2327     case Decl::Field:              return CXCursor_FieldDecl;
2328     case Decl::Function:
2329       return CXCursor_FunctionDecl;
2330     case Decl::ObjCCategory:       return CXCursor_ObjCCategoryDecl;
2331     case Decl::ObjCCategoryImpl:   return CXCursor_ObjCCategoryImplDecl;
2332     case Decl::ObjCClass:
2333       // FIXME
2334       return CXCursor_UnexposedDecl;
2335     case Decl::ObjCForwardProtocol:
2336       // FIXME
2337       return CXCursor_UnexposedDecl;
2338     case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2339     case Decl::ObjCInterface:      return CXCursor_ObjCInterfaceDecl;
2340     case Decl::ObjCIvar:           return CXCursor_ObjCIvarDecl;
2341     case Decl::ObjCMethod:
2342       return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2343       ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2344     case Decl::CXXMethod:          return CXCursor_CXXMethod;
2345     case Decl::CXXConstructor:     return CXCursor_Constructor;
2346     case Decl::CXXDestructor:      return CXCursor_Destructor;
2347     case Decl::CXXConversion:      return CXCursor_ConversionFunction;
2348     case Decl::ObjCProperty:       return CXCursor_ObjCPropertyDecl;
2349     case Decl::ObjCProtocol:       return CXCursor_ObjCProtocolDecl;
2350     case Decl::ParmVar:            return CXCursor_ParmDecl;
2351     case Decl::Typedef:            return CXCursor_TypedefDecl;
2352     case Decl::Var:                return CXCursor_VarDecl;
2353     case Decl::Namespace:          return CXCursor_Namespace;
2354     case Decl::NamespaceAlias:     return CXCursor_NamespaceAlias;
2355     case Decl::TemplateTypeParm:   return CXCursor_TemplateTypeParameter;
2356     case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2357     case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2358     case Decl::FunctionTemplate:   return CXCursor_FunctionTemplate;
2359     case Decl::ClassTemplate:      return CXCursor_ClassTemplate;
2360     case Decl::ClassTemplatePartialSpecialization:
2361       return CXCursor_ClassTemplatePartialSpecialization;
2362     case Decl::UsingDirective:     return CXCursor_UsingDirective;
2363 
2364     case Decl::Using:
2365     case Decl::UnresolvedUsingValue:
2366     case Decl::UnresolvedUsingTypename:
2367       return CXCursor_UsingDeclaration;
2368 
2369     default:
2370       if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2371         switch (TD->getTagKind()) {
2372           case TTK_Struct: return CXCursor_StructDecl;
2373           case TTK_Class:  return CXCursor_ClassDecl;
2374           case TTK_Union:  return CXCursor_UnionDecl;
2375           case TTK_Enum:   return CXCursor_EnumDecl;
2376         }
2377       }
2378   }
2379 
2380   return CXCursor_UnexposedDecl;
2381 }
2382 
2383 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2384                             bool TargetTypeIsPointer = false) {
2385   typedef CodeCompletionResult Result;
2386 
2387   Results.EnterNewScope();
2388   for (Preprocessor::macro_iterator M = PP.macro_begin(),
2389                                  MEnd = PP.macro_end();
2390        M != MEnd; ++M) {
2391     Results.AddResult(Result(M->first,
2392                              getMacroUsagePriority(M->first->getName(),
2393                                                    TargetTypeIsPointer)));
2394   }
2395   Results.ExitScope();
2396 }
2397 
2398 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2399                                      ResultBuilder &Results) {
2400   typedef CodeCompletionResult Result;
2401 
2402   Results.EnterNewScope();
2403   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2404   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2405   if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2406     Results.AddResult(Result("__func__", CCP_Constant));
2407   Results.ExitScope();
2408 }
2409 
2410 static void HandleCodeCompleteResults(Sema *S,
2411                                       CodeCompleteConsumer *CodeCompleter,
2412                                       CodeCompletionContext Context,
2413                                       CodeCompletionResult *Results,
2414                                       unsigned NumResults) {
2415   if (CodeCompleter)
2416     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
2417 
2418   for (unsigned I = 0; I != NumResults; ++I)
2419     Results[I].Destroy();
2420 }
2421 
2422 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2423                                             Sema::ParserCompletionContext PCC) {
2424   switch (PCC) {
2425   case Sema::PCC_Namespace:
2426     return CodeCompletionContext::CCC_TopLevel;
2427 
2428   case Sema::PCC_Class:
2429     return CodeCompletionContext::CCC_ClassStructUnion;
2430 
2431   case Sema::PCC_ObjCInterface:
2432     return CodeCompletionContext::CCC_ObjCInterface;
2433 
2434   case Sema::PCC_ObjCImplementation:
2435     return CodeCompletionContext::CCC_ObjCImplementation;
2436 
2437   case Sema::PCC_ObjCInstanceVariableList:
2438     return CodeCompletionContext::CCC_ObjCIvarList;
2439 
2440   case Sema::PCC_Template:
2441   case Sema::PCC_MemberTemplate:
2442   case Sema::PCC_RecoveryInFunction:
2443     return CodeCompletionContext::CCC_Other;
2444 
2445   case Sema::PCC_Expression:
2446   case Sema::PCC_ForInit:
2447   case Sema::PCC_Condition:
2448     return CodeCompletionContext::CCC_Expression;
2449 
2450   case Sema::PCC_Statement:
2451     return CodeCompletionContext::CCC_Statement;
2452 
2453   case Sema::PCC_Type:
2454     return CodeCompletionContext::CCC_Type;
2455   }
2456 
2457   return CodeCompletionContext::CCC_Other;
2458 }
2459 
2460 /// \brief If we're in a C++ virtual member function, add completion results
2461 /// that invoke the functions we override, since it's common to invoke the
2462 /// overridden function as well as adding new functionality.
2463 ///
2464 /// \param S The semantic analysis object for which we are generating results.
2465 ///
2466 /// \param InContext This context in which the nested-name-specifier preceding
2467 /// the code-completion point
2468 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2469                                   ResultBuilder &Results) {
2470   // Look through blocks.
2471   DeclContext *CurContext = S.CurContext;
2472   while (isa<BlockDecl>(CurContext))
2473     CurContext = CurContext->getParent();
2474 
2475 
2476   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2477   if (!Method || !Method->isVirtual())
2478     return;
2479 
2480   // We need to have names for all of the parameters, if we're going to
2481   // generate a forwarding call.
2482   for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2483                                   PEnd = Method->param_end();
2484        P != PEnd;
2485        ++P) {
2486     if (!(*P)->getDeclName())
2487       return;
2488   }
2489 
2490   for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2491                                    MEnd = Method->end_overridden_methods();
2492        M != MEnd; ++M) {
2493     CodeCompletionString *Pattern = new CodeCompletionString;
2494     CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2495     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2496       continue;
2497 
2498     // If we need a nested-name-specifier, add one now.
2499     if (!InContext) {
2500       NestedNameSpecifier *NNS
2501         = getRequiredQualification(S.Context, CurContext,
2502                                    Overridden->getDeclContext());
2503       if (NNS) {
2504         std::string Str;
2505         llvm::raw_string_ostream OS(Str);
2506         NNS->print(OS, S.Context.PrintingPolicy);
2507         Pattern->AddTextChunk(OS.str());
2508       }
2509     } else if (!InContext->Equals(Overridden->getDeclContext()))
2510       continue;
2511 
2512     Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2513     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2514     bool FirstParam = true;
2515     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2516                                     PEnd = Method->param_end();
2517          P != PEnd; ++P) {
2518       if (FirstParam)
2519         FirstParam = false;
2520       else
2521         Pattern->AddChunk(CodeCompletionString::CK_Comma);
2522 
2523       Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2524     }
2525     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2526     Results.AddResult(CodeCompletionResult(Pattern,
2527                                            CCP_SuperCompletion,
2528                                            CXCursor_CXXMethod));
2529     Results.Ignore(Overridden);
2530   }
2531 }
2532 
2533 void Sema::CodeCompleteOrdinaryName(Scope *S,
2534                                     ParserCompletionContext CompletionContext) {
2535   typedef CodeCompletionResult Result;
2536   ResultBuilder Results(*this);
2537   Results.EnterNewScope();
2538 
2539   // Determine how to filter results, e.g., so that the names of
2540   // values (functions, enumerators, function templates, etc.) are
2541   // only allowed where we can have an expression.
2542   switch (CompletionContext) {
2543   case PCC_Namespace:
2544   case PCC_Class:
2545   case PCC_ObjCInterface:
2546   case PCC_ObjCImplementation:
2547   case PCC_ObjCInstanceVariableList:
2548   case PCC_Template:
2549   case PCC_MemberTemplate:
2550   case PCC_Type:
2551     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2552     break;
2553 
2554   case PCC_Statement:
2555     // For statements that are expressions, we prefer to call 'void' functions
2556     // rather than functions that return a result, since then the result would
2557     // be ignored.
2558     Results.setPreferredType(Context.VoidTy);
2559     // Fall through
2560 
2561   case PCC_Expression:
2562   case PCC_ForInit:
2563   case PCC_Condition:
2564     if (WantTypesInContext(CompletionContext, getLangOptions()))
2565       Results.setFilter(&ResultBuilder::IsOrdinaryName);
2566     else
2567       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2568 
2569     if (getLangOptions().CPlusPlus)
2570       MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
2571     break;
2572 
2573   case PCC_RecoveryInFunction:
2574     // Unfiltered
2575     break;
2576   }
2577 
2578   // If we are in a C++ non-static member function, check the qualifiers on
2579   // the member function to filter/prioritize the results list.
2580   if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2581     if (CurMethod->isInstance())
2582       Results.setObjectTypeQualifiers(
2583                       Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2584 
2585   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2586   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2587                      CodeCompleter->includeGlobals());
2588 
2589   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
2590   Results.ExitScope();
2591 
2592   switch (CompletionContext) {
2593   case PCC_Expression:
2594   case PCC_Statement:
2595   case PCC_RecoveryInFunction:
2596     if (S->getFnParent())
2597       AddPrettyFunctionResults(PP.getLangOptions(), Results);
2598     break;
2599 
2600   case PCC_Namespace:
2601   case PCC_Class:
2602   case PCC_ObjCInterface:
2603   case PCC_ObjCImplementation:
2604   case PCC_ObjCInstanceVariableList:
2605   case PCC_Template:
2606   case PCC_MemberTemplate:
2607   case PCC_ForInit:
2608   case PCC_Condition:
2609   case PCC_Type:
2610     break;
2611   }
2612 
2613   if (CodeCompleter->includeMacros())
2614     AddMacroResults(PP, Results);
2615 
2616   HandleCodeCompleteResults(this, CodeCompleter,
2617                             mapCodeCompletionContext(*this, CompletionContext),
2618                             Results.data(),Results.size());
2619 }
2620 
2621 void Sema::CodeCompleteDeclarator(Scope *S,
2622                                   bool AllowNonIdentifiers,
2623                                   bool AllowNestedNameSpecifiers) {
2624   typedef CodeCompletionResult Result;
2625   ResultBuilder Results(*this);
2626   Results.EnterNewScope();
2627 
2628   // Type qualifiers can come after names.
2629   Results.AddResult(Result("const"));
2630   Results.AddResult(Result("volatile"));
2631   if (getLangOptions().C99)
2632     Results.AddResult(Result("restrict"));
2633 
2634   if (getLangOptions().CPlusPlus) {
2635     if (AllowNonIdentifiers) {
2636       Results.AddResult(Result("operator"));
2637     }
2638 
2639     // Add nested-name-specifiers.
2640     if (AllowNestedNameSpecifiers) {
2641       Results.allowNestedNameSpecifiers();
2642       CodeCompletionDeclConsumer Consumer(Results, CurContext);
2643       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2644                          CodeCompleter->includeGlobals());
2645     }
2646   }
2647   Results.ExitScope();
2648 
2649   // Note that we intentionally suppress macro results here, since we do not
2650   // encourage using macros to produce the names of entities.
2651 
2652   HandleCodeCompleteResults(this, CodeCompleter,
2653                         AllowNestedNameSpecifiers
2654                           ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2655                           : CodeCompletionContext::CCC_Name,
2656                             Results.data(), Results.size());
2657 }
2658 
2659 struct Sema::CodeCompleteExpressionData {
2660   CodeCompleteExpressionData(QualType PreferredType = QualType())
2661     : PreferredType(PreferredType), IntegralConstantExpression(false),
2662       ObjCCollection(false) { }
2663 
2664   QualType PreferredType;
2665   bool IntegralConstantExpression;
2666   bool ObjCCollection;
2667   llvm::SmallVector<Decl *, 4> IgnoreDecls;
2668 };
2669 
2670 /// \brief Perform code-completion in an expression context when we know what
2671 /// type we're looking for.
2672 ///
2673 /// \param IntegralConstantExpression Only permit integral constant
2674 /// expressions.
2675 void Sema::CodeCompleteExpression(Scope *S,
2676                                   const CodeCompleteExpressionData &Data) {
2677   typedef CodeCompletionResult Result;
2678   ResultBuilder Results(*this);
2679 
2680   if (Data.ObjCCollection)
2681     Results.setFilter(&ResultBuilder::IsObjCCollection);
2682   else if (Data.IntegralConstantExpression)
2683     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
2684   else if (WantTypesInContext(PCC_Expression, getLangOptions()))
2685     Results.setFilter(&ResultBuilder::IsOrdinaryName);
2686   else
2687     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2688 
2689   if (!Data.PreferredType.isNull())
2690     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2691 
2692   // Ignore any declarations that we were told that we don't care about.
2693   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2694     Results.Ignore(Data.IgnoreDecls[I]);
2695 
2696   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2697   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2698                      CodeCompleter->includeGlobals());
2699 
2700   Results.EnterNewScope();
2701   AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
2702   Results.ExitScope();
2703 
2704   bool PreferredTypeIsPointer = false;
2705   if (!Data.PreferredType.isNull())
2706     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2707       || Data.PreferredType->isMemberPointerType()
2708       || Data.PreferredType->isBlockPointerType();
2709 
2710   if (S->getFnParent() &&
2711       !Data.ObjCCollection &&
2712       !Data.IntegralConstantExpression)
2713     AddPrettyFunctionResults(PP.getLangOptions(), Results);
2714 
2715   if (CodeCompleter->includeMacros())
2716     AddMacroResults(PP, Results, PreferredTypeIsPointer);
2717   HandleCodeCompleteResults(this, CodeCompleter,
2718                 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2719                                       Data.PreferredType),
2720                             Results.data(),Results.size());
2721 }
2722 
2723 
2724 static void AddObjCProperties(ObjCContainerDecl *Container,
2725                               bool AllowCategories,
2726                               DeclContext *CurContext,
2727                               ResultBuilder &Results) {
2728   typedef CodeCompletionResult Result;
2729 
2730   // Add properties in this container.
2731   for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2732                                      PEnd = Container->prop_end();
2733        P != PEnd;
2734        ++P)
2735     Results.MaybeAddResult(Result(*P, 0), CurContext);
2736 
2737   // Add properties in referenced protocols.
2738   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2739     for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2740                                           PEnd = Protocol->protocol_end();
2741          P != PEnd; ++P)
2742       AddObjCProperties(*P, AllowCategories, CurContext, Results);
2743   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
2744     if (AllowCategories) {
2745       // Look through categories.
2746       for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2747            Category; Category = Category->getNextClassCategory())
2748         AddObjCProperties(Category, AllowCategories, CurContext, Results);
2749     }
2750 
2751     // Look through protocols.
2752     for (ObjCInterfaceDecl::all_protocol_iterator
2753          I = IFace->all_referenced_protocol_begin(),
2754          E = IFace->all_referenced_protocol_end(); I != E; ++I)
2755       AddObjCProperties(*I, AllowCategories, CurContext, Results);
2756 
2757     // Look in the superclass.
2758     if (IFace->getSuperClass())
2759       AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2760                         Results);
2761   } else if (const ObjCCategoryDecl *Category
2762                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
2763     // Look through protocols.
2764     for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
2765                                           PEnd = Category->protocol_end();
2766          P != PEnd; ++P)
2767       AddObjCProperties(*P, AllowCategories, CurContext, Results);
2768   }
2769 }
2770 
2771 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2772                                            SourceLocation OpLoc,
2773                                            bool IsArrow) {
2774   if (!BaseE || !CodeCompleter)
2775     return;
2776 
2777   typedef CodeCompletionResult Result;
2778 
2779   Expr *Base = static_cast<Expr *>(BaseE);
2780   QualType BaseType = Base->getType();
2781 
2782   if (IsArrow) {
2783     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2784       BaseType = Ptr->getPointeeType();
2785     else if (BaseType->isObjCObjectPointerType())
2786       /*Do nothing*/ ;
2787     else
2788       return;
2789   }
2790 
2791   ResultBuilder Results(*this, &ResultBuilder::IsMember);
2792   Results.EnterNewScope();
2793   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2794     // Indicate that we are performing a member access, and the cv-qualifiers
2795     // for the base object type.
2796     Results.setObjectTypeQualifiers(BaseType.getQualifiers());
2797 
2798     // Access to a C/C++ class, struct, or union.
2799     Results.allowNestedNameSpecifiers();
2800     CodeCompletionDeclConsumer Consumer(Results, CurContext);
2801     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2802                        CodeCompleter->includeGlobals());
2803 
2804     if (getLangOptions().CPlusPlus) {
2805       if (!Results.empty()) {
2806         // The "template" keyword can follow "->" or "." in the grammar.
2807         // However, we only want to suggest the template keyword if something
2808         // is dependent.
2809         bool IsDependent = BaseType->isDependentType();
2810         if (!IsDependent) {
2811           for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2812             if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2813               IsDependent = Ctx->isDependentContext();
2814               break;
2815             }
2816         }
2817 
2818         if (IsDependent)
2819           Results.AddResult(Result("template"));
2820       }
2821     }
2822   } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2823     // Objective-C property reference.
2824 
2825     // Add property results based on our interface.
2826     const ObjCObjectPointerType *ObjCPtr
2827       = BaseType->getAsObjCInterfacePointerType();
2828     assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
2829     AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
2830 
2831     // Add properties from the protocols in a qualified interface.
2832     for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2833                                               E = ObjCPtr->qual_end();
2834          I != E; ++I)
2835       AddObjCProperties(*I, true, CurContext, Results);
2836   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2837              (!IsArrow && BaseType->isObjCObjectType())) {
2838     // Objective-C instance variable access.
2839     ObjCInterfaceDecl *Class = 0;
2840     if (const ObjCObjectPointerType *ObjCPtr
2841                                     = BaseType->getAs<ObjCObjectPointerType>())
2842       Class = ObjCPtr->getInterfaceDecl();
2843     else
2844       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
2845 
2846     // Add all ivars from this class and its superclasses.
2847     if (Class) {
2848       CodeCompletionDeclConsumer Consumer(Results, CurContext);
2849       Results.setFilter(&ResultBuilder::IsObjCIvar);
2850       LookupVisibleDecls(Class, LookupMemberName, Consumer,
2851                          CodeCompleter->includeGlobals());
2852     }
2853   }
2854 
2855   // FIXME: How do we cope with isa?
2856 
2857   Results.ExitScope();
2858 
2859   // Hand off the results found for code completion.
2860   HandleCodeCompleteResults(this, CodeCompleter,
2861             CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2862                                               BaseType),
2863                             Results.data(),Results.size());
2864 }
2865 
2866 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2867   if (!CodeCompleter)
2868     return;
2869 
2870   typedef CodeCompletionResult Result;
2871   ResultBuilder::LookupFilter Filter = 0;
2872   enum CodeCompletionContext::Kind ContextKind
2873     = CodeCompletionContext::CCC_Other;
2874   switch ((DeclSpec::TST)TagSpec) {
2875   case DeclSpec::TST_enum:
2876     Filter = &ResultBuilder::IsEnum;
2877     ContextKind = CodeCompletionContext::CCC_EnumTag;
2878     break;
2879 
2880   case DeclSpec::TST_union:
2881     Filter = &ResultBuilder::IsUnion;
2882     ContextKind = CodeCompletionContext::CCC_UnionTag;
2883     break;
2884 
2885   case DeclSpec::TST_struct:
2886   case DeclSpec::TST_class:
2887     Filter = &ResultBuilder::IsClassOrStruct;
2888     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
2889     break;
2890 
2891   default:
2892     assert(false && "Unknown type specifier kind in CodeCompleteTag");
2893     return;
2894   }
2895 
2896   ResultBuilder Results(*this);
2897   CodeCompletionDeclConsumer Consumer(Results, CurContext);
2898 
2899   // First pass: look for tags.
2900   Results.setFilter(Filter);
2901   LookupVisibleDecls(S, LookupTagName, Consumer,
2902                      CodeCompleter->includeGlobals());
2903 
2904   if (CodeCompleter->includeGlobals()) {
2905     // Second pass: look for nested name specifiers.
2906     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2907     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2908   }
2909 
2910   HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2911                             Results.data(),Results.size());
2912 }
2913 
2914 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
2915   ResultBuilder Results(*this);
2916   Results.EnterNewScope();
2917   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
2918     Results.AddResult("const");
2919   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
2920     Results.AddResult("volatile");
2921   if (getLangOptions().C99 &&
2922       !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
2923     Results.AddResult("restrict");
2924   Results.ExitScope();
2925   HandleCodeCompleteResults(this, CodeCompleter,
2926                             CodeCompletionContext::CCC_TypeQualifiers,
2927                             Results.data(), Results.size());
2928 }
2929 
2930 void Sema::CodeCompleteCase(Scope *S) {
2931   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
2932     return;
2933 
2934   SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
2935   if (!Switch->getCond()->getType()->isEnumeralType()) {
2936     CodeCompleteExpressionData Data(Switch->getCond()->getType());
2937     Data.IntegralConstantExpression = true;
2938     CodeCompleteExpression(S, Data);
2939     return;
2940   }
2941 
2942   // Code-complete the cases of a switch statement over an enumeration type
2943   // by providing the list of
2944   EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2945 
2946   // Determine which enumerators we have already seen in the switch statement.
2947   // FIXME: Ideally, we would also be able to look *past* the code-completion
2948   // token, in case we are code-completing in the middle of the switch and not
2949   // at the end. However, we aren't able to do so at the moment.
2950   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
2951   NestedNameSpecifier *Qualifier = 0;
2952   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2953        SC = SC->getNextSwitchCase()) {
2954     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2955     if (!Case)
2956       continue;
2957 
2958     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2959     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2960       if (EnumConstantDecl *Enumerator
2961             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2962         // We look into the AST of the case statement to determine which
2963         // enumerator was named. Alternatively, we could compute the value of
2964         // the integral constant expression, then compare it against the
2965         // values of each enumerator. However, value-based approach would not
2966         // work as well with C++ templates where enumerators declared within a
2967         // template are type- and value-dependent.
2968         EnumeratorsSeen.insert(Enumerator);
2969 
2970         // If this is a qualified-id, keep track of the nested-name-specifier
2971         // so that we can reproduce it as part of code completion, e.g.,
2972         //
2973         //   switch (TagD.getKind()) {
2974         //     case TagDecl::TK_enum:
2975         //       break;
2976         //     case XXX
2977         //
2978         // At the XXX, our completions are TagDecl::TK_union,
2979         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2980         // TK_struct, and TK_class.
2981         Qualifier = DRE->getQualifier();
2982       }
2983   }
2984 
2985   if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2986     // If there are no prior enumerators in C++, check whether we have to
2987     // qualify the names of the enumerators that we suggest, because they
2988     // may not be visible in this scope.
2989     Qualifier = getRequiredQualification(Context, CurContext,
2990                                          Enum->getDeclContext());
2991 
2992     // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2993   }
2994 
2995   // Add any enumerators that have not yet been mentioned.
2996   ResultBuilder Results(*this);
2997   Results.EnterNewScope();
2998   for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2999                                   EEnd = Enum->enumerator_end();
3000        E != EEnd; ++E) {
3001     if (EnumeratorsSeen.count(*E))
3002       continue;
3003 
3004     Results.AddResult(CodeCompletionResult(*E, Qualifier),
3005                       CurContext, 0, false);
3006   }
3007   Results.ExitScope();
3008 
3009   if (CodeCompleter->includeMacros())
3010     AddMacroResults(PP, Results);
3011   HandleCodeCompleteResults(this, CodeCompleter,
3012                             CodeCompletionContext::CCC_Expression,
3013                             Results.data(),Results.size());
3014 }
3015 
3016 namespace {
3017   struct IsBetterOverloadCandidate {
3018     Sema &S;
3019     SourceLocation Loc;
3020 
3021   public:
3022     explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3023       : S(S), Loc(Loc) { }
3024 
3025     bool
3026     operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
3027       return isBetterOverloadCandidate(S, X, Y, Loc);
3028     }
3029   };
3030 }
3031 
3032 static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3033   if (NumArgs && !Args)
3034     return true;
3035 
3036   for (unsigned I = 0; I != NumArgs; ++I)
3037     if (!Args[I])
3038       return true;
3039 
3040   return false;
3041 }
3042 
3043 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3044                             ExprTy **ArgsIn, unsigned NumArgs) {
3045   if (!CodeCompleter)
3046     return;
3047 
3048   // When we're code-completing for a call, we fall back to ordinary
3049   // name code-completion whenever we can't produce specific
3050   // results. We may want to revisit this strategy in the future,
3051   // e.g., by merging the two kinds of results.
3052 
3053   Expr *Fn = (Expr *)FnIn;
3054   Expr **Args = (Expr **)ArgsIn;
3055 
3056   // Ignore type-dependent call expressions entirely.
3057   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
3058       Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3059     CodeCompleteOrdinaryName(S, PCC_Expression);
3060     return;
3061   }
3062 
3063   // Build an overload candidate set based on the functions we find.
3064   SourceLocation Loc = Fn->getExprLoc();
3065   OverloadCandidateSet CandidateSet(Loc);
3066 
3067   // FIXME: What if we're calling something that isn't a function declaration?
3068   // FIXME: What if we're calling a pseudo-destructor?
3069   // FIXME: What if we're calling a member function?
3070 
3071   typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3072   llvm::SmallVector<ResultCandidate, 8> Results;
3073 
3074   Expr *NakedFn = Fn->IgnoreParenCasts();
3075   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3076     AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3077                                 /*PartialOverloading=*/ true);
3078   else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3079     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
3080     if (FDecl) {
3081       if (!getLangOptions().CPlusPlus ||
3082           !FDecl->getType()->getAs<FunctionProtoType>())
3083         Results.push_back(ResultCandidate(FDecl));
3084       else
3085         // FIXME: access?
3086         AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3087                              Args, NumArgs, CandidateSet,
3088                              false, /*PartialOverloading*/true);
3089     }
3090   }
3091 
3092   QualType ParamType;
3093 
3094   if (!CandidateSet.empty()) {
3095     // Sort the overload candidate set by placing the best overloads first.
3096     std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
3097                      IsBetterOverloadCandidate(*this, Loc));
3098 
3099     // Add the remaining viable overload candidates as code-completion reslults.
3100     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3101                                      CandEnd = CandidateSet.end();
3102          Cand != CandEnd; ++Cand) {
3103       if (Cand->Viable)
3104         Results.push_back(ResultCandidate(Cand->Function));
3105     }
3106 
3107     // From the viable candidates, try to determine the type of this parameter.
3108     for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3109       if (const FunctionType *FType = Results[I].getFunctionType())
3110         if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3111           if (NumArgs < Proto->getNumArgs()) {
3112             if (ParamType.isNull())
3113               ParamType = Proto->getArgType(NumArgs);
3114             else if (!Context.hasSameUnqualifiedType(
3115                                             ParamType.getNonReferenceType(),
3116                            Proto->getArgType(NumArgs).getNonReferenceType())) {
3117               ParamType = QualType();
3118               break;
3119             }
3120           }
3121     }
3122   } else {
3123     // Try to determine the parameter type from the type of the expression
3124     // being called.
3125     QualType FunctionType = Fn->getType();
3126     if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3127       FunctionType = Ptr->getPointeeType();
3128     else if (const BlockPointerType *BlockPtr
3129                                     = FunctionType->getAs<BlockPointerType>())
3130       FunctionType = BlockPtr->getPointeeType();
3131     else if (const MemberPointerType *MemPtr
3132                                     = FunctionType->getAs<MemberPointerType>())
3133       FunctionType = MemPtr->getPointeeType();
3134 
3135     if (const FunctionProtoType *Proto
3136                                   = FunctionType->getAs<FunctionProtoType>()) {
3137       if (NumArgs < Proto->getNumArgs())
3138         ParamType = Proto->getArgType(NumArgs);
3139     }
3140   }
3141 
3142   if (ParamType.isNull())
3143     CodeCompleteOrdinaryName(S, PCC_Expression);
3144   else
3145     CodeCompleteExpression(S, ParamType);
3146 
3147   if (!Results.empty())
3148     CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3149                                              Results.size());
3150 }
3151 
3152 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3153   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3154   if (!VD) {
3155     CodeCompleteOrdinaryName(S, PCC_Expression);
3156     return;
3157   }
3158 
3159   CodeCompleteExpression(S, VD->getType());
3160 }
3161 
3162 void Sema::CodeCompleteReturn(Scope *S) {
3163   QualType ResultType;
3164   if (isa<BlockDecl>(CurContext)) {
3165     if (BlockScopeInfo *BSI = getCurBlock())
3166       ResultType = BSI->ReturnType;
3167   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3168     ResultType = Function->getResultType();
3169   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3170     ResultType = Method->getResultType();
3171 
3172   if (ResultType.isNull())
3173     CodeCompleteOrdinaryName(S, PCC_Expression);
3174   else
3175     CodeCompleteExpression(S, ResultType);
3176 }
3177 
3178 void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3179   if (LHS)
3180     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3181   else
3182     CodeCompleteOrdinaryName(S, PCC_Expression);
3183 }
3184 
3185 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
3186                                    bool EnteringContext) {
3187   if (!SS.getScopeRep() || !CodeCompleter)
3188     return;
3189 
3190   DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3191   if (!Ctx)
3192     return;
3193 
3194   // Try to instantiate any non-dependent declaration contexts before
3195   // we look in them.
3196   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
3197     return;
3198 
3199   ResultBuilder Results(*this);
3200 
3201   Results.EnterNewScope();
3202   // The "template" keyword can follow "::" in the grammar, but only
3203   // put it into the grammar if the nested-name-specifier is dependent.
3204   NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3205   if (!Results.empty() && NNS->isDependent())
3206     Results.AddResult("template");
3207 
3208   // Add calls to overridden virtual functions, if there are any.
3209   //
3210   // FIXME: This isn't wonderful, because we don't know whether we're actually
3211   // in a context that permits expressions. This is a general issue with
3212   // qualified-id completions.
3213   if (!EnteringContext)
3214     MaybeAddOverrideCalls(*this, Ctx, Results);
3215   Results.ExitScope();
3216 
3217   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3218   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3219 
3220   HandleCodeCompleteResults(this, CodeCompleter,
3221                             CodeCompletionContext::CCC_Name,
3222                             Results.data(),Results.size());
3223 }
3224 
3225 void Sema::CodeCompleteUsing(Scope *S) {
3226   if (!CodeCompleter)
3227     return;
3228 
3229   ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
3230   Results.EnterNewScope();
3231 
3232   // If we aren't in class scope, we could see the "namespace" keyword.
3233   if (!S->isClassScope())
3234     Results.AddResult(CodeCompletionResult("namespace"));
3235 
3236   // After "using", we can see anything that would start a
3237   // nested-name-specifier.
3238   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3239   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3240                      CodeCompleter->includeGlobals());
3241   Results.ExitScope();
3242 
3243   HandleCodeCompleteResults(this, CodeCompleter,
3244                             CodeCompletionContext::CCC_Other,
3245                             Results.data(),Results.size());
3246 }
3247 
3248 void Sema::CodeCompleteUsingDirective(Scope *S) {
3249   if (!CodeCompleter)
3250     return;
3251 
3252   // After "using namespace", we expect to see a namespace name or namespace
3253   // alias.
3254   ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
3255   Results.EnterNewScope();
3256   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3257   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3258                      CodeCompleter->includeGlobals());
3259   Results.ExitScope();
3260   HandleCodeCompleteResults(this, CodeCompleter,
3261                             CodeCompletionContext::CCC_Namespace,
3262                             Results.data(),Results.size());
3263 }
3264 
3265 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
3266   if (!CodeCompleter)
3267     return;
3268 
3269   ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
3270   DeclContext *Ctx = (DeclContext *)S->getEntity();
3271   if (!S->getParent())
3272     Ctx = Context.getTranslationUnitDecl();
3273 
3274   if (Ctx && Ctx->isFileContext()) {
3275     // We only want to see those namespaces that have already been defined
3276     // within this scope, because its likely that the user is creating an
3277     // extended namespace declaration. Keep track of the most recent
3278     // definition of each namespace.
3279     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3280     for (DeclContext::specific_decl_iterator<NamespaceDecl>
3281          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3282          NS != NSEnd; ++NS)
3283       OrigToLatest[NS->getOriginalNamespace()] = *NS;
3284 
3285     // Add the most recent definition (or extended definition) of each
3286     // namespace to the list of results.
3287     Results.EnterNewScope();
3288     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3289          NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3290          NS != NSEnd; ++NS)
3291       Results.AddResult(CodeCompletionResult(NS->second, 0),
3292                         CurContext, 0, false);
3293     Results.ExitScope();
3294   }
3295 
3296   HandleCodeCompleteResults(this, CodeCompleter,
3297                             CodeCompletionContext::CCC_Other,
3298                             Results.data(),Results.size());
3299 }
3300 
3301 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
3302   if (!CodeCompleter)
3303     return;
3304 
3305   // After "namespace", we expect to see a namespace or alias.
3306   ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
3307   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3308   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3309                      CodeCompleter->includeGlobals());
3310   HandleCodeCompleteResults(this, CodeCompleter,
3311                             CodeCompletionContext::CCC_Namespace,
3312                             Results.data(),Results.size());
3313 }
3314 
3315 void Sema::CodeCompleteOperatorName(Scope *S) {
3316   if (!CodeCompleter)
3317     return;
3318 
3319   typedef CodeCompletionResult Result;
3320   ResultBuilder Results(*this, &ResultBuilder::IsType);
3321   Results.EnterNewScope();
3322 
3323   // Add the names of overloadable operators.
3324 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
3325   if (std::strcmp(Spelling, "?"))                                                  \
3326     Results.AddResult(Result(Spelling));
3327 #include "clang/Basic/OperatorKinds.def"
3328 
3329   // Add any type names visible from the current scope
3330   Results.allowNestedNameSpecifiers();
3331   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3332   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3333                      CodeCompleter->includeGlobals());
3334 
3335   // Add any type specifiers
3336   AddTypeSpecifierResults(getLangOptions(), Results);
3337   Results.ExitScope();
3338 
3339   HandleCodeCompleteResults(this, CodeCompleter,
3340                             CodeCompletionContext::CCC_Type,
3341                             Results.data(),Results.size());
3342 }
3343 
3344 void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3345                                     CXXBaseOrMemberInitializer** Initializers,
3346                                               unsigned NumInitializers) {
3347   CXXConstructorDecl *Constructor
3348     = static_cast<CXXConstructorDecl *>(ConstructorD);
3349   if (!Constructor)
3350     return;
3351 
3352   ResultBuilder Results(*this);
3353   Results.EnterNewScope();
3354 
3355   // Fill in any already-initialized fields or base classes.
3356   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3357   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3358   for (unsigned I = 0; I != NumInitializers; ++I) {
3359     if (Initializers[I]->isBaseInitializer())
3360       InitializedBases.insert(
3361         Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3362     else
3363       InitializedFields.insert(cast<FieldDecl>(Initializers[I]->getMember()));
3364   }
3365 
3366   // Add completions for base classes.
3367   bool SawLastInitializer = (NumInitializers == 0);
3368   CXXRecordDecl *ClassDecl = Constructor->getParent();
3369   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3370                                        BaseEnd = ClassDecl->bases_end();
3371        Base != BaseEnd; ++Base) {
3372     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3373       SawLastInitializer
3374         = NumInitializers > 0 &&
3375           Initializers[NumInitializers - 1]->isBaseInitializer() &&
3376           Context.hasSameUnqualifiedType(Base->getType(),
3377                QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
3378       continue;
3379     }
3380 
3381     CodeCompletionString *Pattern = new CodeCompletionString;
3382     Pattern->AddTypedTextChunk(
3383                            Base->getType().getAsString(Context.PrintingPolicy));
3384     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3385     Pattern->AddPlaceholderChunk("args");
3386     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3387     Results.AddResult(CodeCompletionResult(Pattern,
3388                                    SawLastInitializer? CCP_NextInitializer
3389                                                      : CCP_MemberDeclaration));
3390     SawLastInitializer = false;
3391   }
3392 
3393   // Add completions for virtual base classes.
3394   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3395                                        BaseEnd = ClassDecl->vbases_end();
3396        Base != BaseEnd; ++Base) {
3397     if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3398       SawLastInitializer
3399         = NumInitializers > 0 &&
3400           Initializers[NumInitializers - 1]->isBaseInitializer() &&
3401           Context.hasSameUnqualifiedType(Base->getType(),
3402                QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
3403       continue;
3404     }
3405 
3406     CodeCompletionString *Pattern = new CodeCompletionString;
3407     Pattern->AddTypedTextChunk(
3408                            Base->getType().getAsString(Context.PrintingPolicy));
3409     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3410     Pattern->AddPlaceholderChunk("args");
3411     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3412     Results.AddResult(CodeCompletionResult(Pattern,
3413                                    SawLastInitializer? CCP_NextInitializer
3414                                                      : CCP_MemberDeclaration));
3415     SawLastInitializer = false;
3416   }
3417 
3418   // Add completions for members.
3419   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3420                                   FieldEnd = ClassDecl->field_end();
3421        Field != FieldEnd; ++Field) {
3422     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3423       SawLastInitializer
3424         = NumInitializers > 0 &&
3425           Initializers[NumInitializers - 1]->isMemberInitializer() &&
3426           Initializers[NumInitializers - 1]->getMember() == *Field;
3427       continue;
3428     }
3429 
3430     if (!Field->getDeclName())
3431       continue;
3432 
3433     CodeCompletionString *Pattern = new CodeCompletionString;
3434     Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3435     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3436     Pattern->AddPlaceholderChunk("args");
3437     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3438     Results.AddResult(CodeCompletionResult(Pattern,
3439                                    SawLastInitializer? CCP_NextInitializer
3440                                                      : CCP_MemberDeclaration));
3441     SawLastInitializer = false;
3442   }
3443   Results.ExitScope();
3444 
3445   HandleCodeCompleteResults(this, CodeCompleter,
3446                             CodeCompletionContext::CCC_Name,
3447                             Results.data(), Results.size());
3448 }
3449 
3450 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3451 // true or false.
3452 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
3453 static void AddObjCImplementationResults(const LangOptions &LangOpts,
3454                                          ResultBuilder &Results,
3455                                          bool NeedAt) {
3456   typedef CodeCompletionResult Result;
3457   // Since we have an implementation, we can end it.
3458   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
3459 
3460   CodeCompletionString *Pattern = 0;
3461   if (LangOpts.ObjC2) {
3462     // @dynamic
3463     Pattern = new CodeCompletionString;
3464     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3465     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3466     Pattern->AddPlaceholderChunk("property");
3467     Results.AddResult(Result(Pattern));
3468 
3469     // @synthesize
3470     Pattern = new CodeCompletionString;
3471     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3472     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3473     Pattern->AddPlaceholderChunk("property");
3474     Results.AddResult(Result(Pattern));
3475   }
3476 }
3477 
3478 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
3479                                     ResultBuilder &Results,
3480                                     bool NeedAt) {
3481   typedef CodeCompletionResult Result;
3482 
3483   // Since we have an interface or protocol, we can end it.
3484   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
3485 
3486   if (LangOpts.ObjC2) {
3487     // @property
3488     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
3489 
3490     // @required
3491     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
3492 
3493     // @optional
3494     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
3495   }
3496 }
3497 
3498 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
3499   typedef CodeCompletionResult Result;
3500   CodeCompletionString *Pattern = 0;
3501 
3502   // @class name ;
3503   Pattern = new CodeCompletionString;
3504   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3505   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3506   Pattern->AddPlaceholderChunk("name");
3507   Results.AddResult(Result(Pattern));
3508 
3509   if (Results.includeCodePatterns()) {
3510     // @interface name
3511     // FIXME: Could introduce the whole pattern, including superclasses and
3512     // such.
3513     Pattern = new CodeCompletionString;
3514     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3515     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3516     Pattern->AddPlaceholderChunk("class");
3517     Results.AddResult(Result(Pattern));
3518 
3519     // @protocol name
3520     Pattern = new CodeCompletionString;
3521     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3522     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3523     Pattern->AddPlaceholderChunk("protocol");
3524     Results.AddResult(Result(Pattern));
3525 
3526     // @implementation name
3527     Pattern = new CodeCompletionString;
3528     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3529     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3530     Pattern->AddPlaceholderChunk("class");
3531     Results.AddResult(Result(Pattern));
3532   }
3533 
3534   // @compatibility_alias name
3535   Pattern = new CodeCompletionString;
3536   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3537   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3538   Pattern->AddPlaceholderChunk("alias");
3539   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3540   Pattern->AddPlaceholderChunk("class");
3541   Results.AddResult(Result(Pattern));
3542 }
3543 
3544 void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
3545                                        bool InInterface) {
3546   typedef CodeCompletionResult Result;
3547   ResultBuilder Results(*this);
3548   Results.EnterNewScope();
3549   if (ObjCImpDecl)
3550     AddObjCImplementationResults(getLangOptions(), Results, false);
3551   else if (InInterface)
3552     AddObjCInterfaceResults(getLangOptions(), Results, false);
3553   else
3554     AddObjCTopLevelResults(Results, false);
3555   Results.ExitScope();
3556   HandleCodeCompleteResults(this, CodeCompleter,
3557                             CodeCompletionContext::CCC_Other,
3558                             Results.data(),Results.size());
3559 }
3560 
3561 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
3562   typedef CodeCompletionResult Result;
3563   CodeCompletionString *Pattern = 0;
3564 
3565   // @encode ( type-name )
3566   Pattern = new CodeCompletionString;
3567   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
3568   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3569   Pattern->AddPlaceholderChunk("type-name");
3570   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3571   Results.AddResult(Result(Pattern));
3572 
3573   // @protocol ( protocol-name )
3574   Pattern = new CodeCompletionString;
3575   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3576   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3577   Pattern->AddPlaceholderChunk("protocol-name");
3578   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3579   Results.AddResult(Result(Pattern));
3580 
3581   // @selector ( selector )
3582   Pattern = new CodeCompletionString;
3583   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
3584   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3585   Pattern->AddPlaceholderChunk("selector");
3586   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3587   Results.AddResult(Result(Pattern));
3588 }
3589 
3590 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
3591   typedef CodeCompletionResult Result;
3592   CodeCompletionString *Pattern = 0;
3593 
3594   if (Results.includeCodePatterns()) {
3595     // @try { statements } @catch ( declaration ) { statements } @finally
3596     //   { statements }
3597     Pattern = new CodeCompletionString;
3598     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3599     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3600     Pattern->AddPlaceholderChunk("statements");
3601     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3602     Pattern->AddTextChunk("@catch");
3603     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3604     Pattern->AddPlaceholderChunk("parameter");
3605     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3606     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3607     Pattern->AddPlaceholderChunk("statements");
3608     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3609     Pattern->AddTextChunk("@finally");
3610     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3611     Pattern->AddPlaceholderChunk("statements");
3612     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3613     Results.AddResult(Result(Pattern));
3614   }
3615 
3616   // @throw
3617   Pattern = new CodeCompletionString;
3618   Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
3619   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3620   Pattern->AddPlaceholderChunk("expression");
3621   Results.AddResult(Result(Pattern));
3622 
3623   if (Results.includeCodePatterns()) {
3624     // @synchronized ( expression ) { statements }
3625     Pattern = new CodeCompletionString;
3626     Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3627     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3628     Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3629     Pattern->AddPlaceholderChunk("expression");
3630     Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3631     Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3632     Pattern->AddPlaceholderChunk("statements");
3633     Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3634     Results.AddResult(Result(Pattern));
3635   }
3636 }
3637 
3638 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
3639                                      ResultBuilder &Results,
3640                                      bool NeedAt) {
3641   typedef CodeCompletionResult Result;
3642   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3643   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3644   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
3645   if (LangOpts.ObjC2)
3646     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
3647 }
3648 
3649 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3650   ResultBuilder Results(*this);
3651   Results.EnterNewScope();
3652   AddObjCVisibilityResults(getLangOptions(), Results, false);
3653   Results.ExitScope();
3654   HandleCodeCompleteResults(this, CodeCompleter,
3655                             CodeCompletionContext::CCC_Other,
3656                             Results.data(),Results.size());
3657 }
3658 
3659 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
3660   ResultBuilder Results(*this);
3661   Results.EnterNewScope();
3662   AddObjCStatementResults(Results, false);
3663   AddObjCExpressionResults(Results, false);
3664   Results.ExitScope();
3665   HandleCodeCompleteResults(this, CodeCompleter,
3666                             CodeCompletionContext::CCC_Other,
3667                             Results.data(),Results.size());
3668 }
3669 
3670 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3671   ResultBuilder Results(*this);
3672   Results.EnterNewScope();
3673   AddObjCExpressionResults(Results, false);
3674   Results.ExitScope();
3675   HandleCodeCompleteResults(this, CodeCompleter,
3676                             CodeCompletionContext::CCC_Other,
3677                             Results.data(),Results.size());
3678 }
3679 
3680 /// \brief Determine whether the addition of the given flag to an Objective-C
3681 /// property's attributes will cause a conflict.
3682 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3683   // Check if we've already added this flag.
3684   if (Attributes & NewFlag)
3685     return true;
3686 
3687   Attributes |= NewFlag;
3688 
3689   // Check for collisions with "readonly".
3690   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3691       (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3692                      ObjCDeclSpec::DQ_PR_assign |
3693                      ObjCDeclSpec::DQ_PR_copy |
3694                      ObjCDeclSpec::DQ_PR_retain)))
3695     return true;
3696 
3697   // Check for more than one of { assign, copy, retain }.
3698   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3699                                              ObjCDeclSpec::DQ_PR_copy |
3700                                              ObjCDeclSpec::DQ_PR_retain);
3701   if (AssignCopyRetMask &&
3702       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3703       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3704       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3705     return true;
3706 
3707   return false;
3708 }
3709 
3710 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
3711   if (!CodeCompleter)
3712     return;
3713 
3714   unsigned Attributes = ODS.getPropertyAttributes();
3715 
3716   typedef CodeCompletionResult Result;
3717   ResultBuilder Results(*this);
3718   Results.EnterNewScope();
3719   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
3720     Results.AddResult(CodeCompletionResult("readonly"));
3721   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
3722     Results.AddResult(CodeCompletionResult("assign"));
3723   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
3724     Results.AddResult(CodeCompletionResult("readwrite"));
3725   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
3726     Results.AddResult(CodeCompletionResult("retain"));
3727   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
3728     Results.AddResult(CodeCompletionResult("copy"));
3729   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
3730     Results.AddResult(CodeCompletionResult("nonatomic"));
3731   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
3732     CodeCompletionString *Setter = new CodeCompletionString;
3733     Setter->AddTypedTextChunk("setter");
3734     Setter->AddTextChunk(" = ");
3735     Setter->AddPlaceholderChunk("method");
3736     Results.AddResult(CodeCompletionResult(Setter));
3737   }
3738   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
3739     CodeCompletionString *Getter = new CodeCompletionString;
3740     Getter->AddTypedTextChunk("getter");
3741     Getter->AddTextChunk(" = ");
3742     Getter->AddPlaceholderChunk("method");
3743     Results.AddResult(CodeCompletionResult(Getter));
3744   }
3745   Results.ExitScope();
3746   HandleCodeCompleteResults(this, CodeCompleter,
3747                             CodeCompletionContext::CCC_Other,
3748                             Results.data(),Results.size());
3749 }
3750 
3751 /// \brief Descripts the kind of Objective-C method that we want to find
3752 /// via code completion.
3753 enum ObjCMethodKind {
3754   MK_Any, //< Any kind of method, provided it means other specified criteria.
3755   MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3756   MK_OneArgSelector //< One-argument selector.
3757 };
3758 
3759 static bool isAcceptableObjCSelector(Selector Sel,
3760                                      ObjCMethodKind WantKind,
3761                                      IdentifierInfo **SelIdents,
3762                                      unsigned NumSelIdents) {
3763   if (NumSelIdents > Sel.getNumArgs())
3764     return false;
3765 
3766   switch (WantKind) {
3767     case MK_Any:             break;
3768     case MK_ZeroArgSelector: return Sel.isUnarySelector();
3769     case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
3770   }
3771 
3772   for (unsigned I = 0; I != NumSelIdents; ++I)
3773     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3774       return false;
3775 
3776   return true;
3777 }
3778 
3779 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3780                                    ObjCMethodKind WantKind,
3781                                    IdentifierInfo **SelIdents,
3782                                    unsigned NumSelIdents) {
3783   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3784                                   NumSelIdents);
3785 }
3786 
3787 /// \brief Add all of the Objective-C methods in the given Objective-C
3788 /// container to the set of results.
3789 ///
3790 /// The container will be a class, protocol, category, or implementation of
3791 /// any of the above. This mether will recurse to include methods from
3792 /// the superclasses of classes along with their categories, protocols, and
3793 /// implementations.
3794 ///
3795 /// \param Container the container in which we'll look to find methods.
3796 ///
3797 /// \param WantInstance whether to add instance methods (only); if false, this
3798 /// routine will add factory methods (only).
3799 ///
3800 /// \param CurContext the context in which we're performing the lookup that
3801 /// finds methods.
3802 ///
3803 /// \param Results the structure into which we'll add results.
3804 static void AddObjCMethods(ObjCContainerDecl *Container,
3805                            bool WantInstanceMethods,
3806                            ObjCMethodKind WantKind,
3807                            IdentifierInfo **SelIdents,
3808                            unsigned NumSelIdents,
3809                            DeclContext *CurContext,
3810                            ResultBuilder &Results,
3811                            bool InOriginalClass = true) {
3812   typedef CodeCompletionResult Result;
3813   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3814                                        MEnd = Container->meth_end();
3815        M != MEnd; ++M) {
3816     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3817       // Check whether the selector identifiers we've been given are a
3818       // subset of the identifiers for this particular method.
3819       if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
3820         continue;
3821 
3822       Result R = Result(*M, 0);
3823       R.StartParameter = NumSelIdents;
3824       R.AllParametersAreInformative = (WantKind != MK_Any);
3825       if (!InOriginalClass)
3826         R.Priority += CCD_InBaseClass;
3827       Results.MaybeAddResult(R, CurContext);
3828     }
3829   }
3830 
3831   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3832   if (!IFace)
3833     return;
3834 
3835   // Add methods in protocols.
3836   const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3837   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3838                                             E = Protocols.end();
3839        I != E; ++I)
3840     AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
3841                    CurContext, Results, false);
3842 
3843   // Add methods in categories.
3844   for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3845        CatDecl = CatDecl->getNextClassCategory()) {
3846     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3847                    NumSelIdents, CurContext, Results, InOriginalClass);
3848 
3849     // Add a categories protocol methods.
3850     const ObjCList<ObjCProtocolDecl> &Protocols
3851       = CatDecl->getReferencedProtocols();
3852     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3853                                               E = Protocols.end();
3854          I != E; ++I)
3855       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3856                      NumSelIdents, CurContext, Results, false);
3857 
3858     // Add methods in category implementations.
3859     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
3860       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3861                      NumSelIdents, CurContext, Results, InOriginalClass);
3862   }
3863 
3864   // Add methods in superclass.
3865   if (IFace->getSuperClass())
3866     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3867                    SelIdents, NumSelIdents, CurContext, Results, false);
3868 
3869   // Add methods in our implementation, if any.
3870   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
3871     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3872                    NumSelIdents, CurContext, Results, InOriginalClass);
3873 }
3874 
3875 
3876 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
3877                                           Decl **Methods,
3878                                           unsigned NumMethods) {
3879   typedef CodeCompletionResult Result;
3880 
3881   // Try to find the interface where getters might live.
3882   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
3883   if (!Class) {
3884     if (ObjCCategoryDecl *Category
3885           = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
3886       Class = Category->getClassInterface();
3887 
3888     if (!Class)
3889       return;
3890   }
3891 
3892   // Find all of the potential getters.
3893   ResultBuilder Results(*this);
3894   Results.EnterNewScope();
3895 
3896   // FIXME: We need to do this because Objective-C methods don't get
3897   // pushed into DeclContexts early enough. Argh!
3898   for (unsigned I = 0; I != NumMethods; ++I) {
3899     if (ObjCMethodDecl *Method
3900             = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
3901       if (Method->isInstanceMethod() &&
3902           isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3903         Result R = Result(Method, 0);
3904         R.AllParametersAreInformative = true;
3905         Results.MaybeAddResult(R, CurContext);
3906       }
3907   }
3908 
3909   AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3910   Results.ExitScope();
3911   HandleCodeCompleteResults(this, CodeCompleter,
3912                             CodeCompletionContext::CCC_Other,
3913                             Results.data(),Results.size());
3914 }
3915 
3916 void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
3917                                           Decl **Methods,
3918                                           unsigned NumMethods) {
3919   typedef CodeCompletionResult Result;
3920 
3921   // Try to find the interface where setters might live.
3922   ObjCInterfaceDecl *Class
3923     = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
3924   if (!Class) {
3925     if (ObjCCategoryDecl *Category
3926           = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
3927       Class = Category->getClassInterface();
3928 
3929     if (!Class)
3930       return;
3931   }
3932 
3933   // Find all of the potential getters.
3934   ResultBuilder Results(*this);
3935   Results.EnterNewScope();
3936 
3937   // FIXME: We need to do this because Objective-C methods don't get
3938   // pushed into DeclContexts early enough. Argh!
3939   for (unsigned I = 0; I != NumMethods; ++I) {
3940     if (ObjCMethodDecl *Method
3941             = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
3942       if (Method->isInstanceMethod() &&
3943           isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3944         Result R = Result(Method, 0);
3945         R.AllParametersAreInformative = true;
3946         Results.MaybeAddResult(R, CurContext);
3947       }
3948   }
3949 
3950   AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3951 
3952   Results.ExitScope();
3953   HandleCodeCompleteResults(this, CodeCompleter,
3954                             CodeCompletionContext::CCC_Other,
3955                             Results.data(),Results.size());
3956 }
3957 
3958 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
3959   typedef CodeCompletionResult Result;
3960   ResultBuilder Results(*this);
3961   Results.EnterNewScope();
3962 
3963   // Add context-sensitive, Objective-C parameter-passing keywords.
3964   bool AddedInOut = false;
3965   if ((DS.getObjCDeclQualifier() &
3966        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
3967     Results.AddResult("in");
3968     Results.AddResult("inout");
3969     AddedInOut = true;
3970   }
3971   if ((DS.getObjCDeclQualifier() &
3972        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
3973     Results.AddResult("out");
3974     if (!AddedInOut)
3975       Results.AddResult("inout");
3976   }
3977   if ((DS.getObjCDeclQualifier() &
3978        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
3979         ObjCDeclSpec::DQ_Oneway)) == 0) {
3980      Results.AddResult("bycopy");
3981      Results.AddResult("byref");
3982      Results.AddResult("oneway");
3983   }
3984 
3985   // Add various builtin type names and specifiers.
3986   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
3987   Results.ExitScope();
3988 
3989   // Add the various type names
3990   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3991   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3992   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3993                      CodeCompleter->includeGlobals());
3994 
3995   if (CodeCompleter->includeMacros())
3996     AddMacroResults(PP, Results);
3997 
3998   HandleCodeCompleteResults(this, CodeCompleter,
3999                             CodeCompletionContext::CCC_Type,
4000                             Results.data(), Results.size());
4001 }
4002 
4003 /// \brief When we have an expression with type "id", we may assume
4004 /// that it has some more-specific class type based on knowledge of
4005 /// common uses of Objective-C. This routine returns that class type,
4006 /// or NULL if no better result could be determined.
4007 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
4008   ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
4009   if (!Msg)
4010     return 0;
4011 
4012   Selector Sel = Msg->getSelector();
4013   if (Sel.isNull())
4014     return 0;
4015 
4016   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4017   if (!Id)
4018     return 0;
4019 
4020   ObjCMethodDecl *Method = Msg->getMethodDecl();
4021   if (!Method)
4022     return 0;
4023 
4024   // Determine the class that we're sending the message to.
4025   ObjCInterfaceDecl *IFace = 0;
4026   switch (Msg->getReceiverKind()) {
4027   case ObjCMessageExpr::Class:
4028     if (const ObjCObjectType *ObjType
4029                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4030       IFace = ObjType->getInterface();
4031     break;
4032 
4033   case ObjCMessageExpr::Instance: {
4034     QualType T = Msg->getInstanceReceiver()->getType();
4035     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4036       IFace = Ptr->getInterfaceDecl();
4037     break;
4038   }
4039 
4040   case ObjCMessageExpr::SuperInstance:
4041   case ObjCMessageExpr::SuperClass:
4042     break;
4043   }
4044 
4045   if (!IFace)
4046     return 0;
4047 
4048   ObjCInterfaceDecl *Super = IFace->getSuperClass();
4049   if (Method->isInstanceMethod())
4050     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4051       .Case("retain", IFace)
4052       .Case("autorelease", IFace)
4053       .Case("copy", IFace)
4054       .Case("copyWithZone", IFace)
4055       .Case("mutableCopy", IFace)
4056       .Case("mutableCopyWithZone", IFace)
4057       .Case("awakeFromCoder", IFace)
4058       .Case("replacementObjectFromCoder", IFace)
4059       .Case("class", IFace)
4060       .Case("classForCoder", IFace)
4061       .Case("superclass", Super)
4062       .Default(0);
4063 
4064   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4065     .Case("new", IFace)
4066     .Case("alloc", IFace)
4067     .Case("allocWithZone", IFace)
4068     .Case("class", IFace)
4069     .Case("superclass", Super)
4070     .Default(0);
4071 }
4072 
4073 // Add a special completion for a message send to "super", which fills in the
4074 // most likely case of forwarding all of our arguments to the superclass
4075 // function.
4076 ///
4077 /// \param S The semantic analysis object.
4078 ///
4079 /// \param S NeedSuperKeyword Whether we need to prefix this completion with
4080 /// the "super" keyword. Otherwise, we just need to provide the arguments.
4081 ///
4082 /// \param SelIdents The identifiers in the selector that have already been
4083 /// provided as arguments for a send to "super".
4084 ///
4085 /// \param NumSelIdents The number of identifiers in \p SelIdents.
4086 ///
4087 /// \param Results The set of results to augment.
4088 ///
4089 /// \returns the Objective-C method declaration that would be invoked by
4090 /// this "super" completion. If NULL, no completion was added.
4091 static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4092                                               IdentifierInfo **SelIdents,
4093                                               unsigned NumSelIdents,
4094                                               ResultBuilder &Results) {
4095   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4096   if (!CurMethod)
4097     return 0;
4098 
4099   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4100   if (!Class)
4101     return 0;
4102 
4103   // Try to find a superclass method with the same selector.
4104   ObjCMethodDecl *SuperMethod = 0;
4105   while ((Class = Class->getSuperClass()) && !SuperMethod)
4106     SuperMethod = Class->getMethod(CurMethod->getSelector(),
4107                                    CurMethod->isInstanceMethod());
4108 
4109   if (!SuperMethod)
4110     return 0;
4111 
4112   // Check whether the superclass method has the same signature.
4113   if (CurMethod->param_size() != SuperMethod->param_size() ||
4114       CurMethod->isVariadic() != SuperMethod->isVariadic())
4115     return 0;
4116 
4117   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4118                                    CurPEnd = CurMethod->param_end(),
4119                                     SuperP = SuperMethod->param_begin();
4120        CurP != CurPEnd; ++CurP, ++SuperP) {
4121     // Make sure the parameter types are compatible.
4122     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4123                                           (*SuperP)->getType()))
4124       return 0;
4125 
4126     // Make sure we have a parameter name to forward!
4127     if (!(*CurP)->getIdentifier())
4128       return 0;
4129   }
4130 
4131   // We have a superclass method. Now, form the send-to-super completion.
4132   CodeCompletionString *Pattern = new CodeCompletionString;
4133 
4134   // Give this completion a return type.
4135   AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4136 
4137   // If we need the "super" keyword, add it (plus some spacing).
4138   if (NeedSuperKeyword) {
4139     Pattern->AddTypedTextChunk("super");
4140     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4141   }
4142 
4143   Selector Sel = CurMethod->getSelector();
4144   if (Sel.isUnarySelector()) {
4145     if (NeedSuperKeyword)
4146       Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4147     else
4148       Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4149   } else {
4150     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4151     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4152       if (I > NumSelIdents)
4153         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4154 
4155       if (I < NumSelIdents)
4156         Pattern->AddInformativeChunk(
4157                        Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4158       else if (NeedSuperKeyword || I > NumSelIdents) {
4159         Pattern->AddTextChunk(
4160                         Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4161         Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4162       } else {
4163         Pattern->AddTypedTextChunk(
4164                               Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4165         Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4166       }
4167     }
4168   }
4169 
4170   Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4171                                          SuperMethod->isInstanceMethod()
4172                                            ? CXCursor_ObjCInstanceMethodDecl
4173                                            : CXCursor_ObjCClassMethodDecl));
4174   return SuperMethod;
4175 }
4176 
4177 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
4178   typedef CodeCompletionResult Result;
4179   ResultBuilder Results(*this);
4180 
4181   // Find anything that looks like it could be a message receiver.
4182   Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
4183   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4184   Results.EnterNewScope();
4185   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4186                      CodeCompleter->includeGlobals());
4187 
4188   // If we are in an Objective-C method inside a class that has a superclass,
4189   // add "super" as an option.
4190   if (ObjCMethodDecl *Method = getCurMethodDecl())
4191     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
4192       if (Iface->getSuperClass()) {
4193         Results.AddResult(Result("super"));
4194 
4195         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4196       }
4197 
4198   Results.ExitScope();
4199 
4200   if (CodeCompleter->includeMacros())
4201     AddMacroResults(PP, Results);
4202   HandleCodeCompleteResults(this, CodeCompleter,
4203                             CodeCompletionContext::CCC_ObjCMessageReceiver,
4204                             Results.data(), Results.size());
4205 
4206 }
4207 
4208 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4209                                         IdentifierInfo **SelIdents,
4210                                         unsigned NumSelIdents) {
4211   ObjCInterfaceDecl *CDecl = 0;
4212   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4213     // Figure out which interface we're in.
4214     CDecl = CurMethod->getClassInterface();
4215     if (!CDecl)
4216       return;
4217 
4218     // Find the superclass of this class.
4219     CDecl = CDecl->getSuperClass();
4220     if (!CDecl)
4221       return;
4222 
4223     if (CurMethod->isInstanceMethod()) {
4224       // We are inside an instance method, which means that the message
4225       // send [super ...] is actually calling an instance method on the
4226       // current object. Build the super expression and handle this like
4227       // an instance method.
4228       QualType SuperTy = Context.getObjCInterfaceType(CDecl);
4229       SuperTy = Context.getObjCObjectPointerType(SuperTy);
4230       ExprResult Super
4231         = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
4232       return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
4233                                              SelIdents, NumSelIdents,
4234                                              /*IsSuper=*/true);
4235     }
4236 
4237     // Fall through to send to the superclass in CDecl.
4238   } else {
4239     // "super" may be the name of a type or variable. Figure out which
4240     // it is.
4241     IdentifierInfo *Super = &Context.Idents.get("super");
4242     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4243                                      LookupOrdinaryName);
4244     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4245       // "super" names an interface. Use it.
4246     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
4247       if (const ObjCObjectType *Iface
4248             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4249         CDecl = Iface->getInterface();
4250     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4251       // "super" names an unresolved type; we can't be more specific.
4252     } else {
4253       // Assume that "super" names some kind of value and parse that way.
4254       CXXScopeSpec SS;
4255       UnqualifiedId id;
4256       id.setIdentifier(Super, SuperLoc);
4257       ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
4258       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
4259                                              SelIdents, NumSelIdents);
4260     }
4261 
4262     // Fall through
4263   }
4264 
4265   ParsedType Receiver;
4266   if (CDecl)
4267     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
4268   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
4269                                       NumSelIdents, /*IsSuper=*/true);
4270 }
4271 
4272 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4273                                         IdentifierInfo **SelIdents,
4274                                         unsigned NumSelIdents) {
4275   CodeCompleteObjCClassMessage(S, Receiver, SelIdents, NumSelIdents, false);
4276 }
4277 
4278 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4279                                         IdentifierInfo **SelIdents,
4280                                         unsigned NumSelIdents,
4281                                         bool IsSuper) {
4282   typedef CodeCompletionResult Result;
4283   ObjCInterfaceDecl *CDecl = 0;
4284 
4285   // If the given name refers to an interface type, retrieve the
4286   // corresponding declaration.
4287   if (Receiver) {
4288     QualType T = GetTypeFromParser(Receiver, 0);
4289     if (!T.isNull())
4290       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4291         CDecl = Interface->getInterface();
4292   }
4293 
4294   // Add all of the factory methods in this Objective-C class, its protocols,
4295   // superclasses, categories, implementation, etc.
4296   ResultBuilder Results(*this);
4297   Results.EnterNewScope();
4298 
4299   // If this is a send-to-super, try to add the special "super" send
4300   // completion.
4301   if (IsSuper) {
4302     if (ObjCMethodDecl *SuperMethod
4303           = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4304                                    Results))
4305       Results.Ignore(SuperMethod);
4306   }
4307 
4308   // If we're inside an Objective-C method definition, prefer its selector to
4309   // others.
4310   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4311     Results.setPreferredSelector(CurMethod->getSelector());
4312 
4313   if (CDecl)
4314     AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
4315                    Results);
4316   else {
4317     // We're messaging "id" as a type; provide all class/factory methods.
4318 
4319     // If we have an external source, load the entire class method
4320     // pool from the AST file.
4321     if (ExternalSource) {
4322       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4323            I != N; ++I) {
4324         Selector Sel = ExternalSource->GetExternalSelector(I);
4325         if (Sel.isNull() || MethodPool.count(Sel))
4326           continue;
4327 
4328         ReadMethodPool(Sel);
4329       }
4330     }
4331 
4332     for (GlobalMethodPool::iterator M = MethodPool.begin(),
4333                                     MEnd = MethodPool.end();
4334          M != MEnd; ++M) {
4335       for (ObjCMethodList *MethList = &M->second.second;
4336            MethList && MethList->Method;
4337            MethList = MethList->Next) {
4338         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4339                                     NumSelIdents))
4340           continue;
4341 
4342         Result R(MethList->Method, 0);
4343         R.StartParameter = NumSelIdents;
4344         R.AllParametersAreInformative = false;
4345         Results.MaybeAddResult(R, CurContext);
4346       }
4347     }
4348   }
4349 
4350   Results.ExitScope();
4351   HandleCodeCompleteResults(this, CodeCompleter,
4352                             CodeCompletionContext::CCC_Other,
4353                             Results.data(), Results.size());
4354 }
4355 
4356 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4357                                            IdentifierInfo **SelIdents,
4358                                            unsigned NumSelIdents) {
4359   CodeCompleteObjCInstanceMessage(S, Receiver, SelIdents, NumSelIdents, false);
4360 }
4361 
4362 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4363                                            IdentifierInfo **SelIdents,
4364                                            unsigned NumSelIdents,
4365                                            bool IsSuper) {
4366   typedef CodeCompletionResult Result;
4367 
4368   Expr *RecExpr = static_cast<Expr *>(Receiver);
4369 
4370   // If necessary, apply function/array conversion to the receiver.
4371   // C99 6.7.5.3p[7,8].
4372   DefaultFunctionArrayLvalueConversion(RecExpr);
4373   QualType ReceiverType = RecExpr->getType();
4374 
4375   // Build the set of methods we can see.
4376   ResultBuilder Results(*this);
4377   Results.EnterNewScope();
4378 
4379   // If this is a send-to-super, try to add the special "super" send
4380   // completion.
4381   if (IsSuper) {
4382     if (ObjCMethodDecl *SuperMethod
4383           = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4384                                    Results))
4385       Results.Ignore(SuperMethod);
4386   }
4387 
4388   // If we're inside an Objective-C method definition, prefer its selector to
4389   // others.
4390   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4391     Results.setPreferredSelector(CurMethod->getSelector());
4392 
4393   // If we're messaging an expression with type "id" or "Class", check
4394   // whether we know something special about the receiver that allows
4395   // us to assume a more-specific receiver type.
4396   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4397     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4398       ReceiverType = Context.getObjCObjectPointerType(
4399                                           Context.getObjCInterfaceType(IFace));
4400 
4401   // Handle messages to Class. This really isn't a message to an instance
4402   // method, so we treat it the same way we would treat a message send to a
4403   // class method.
4404   if (ReceiverType->isObjCClassType() ||
4405       ReceiverType->isObjCQualifiedClassType()) {
4406     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4407       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
4408         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
4409                        CurContext, Results);
4410     }
4411   }
4412   // Handle messages to a qualified ID ("id<foo>").
4413   else if (const ObjCObjectPointerType *QualID
4414              = ReceiverType->getAsObjCQualifiedIdType()) {
4415     // Search protocols for instance methods.
4416     for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4417                                               E = QualID->qual_end();
4418          I != E; ++I)
4419       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4420                      Results);
4421   }
4422   // Handle messages to a pointer to interface type.
4423   else if (const ObjCObjectPointerType *IFacePtr
4424                               = ReceiverType->getAsObjCInterfacePointerType()) {
4425     // Search the class, its superclasses, etc., for instance methods.
4426     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
4427                    NumSelIdents, CurContext, Results);
4428 
4429     // Search protocols for instance methods.
4430     for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4431          E = IFacePtr->qual_end();
4432          I != E; ++I)
4433       AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4434                      Results);
4435   }
4436   // Handle messages to "id".
4437   else if (ReceiverType->isObjCIdType()) {
4438     // We're messaging "id", so provide all instance methods we know
4439     // about as code-completion results.
4440 
4441     // If we have an external source, load the entire class method
4442     // pool from the AST file.
4443     if (ExternalSource) {
4444       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4445            I != N; ++I) {
4446         Selector Sel = ExternalSource->GetExternalSelector(I);
4447         if (Sel.isNull() || MethodPool.count(Sel))
4448           continue;
4449 
4450         ReadMethodPool(Sel);
4451       }
4452     }
4453 
4454     for (GlobalMethodPool::iterator M = MethodPool.begin(),
4455                                     MEnd = MethodPool.end();
4456          M != MEnd; ++M) {
4457       for (ObjCMethodList *MethList = &M->second.first;
4458            MethList && MethList->Method;
4459            MethList = MethList->Next) {
4460         if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4461                                     NumSelIdents))
4462           continue;
4463 
4464         Result R(MethList->Method, 0);
4465         R.StartParameter = NumSelIdents;
4466         R.AllParametersAreInformative = false;
4467         Results.MaybeAddResult(R, CurContext);
4468       }
4469     }
4470   }
4471 
4472   Results.ExitScope();
4473   HandleCodeCompleteResults(this, CodeCompleter,
4474                             CodeCompletionContext::CCC_Other,
4475                             Results.data(),Results.size());
4476 }
4477 
4478 void Sema::CodeCompleteObjCForCollection(Scope *S,
4479                                          DeclGroupPtrTy IterationVar) {
4480   CodeCompleteExpressionData Data;
4481   Data.ObjCCollection = true;
4482 
4483   if (IterationVar.getAsOpaquePtr()) {
4484     DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4485     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4486       if (*I)
4487         Data.IgnoreDecls.push_back(*I);
4488     }
4489   }
4490 
4491   CodeCompleteExpression(S, Data);
4492 }
4493 
4494 void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4495                                     unsigned NumSelIdents) {
4496   // If we have an external source, load the entire class method
4497   // pool from the AST file.
4498   if (ExternalSource) {
4499     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4500          I != N; ++I) {
4501       Selector Sel = ExternalSource->GetExternalSelector(I);
4502       if (Sel.isNull() || MethodPool.count(Sel))
4503         continue;
4504 
4505       ReadMethodPool(Sel);
4506     }
4507   }
4508 
4509   ResultBuilder Results(*this);
4510   Results.EnterNewScope();
4511   for (GlobalMethodPool::iterator M = MethodPool.begin(),
4512                                MEnd = MethodPool.end();
4513        M != MEnd; ++M) {
4514 
4515     Selector Sel = M->first;
4516     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4517       continue;
4518 
4519     CodeCompletionString *Pattern = new CodeCompletionString;
4520     if (Sel.isUnarySelector()) {
4521       Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4522       Results.AddResult(Pattern);
4523       continue;
4524     }
4525 
4526     std::string Accumulator;
4527     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
4528       if (I == NumSelIdents) {
4529         if (!Accumulator.empty()) {
4530           Pattern->AddInformativeChunk(Accumulator);
4531           Accumulator.clear();
4532         }
4533       }
4534 
4535       Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4536       Accumulator += ':';
4537     }
4538     Pattern->AddTypedTextChunk(Accumulator);
4539     Results.AddResult(Pattern);
4540   }
4541   Results.ExitScope();
4542 
4543   HandleCodeCompleteResults(this, CodeCompleter,
4544                             CodeCompletionContext::CCC_SelectorName,
4545                             Results.data(), Results.size());
4546 }
4547 
4548 /// \brief Add all of the protocol declarations that we find in the given
4549 /// (translation unit) context.
4550 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
4551                                bool OnlyForwardDeclarations,
4552                                ResultBuilder &Results) {
4553   typedef CodeCompletionResult Result;
4554 
4555   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4556                                DEnd = Ctx->decls_end();
4557        D != DEnd; ++D) {
4558     // Record any protocols we find.
4559     if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
4560       if (!OnlyForwardDeclarations || Proto->isForwardDecl())
4561         Results.AddResult(Result(Proto, 0), CurContext, 0, false);
4562 
4563     // Record any forward-declared protocols we find.
4564     if (ObjCForwardProtocolDecl *Forward
4565           = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4566       for (ObjCForwardProtocolDecl::protocol_iterator
4567              P = Forward->protocol_begin(),
4568              PEnd = Forward->protocol_end();
4569            P != PEnd; ++P)
4570         if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
4571           Results.AddResult(Result(*P, 0), CurContext, 0, false);
4572     }
4573   }
4574 }
4575 
4576 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4577                                               unsigned NumProtocols) {
4578   ResultBuilder Results(*this);
4579   Results.EnterNewScope();
4580 
4581   // Tell the result set to ignore all of the protocols we have
4582   // already seen.
4583   for (unsigned I = 0; I != NumProtocols; ++I)
4584     if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4585                                                     Protocols[I].second))
4586       Results.Ignore(Protocol);
4587 
4588   // Add all protocols.
4589   AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4590                      Results);
4591 
4592   Results.ExitScope();
4593   HandleCodeCompleteResults(this, CodeCompleter,
4594                             CodeCompletionContext::CCC_ObjCProtocolName,
4595                             Results.data(),Results.size());
4596 }
4597 
4598 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4599   ResultBuilder Results(*this);
4600   Results.EnterNewScope();
4601 
4602   // Add all protocols.
4603   AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4604                      Results);
4605 
4606   Results.ExitScope();
4607   HandleCodeCompleteResults(this, CodeCompleter,
4608                             CodeCompletionContext::CCC_ObjCProtocolName,
4609                             Results.data(),Results.size());
4610 }
4611 
4612 /// \brief Add all of the Objective-C interface declarations that we find in
4613 /// the given (translation unit) context.
4614 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4615                                 bool OnlyForwardDeclarations,
4616                                 bool OnlyUnimplemented,
4617                                 ResultBuilder &Results) {
4618   typedef CodeCompletionResult Result;
4619 
4620   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4621                                DEnd = Ctx->decls_end();
4622        D != DEnd; ++D) {
4623     // Record any interfaces we find.
4624     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4625       if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4626           (!OnlyUnimplemented || !Class->getImplementation()))
4627         Results.AddResult(Result(Class, 0), CurContext, 0, false);
4628 
4629     // Record any forward-declared interfaces we find.
4630     if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4631       for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
4632            C != CEnd; ++C)
4633         if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4634             (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4635           Results.AddResult(Result(C->getInterface(), 0), CurContext,
4636                             0, false);
4637     }
4638   }
4639 }
4640 
4641 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
4642   ResultBuilder Results(*this);
4643   Results.EnterNewScope();
4644 
4645   // Add all classes.
4646   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4647                       false, Results);
4648 
4649   Results.ExitScope();
4650   HandleCodeCompleteResults(this, CodeCompleter,
4651                             CodeCompletionContext::CCC_Other,
4652                             Results.data(),Results.size());
4653 }
4654 
4655 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4656                                       SourceLocation ClassNameLoc) {
4657   ResultBuilder Results(*this);
4658   Results.EnterNewScope();
4659 
4660   // Make sure that we ignore the class we're currently defining.
4661   NamedDecl *CurClass
4662     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
4663   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
4664     Results.Ignore(CurClass);
4665 
4666   // Add all classes.
4667   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4668                       false, Results);
4669 
4670   Results.ExitScope();
4671   HandleCodeCompleteResults(this, CodeCompleter,
4672                             CodeCompletionContext::CCC_Other,
4673                             Results.data(),Results.size());
4674 }
4675 
4676 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
4677   ResultBuilder Results(*this);
4678   Results.EnterNewScope();
4679 
4680   // Add all unimplemented classes.
4681   AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4682                       true, Results);
4683 
4684   Results.ExitScope();
4685   HandleCodeCompleteResults(this, CodeCompleter,
4686                             CodeCompletionContext::CCC_Other,
4687                             Results.data(),Results.size());
4688 }
4689 
4690 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
4691                                              IdentifierInfo *ClassName,
4692                                              SourceLocation ClassNameLoc) {
4693   typedef CodeCompletionResult Result;
4694 
4695   ResultBuilder Results(*this);
4696 
4697   // Ignore any categories we find that have already been implemented by this
4698   // interface.
4699   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4700   NamedDecl *CurClass
4701     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
4702   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
4703     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4704          Category = Category->getNextClassCategory())
4705       CategoryNames.insert(Category->getIdentifier());
4706 
4707   // Add all of the categories we know about.
4708   Results.EnterNewScope();
4709   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4710   for (DeclContext::decl_iterator D = TU->decls_begin(),
4711                                DEnd = TU->decls_end();
4712        D != DEnd; ++D)
4713     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
4714       if (CategoryNames.insert(Category->getIdentifier()))
4715         Results.AddResult(Result(Category, 0), CurContext, 0, false);
4716   Results.ExitScope();
4717 
4718   HandleCodeCompleteResults(this, CodeCompleter,
4719                             CodeCompletionContext::CCC_Other,
4720                             Results.data(),Results.size());
4721 }
4722 
4723 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
4724                                                   IdentifierInfo *ClassName,
4725                                                   SourceLocation ClassNameLoc) {
4726   typedef CodeCompletionResult Result;
4727 
4728   // Find the corresponding interface. If we couldn't find the interface, the
4729   // program itself is ill-formed. However, we'll try to be helpful still by
4730   // providing the list of all of the categories we know about.
4731   NamedDecl *CurClass
4732     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
4733   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
4734   if (!Class)
4735     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
4736 
4737   ResultBuilder Results(*this);
4738 
4739   // Add all of the categories that have have corresponding interface
4740   // declarations in this class and any of its superclasses, except for
4741   // already-implemented categories in the class itself.
4742   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4743   Results.EnterNewScope();
4744   bool IgnoreImplemented = true;
4745   while (Class) {
4746     for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4747          Category = Category->getNextClassCategory())
4748       if ((!IgnoreImplemented || !Category->getImplementation()) &&
4749           CategoryNames.insert(Category->getIdentifier()))
4750         Results.AddResult(Result(Category, 0), CurContext, 0, false);
4751 
4752     Class = Class->getSuperClass();
4753     IgnoreImplemented = false;
4754   }
4755   Results.ExitScope();
4756 
4757   HandleCodeCompleteResults(this, CodeCompleter,
4758                             CodeCompletionContext::CCC_Other,
4759                             Results.data(),Results.size());
4760 }
4761 
4762 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
4763   typedef CodeCompletionResult Result;
4764   ResultBuilder Results(*this);
4765 
4766   // Figure out where this @synthesize lives.
4767   ObjCContainerDecl *Container
4768     = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
4769   if (!Container ||
4770       (!isa<ObjCImplementationDecl>(Container) &&
4771        !isa<ObjCCategoryImplDecl>(Container)))
4772     return;
4773 
4774   // Ignore any properties that have already been implemented.
4775   for (DeclContext::decl_iterator D = Container->decls_begin(),
4776                                DEnd = Container->decls_end();
4777        D != DEnd; ++D)
4778     if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4779       Results.Ignore(PropertyImpl->getPropertyDecl());
4780 
4781   // Add any properties that we find.
4782   Results.EnterNewScope();
4783   if (ObjCImplementationDecl *ClassImpl
4784         = dyn_cast<ObjCImplementationDecl>(Container))
4785     AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4786                       Results);
4787   else
4788     AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4789                       false, CurContext, Results);
4790   Results.ExitScope();
4791 
4792   HandleCodeCompleteResults(this, CodeCompleter,
4793                             CodeCompletionContext::CCC_Other,
4794                             Results.data(),Results.size());
4795 }
4796 
4797 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4798                                                   IdentifierInfo *PropertyName,
4799                                                   Decl *ObjCImpDecl) {
4800   typedef CodeCompletionResult Result;
4801   ResultBuilder Results(*this);
4802 
4803   // Figure out where this @synthesize lives.
4804   ObjCContainerDecl *Container
4805     = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
4806   if (!Container ||
4807       (!isa<ObjCImplementationDecl>(Container) &&
4808        !isa<ObjCCategoryImplDecl>(Container)))
4809     return;
4810 
4811   // Figure out which interface we're looking into.
4812   ObjCInterfaceDecl *Class = 0;
4813   if (ObjCImplementationDecl *ClassImpl
4814                                  = dyn_cast<ObjCImplementationDecl>(Container))
4815     Class = ClassImpl->getClassInterface();
4816   else
4817     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4818                                                           ->getClassInterface();
4819 
4820   // Add all of the instance variables in this class and its superclasses.
4821   Results.EnterNewScope();
4822   for(; Class; Class = Class->getSuperClass()) {
4823     // FIXME: We could screen the type of each ivar for compatibility with
4824     // the property, but is that being too paternal?
4825     for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4826                                        IVarEnd = Class->ivar_end();
4827          IVar != IVarEnd; ++IVar)
4828       Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
4829   }
4830   Results.ExitScope();
4831 
4832   HandleCodeCompleteResults(this, CodeCompleter,
4833                             CodeCompletionContext::CCC_Other,
4834                             Results.data(),Results.size());
4835 }
4836 
4837 // Mapping from selectors to the methods that implement that selector, along
4838 // with the "in original class" flag.
4839 typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
4840   KnownMethodsMap;
4841 
4842 /// \brief Find all of the methods that reside in the given container
4843 /// (and its superclasses, protocols, etc.) that meet the given
4844 /// criteria. Insert those methods into the map of known methods,
4845 /// indexed by selector so they can be easily found.
4846 static void FindImplementableMethods(ASTContext &Context,
4847                                      ObjCContainerDecl *Container,
4848                                      bool WantInstanceMethods,
4849                                      QualType ReturnType,
4850                                      bool IsInImplementation,
4851                                      KnownMethodsMap &KnownMethods,
4852                                      bool InOriginalClass = true) {
4853   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4854     // Recurse into protocols.
4855     const ObjCList<ObjCProtocolDecl> &Protocols
4856       = IFace->getReferencedProtocols();
4857     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4858            E = Protocols.end();
4859          I != E; ++I)
4860       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4861                                IsInImplementation, KnownMethods,
4862                                InOriginalClass);
4863 
4864     // If we're not in the implementation of a class, also visit the
4865     // superclass.
4866     if (!IsInImplementation && IFace->getSuperClass())
4867       FindImplementableMethods(Context, IFace->getSuperClass(),
4868                                WantInstanceMethods, ReturnType,
4869                                IsInImplementation, KnownMethods,
4870                                false);
4871 
4872     // Add methods from any class extensions (but not from categories;
4873     // those should go into category implementations).
4874     for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4875          Cat = Cat->getNextClassExtension())
4876       FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4877                                WantInstanceMethods, ReturnType,
4878                                IsInImplementation, KnownMethods,
4879                                InOriginalClass);
4880   }
4881 
4882   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4883     // Recurse into protocols.
4884     const ObjCList<ObjCProtocolDecl> &Protocols
4885       = Category->getReferencedProtocols();
4886     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4887            E = Protocols.end();
4888          I != E; ++I)
4889       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4890                                IsInImplementation, KnownMethods,
4891                                InOriginalClass);
4892   }
4893 
4894   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4895     // Recurse into protocols.
4896     const ObjCList<ObjCProtocolDecl> &Protocols
4897       = Protocol->getReferencedProtocols();
4898     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4899            E = Protocols.end();
4900          I != E; ++I)
4901       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4902                                IsInImplementation, KnownMethods, false);
4903   }
4904 
4905   // Add methods in this container. This operation occurs last because
4906   // we want the methods from this container to override any methods
4907   // we've previously seen with the same selector.
4908   for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4909                                        MEnd = Container->meth_end();
4910        M != MEnd; ++M) {
4911     if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4912       if (!ReturnType.isNull() &&
4913           !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4914         continue;
4915 
4916       KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
4917     }
4918   }
4919 }
4920 
4921 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4922                                       bool IsInstanceMethod,
4923                                       ParsedType ReturnTy,
4924                                       Decl *IDecl) {
4925   // Determine the return type of the method we're declaring, if
4926   // provided.
4927   QualType ReturnType = GetTypeFromParser(ReturnTy);
4928 
4929   // Determine where we should start searching for methods, and where we
4930   ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4931   bool IsInImplementation = false;
4932   if (Decl *D = IDecl) {
4933     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4934       SearchDecl = Impl->getClassInterface();
4935       CurrentDecl = Impl;
4936       IsInImplementation = true;
4937     } else if (ObjCCategoryImplDecl *CatImpl
4938                                        = dyn_cast<ObjCCategoryImplDecl>(D)) {
4939       SearchDecl = CatImpl->getCategoryDecl();
4940       CurrentDecl = CatImpl;
4941       IsInImplementation = true;
4942     } else {
4943       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4944       CurrentDecl = SearchDecl;
4945     }
4946   }
4947 
4948   if (!SearchDecl && S) {
4949     if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4950       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4951       CurrentDecl = SearchDecl;
4952     }
4953   }
4954 
4955   if (!SearchDecl || !CurrentDecl) {
4956     HandleCodeCompleteResults(this, CodeCompleter,
4957                               CodeCompletionContext::CCC_Other,
4958                               0, 0);
4959     return;
4960   }
4961 
4962   // Find all of the methods that we could declare/implement here.
4963   KnownMethodsMap KnownMethods;
4964   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4965                            ReturnType, IsInImplementation, KnownMethods);
4966 
4967   // Erase any methods that have already been declared or
4968   // implemented here.
4969   for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4970                                        MEnd = CurrentDecl->meth_end();
4971        M != MEnd; ++M) {
4972     if ((*M)->isInstanceMethod() != IsInstanceMethod)
4973       continue;
4974 
4975     KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4976     if (Pos != KnownMethods.end())
4977       KnownMethods.erase(Pos);
4978   }
4979 
4980   // Add declarations or definitions for each of the known methods.
4981   typedef CodeCompletionResult Result;
4982   ResultBuilder Results(*this);
4983   Results.EnterNewScope();
4984   PrintingPolicy Policy(Context.PrintingPolicy);
4985   Policy.AnonymousTagLocations = false;
4986   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4987                               MEnd = KnownMethods.end();
4988        M != MEnd; ++M) {
4989     ObjCMethodDecl *Method = M->second.first;
4990     CodeCompletionString *Pattern = new CodeCompletionString;
4991 
4992     // If the result type was not already provided, add it to the
4993     // pattern as (type).
4994     if (ReturnType.isNull()) {
4995       std::string TypeStr;
4996       Method->getResultType().getAsStringInternal(TypeStr, Policy);
4997       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4998       Pattern->AddTextChunk(TypeStr);
4999       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5000     }
5001 
5002     Selector Sel = Method->getSelector();
5003 
5004     // Add the first part of the selector to the pattern.
5005     Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
5006 
5007     // Add parameters to the pattern.
5008     unsigned I = 0;
5009     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5010                                      PEnd = Method->param_end();
5011          P != PEnd; (void)++P, ++I) {
5012       // Add the part of the selector name.
5013       if (I == 0)
5014         Pattern->AddChunk(CodeCompletionString::CK_Colon);
5015       else if (I < Sel.getNumArgs()) {
5016         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5017         Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
5018         Pattern->AddChunk(CodeCompletionString::CK_Colon);
5019       } else
5020         break;
5021 
5022       // Add the parameter type.
5023       std::string TypeStr;
5024       (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
5025       Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5026       Pattern->AddTextChunk(TypeStr);
5027       Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5028 
5029       if (IdentifierInfo *Id = (*P)->getIdentifier())
5030         Pattern->AddTextChunk(Id->getName());
5031     }
5032 
5033     if (Method->isVariadic()) {
5034       if (Method->param_size() > 0)
5035         Pattern->AddChunk(CodeCompletionString::CK_Comma);
5036       Pattern->AddTextChunk("...");
5037     }
5038 
5039     if (IsInImplementation && Results.includeCodePatterns()) {
5040       // We will be defining the method here, so add a compound statement.
5041       Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5042       Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
5043       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5044       if (!Method->getResultType()->isVoidType()) {
5045         // If the result type is not void, add a return clause.
5046         Pattern->AddTextChunk("return");
5047         Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5048         Pattern->AddPlaceholderChunk("expression");
5049         Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
5050       } else
5051         Pattern->AddPlaceholderChunk("statements");
5052 
5053       Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5054       Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
5055     }
5056 
5057     unsigned Priority = CCP_CodePattern;
5058     if (!M->second.second)
5059       Priority += CCD_InBaseClass;
5060 
5061     Results.AddResult(Result(Pattern, Priority,
5062                              Method->isInstanceMethod()
5063                                ? CXCursor_ObjCInstanceMethodDecl
5064                                : CXCursor_ObjCClassMethodDecl));
5065   }
5066 
5067   Results.ExitScope();
5068 
5069   HandleCodeCompleteResults(this, CodeCompleter,
5070                             CodeCompletionContext::CCC_Other,
5071                             Results.data(),Results.size());
5072 }
5073 
5074 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5075                                               bool IsInstanceMethod,
5076                                               bool AtParameterName,
5077                                               ParsedType ReturnTy,
5078                                               IdentifierInfo **SelIdents,
5079                                               unsigned NumSelIdents) {
5080   // If we have an external source, load the entire class method
5081   // pool from the AST file.
5082   if (ExternalSource) {
5083     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5084          I != N; ++I) {
5085       Selector Sel = ExternalSource->GetExternalSelector(I);
5086       if (Sel.isNull() || MethodPool.count(Sel))
5087         continue;
5088 
5089       ReadMethodPool(Sel);
5090     }
5091   }
5092 
5093   // Build the set of methods we can see.
5094   typedef CodeCompletionResult Result;
5095   ResultBuilder Results(*this);
5096 
5097   if (ReturnTy)
5098     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
5099 
5100   Results.EnterNewScope();
5101   for (GlobalMethodPool::iterator M = MethodPool.begin(),
5102                                   MEnd = MethodPool.end();
5103        M != MEnd; ++M) {
5104     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5105                                                        &M->second.second;
5106          MethList && MethList->Method;
5107          MethList = MethList->Next) {
5108       if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5109                                   NumSelIdents))
5110         continue;
5111 
5112       if (AtParameterName) {
5113         // Suggest parameter names we've seen before.
5114         if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5115           ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5116           if (Param->getIdentifier()) {
5117             CodeCompletionString *Pattern = new CodeCompletionString;
5118             Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5119             Results.AddResult(Pattern);
5120           }
5121         }
5122 
5123         continue;
5124       }
5125 
5126       Result R(MethList->Method, 0);
5127       R.StartParameter = NumSelIdents;
5128       R.AllParametersAreInformative = false;
5129       R.DeclaringEntity = true;
5130       Results.MaybeAddResult(R, CurContext);
5131     }
5132   }
5133 
5134   Results.ExitScope();
5135   HandleCodeCompleteResults(this, CodeCompleter,
5136                             CodeCompletionContext::CCC_Other,
5137                             Results.data(),Results.size());
5138 }
5139 
5140 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
5141   ResultBuilder Results(*this);
5142   Results.EnterNewScope();
5143 
5144   // #if <condition>
5145   CodeCompletionString *Pattern = new CodeCompletionString;
5146   Pattern->AddTypedTextChunk("if");
5147   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5148   Pattern->AddPlaceholderChunk("condition");
5149   Results.AddResult(Pattern);
5150 
5151   // #ifdef <macro>
5152   Pattern = new CodeCompletionString;
5153   Pattern->AddTypedTextChunk("ifdef");
5154   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5155   Pattern->AddPlaceholderChunk("macro");
5156   Results.AddResult(Pattern);
5157 
5158   // #ifndef <macro>
5159   Pattern = new CodeCompletionString;
5160   Pattern->AddTypedTextChunk("ifndef");
5161   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5162   Pattern->AddPlaceholderChunk("macro");
5163   Results.AddResult(Pattern);
5164 
5165   if (InConditional) {
5166     // #elif <condition>
5167     Pattern = new CodeCompletionString;
5168     Pattern->AddTypedTextChunk("elif");
5169     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5170     Pattern->AddPlaceholderChunk("condition");
5171     Results.AddResult(Pattern);
5172 
5173     // #else
5174     Pattern = new CodeCompletionString;
5175     Pattern->AddTypedTextChunk("else");
5176     Results.AddResult(Pattern);
5177 
5178     // #endif
5179     Pattern = new CodeCompletionString;
5180     Pattern->AddTypedTextChunk("endif");
5181     Results.AddResult(Pattern);
5182   }
5183 
5184   // #include "header"
5185   Pattern = new CodeCompletionString;
5186   Pattern->AddTypedTextChunk("include");
5187   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5188   Pattern->AddTextChunk("\"");
5189   Pattern->AddPlaceholderChunk("header");
5190   Pattern->AddTextChunk("\"");
5191   Results.AddResult(Pattern);
5192 
5193   // #include <header>
5194   Pattern = new CodeCompletionString;
5195   Pattern->AddTypedTextChunk("include");
5196   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5197   Pattern->AddTextChunk("<");
5198   Pattern->AddPlaceholderChunk("header");
5199   Pattern->AddTextChunk(">");
5200   Results.AddResult(Pattern);
5201 
5202   // #define <macro>
5203   Pattern = new CodeCompletionString;
5204   Pattern->AddTypedTextChunk("define");
5205   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5206   Pattern->AddPlaceholderChunk("macro");
5207   Results.AddResult(Pattern);
5208 
5209   // #define <macro>(<args>)
5210   Pattern = new CodeCompletionString;
5211   Pattern->AddTypedTextChunk("define");
5212   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5213   Pattern->AddPlaceholderChunk("macro");
5214   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5215   Pattern->AddPlaceholderChunk("args");
5216   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5217   Results.AddResult(Pattern);
5218 
5219   // #undef <macro>
5220   Pattern = new CodeCompletionString;
5221   Pattern->AddTypedTextChunk("undef");
5222   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5223   Pattern->AddPlaceholderChunk("macro");
5224   Results.AddResult(Pattern);
5225 
5226   // #line <number>
5227   Pattern = new CodeCompletionString;
5228   Pattern->AddTypedTextChunk("line");
5229   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5230   Pattern->AddPlaceholderChunk("number");
5231   Results.AddResult(Pattern);
5232 
5233   // #line <number> "filename"
5234   Pattern = new CodeCompletionString;
5235   Pattern->AddTypedTextChunk("line");
5236   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5237   Pattern->AddPlaceholderChunk("number");
5238   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5239   Pattern->AddTextChunk("\"");
5240   Pattern->AddPlaceholderChunk("filename");
5241   Pattern->AddTextChunk("\"");
5242   Results.AddResult(Pattern);
5243 
5244   // #error <message>
5245   Pattern = new CodeCompletionString;
5246   Pattern->AddTypedTextChunk("error");
5247   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5248   Pattern->AddPlaceholderChunk("message");
5249   Results.AddResult(Pattern);
5250 
5251   // #pragma <arguments>
5252   Pattern = new CodeCompletionString;
5253   Pattern->AddTypedTextChunk("pragma");
5254   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5255   Pattern->AddPlaceholderChunk("arguments");
5256   Results.AddResult(Pattern);
5257 
5258   if (getLangOptions().ObjC1) {
5259     // #import "header"
5260     Pattern = new CodeCompletionString;
5261     Pattern->AddTypedTextChunk("import");
5262     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5263     Pattern->AddTextChunk("\"");
5264     Pattern->AddPlaceholderChunk("header");
5265     Pattern->AddTextChunk("\"");
5266     Results.AddResult(Pattern);
5267 
5268     // #import <header>
5269     Pattern = new CodeCompletionString;
5270     Pattern->AddTypedTextChunk("import");
5271     Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5272     Pattern->AddTextChunk("<");
5273     Pattern->AddPlaceholderChunk("header");
5274     Pattern->AddTextChunk(">");
5275     Results.AddResult(Pattern);
5276   }
5277 
5278   // #include_next "header"
5279   Pattern = new CodeCompletionString;
5280   Pattern->AddTypedTextChunk("include_next");
5281   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5282   Pattern->AddTextChunk("\"");
5283   Pattern->AddPlaceholderChunk("header");
5284   Pattern->AddTextChunk("\"");
5285   Results.AddResult(Pattern);
5286 
5287   // #include_next <header>
5288   Pattern = new CodeCompletionString;
5289   Pattern->AddTypedTextChunk("include_next");
5290   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5291   Pattern->AddTextChunk("<");
5292   Pattern->AddPlaceholderChunk("header");
5293   Pattern->AddTextChunk(">");
5294   Results.AddResult(Pattern);
5295 
5296   // #warning <message>
5297   Pattern = new CodeCompletionString;
5298   Pattern->AddTypedTextChunk("warning");
5299   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5300   Pattern->AddPlaceholderChunk("message");
5301   Results.AddResult(Pattern);
5302 
5303   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5304   // completions for them. And __include_macros is a Clang-internal extension
5305   // that we don't want to encourage anyone to use.
5306 
5307   // FIXME: we don't support #assert or #unassert, so don't suggest them.
5308   Results.ExitScope();
5309 
5310   HandleCodeCompleteResults(this, CodeCompleter,
5311                             CodeCompletionContext::CCC_PreprocessorDirective,
5312                             Results.data(), Results.size());
5313 }
5314 
5315 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
5316   CodeCompleteOrdinaryName(S,
5317                            S->getFnParent()? Sema::PCC_RecoveryInFunction
5318                                            : Sema::PCC_Namespace);
5319 }
5320 
5321 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
5322   ResultBuilder Results(*this);
5323   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5324     // Add just the names of macros, not their arguments.
5325     Results.EnterNewScope();
5326     for (Preprocessor::macro_iterator M = PP.macro_begin(),
5327                                    MEnd = PP.macro_end();
5328          M != MEnd; ++M) {
5329       CodeCompletionString *Pattern = new CodeCompletionString;
5330       Pattern->AddTypedTextChunk(M->first->getName());
5331       Results.AddResult(Pattern);
5332     }
5333     Results.ExitScope();
5334   } else if (IsDefinition) {
5335     // FIXME: Can we detect when the user just wrote an include guard above?
5336   }
5337 
5338   HandleCodeCompleteResults(this, CodeCompleter,
5339                       IsDefinition? CodeCompletionContext::CCC_MacroName
5340                                   : CodeCompletionContext::CCC_MacroNameUse,
5341                             Results.data(), Results.size());
5342 }
5343 
5344 void Sema::CodeCompletePreprocessorExpression() {
5345   ResultBuilder Results(*this);
5346 
5347   if (!CodeCompleter || CodeCompleter->includeMacros())
5348     AddMacroResults(PP, Results);
5349 
5350     // defined (<macro>)
5351   Results.EnterNewScope();
5352   CodeCompletionString *Pattern = new CodeCompletionString;
5353   Pattern->AddTypedTextChunk("defined");
5354   Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5355   Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5356   Pattern->AddPlaceholderChunk("macro");
5357   Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5358   Results.AddResult(Pattern);
5359   Results.ExitScope();
5360 
5361   HandleCodeCompleteResults(this, CodeCompleter,
5362                             CodeCompletionContext::CCC_PreprocessorExpression,
5363                             Results.data(), Results.size());
5364 }
5365 
5366 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5367                                                  IdentifierInfo *Macro,
5368                                                  MacroInfo *MacroInfo,
5369                                                  unsigned Argument) {
5370   // FIXME: In the future, we could provide "overload" results, much like we
5371   // do for function calls.
5372 
5373   CodeCompleteOrdinaryName(S,
5374                            S->getFnParent()? Sema::PCC_RecoveryInFunction
5375                                            : Sema::PCC_Namespace);
5376 }
5377 
5378 void Sema::CodeCompleteNaturalLanguage() {
5379   HandleCodeCompleteResults(this, CodeCompleter,
5380                             CodeCompletionContext::CCC_NaturalLanguage,
5381                             0, 0);
5382 }
5383 
5384 void Sema::GatherGlobalCodeCompletions(
5385                  llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
5386   ResultBuilder Builder(*this);
5387 
5388   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5389     CodeCompletionDeclConsumer Consumer(Builder,
5390                                         Context.getTranslationUnitDecl());
5391     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5392                        Consumer);
5393   }
5394 
5395   if (!CodeCompleter || CodeCompleter->includeMacros())
5396     AddMacroResults(PP, Builder);
5397 
5398   Results.clear();
5399   Results.insert(Results.end(),
5400                  Builder.data(), Builder.data() + Builder.size());
5401 }
5402