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