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