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