DeclObjC.h revision 04593d0f9d84f6adf942bd66f1587e05c6a47c42
1//===--- DeclObjC.h - Classes for representing declarations -----*- 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 DeclObjC interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLOBJC_H
15#define LLVM_CLANG_AST_DECLOBJC_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/SelectorLocationsKind.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/Compiler.h"
21
22namespace clang {
23class Expr;
24class Stmt;
25class FunctionDecl;
26class RecordDecl;
27class ObjCIvarDecl;
28class ObjCMethodDecl;
29class ObjCProtocolDecl;
30class ObjCCategoryDecl;
31class ObjCPropertyDecl;
32class ObjCPropertyImplDecl;
33class CXXCtorInitializer;
34
35class ObjCListBase {
36  ObjCListBase(const ObjCListBase &) LLVM_DELETED_FUNCTION;
37  void operator=(const ObjCListBase &) LLVM_DELETED_FUNCTION;
38protected:
39  /// List is an array of pointers to objects that are not owned by this object.
40  void **List;
41  unsigned NumElts;
42
43public:
44  ObjCListBase() : List(0), NumElts(0) {}
45  unsigned size() const { return NumElts; }
46  bool empty() const { return NumElts == 0; }
47
48protected:
49  void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
50};
51
52
53/// ObjCList - This is a simple template class used to hold various lists of
54/// decls etc, which is heavily used by the ObjC front-end.  This only use case
55/// this supports is setting the list all at once and then reading elements out
56/// of it.
57template <typename T>
58class ObjCList : public ObjCListBase {
59public:
60  void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
61    ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
62  }
63
64  typedef T* const * iterator;
65  iterator begin() const { return (iterator)List; }
66  iterator end() const { return (iterator)List+NumElts; }
67
68  T* operator[](unsigned Idx) const {
69    assert(Idx < NumElts && "Invalid access");
70    return (T*)List[Idx];
71  }
72};
73
74/// \brief A list of Objective-C protocols, along with the source
75/// locations at which they were referenced.
76class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
77  SourceLocation *Locations;
78
79  using ObjCList<ObjCProtocolDecl>::set;
80
81public:
82  ObjCProtocolList() : ObjCList<ObjCProtocolDecl>(), Locations(0) { }
83
84  typedef const SourceLocation *loc_iterator;
85  loc_iterator loc_begin() const { return Locations; }
86  loc_iterator loc_end() const { return Locations + size(); }
87
88  void set(ObjCProtocolDecl* const* InList, unsigned Elts,
89           const SourceLocation *Locs, ASTContext &Ctx);
90};
91
92
93/// ObjCMethodDecl - Represents an instance or class method declaration.
94/// ObjC methods can be declared within 4 contexts: class interfaces,
95/// categories, protocols, and class implementations. While C++ member
96/// functions leverage C syntax, Objective-C method syntax is modeled after
97/// Smalltalk (using colons to specify argument types/expressions).
98/// Here are some brief examples:
99///
100/// Setter/getter instance methods:
101/// - (void)setMenu:(NSMenu *)menu;
102/// - (NSMenu *)menu;
103///
104/// Instance method that takes 2 NSView arguments:
105/// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
106///
107/// Getter class method:
108/// + (NSMenu *)defaultMenu;
109///
110/// A selector represents a unique name for a method. The selector names for
111/// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
112///
113class ObjCMethodDecl : public NamedDecl, public DeclContext {
114public:
115  enum ImplementationControl { None, Required, Optional };
116private:
117  // The conventional meaning of this method; an ObjCMethodFamily.
118  // This is not serialized; instead, it is computed on demand and
119  // cached.
120  mutable unsigned Family : ObjCMethodFamilyBitWidth;
121
122  /// instance (true) or class (false) method.
123  unsigned IsInstance : 1;
124  unsigned IsVariadic : 1;
125
126  /// True if this method is the getter or setter for an explicit property.
127  unsigned IsPropertyAccessor : 1;
128
129  // Method has a definition.
130  unsigned IsDefined : 1;
131
132  /// \brief Method redeclaration in the same interface.
133  unsigned IsRedeclaration : 1;
134
135  /// \brief Is redeclared in the same interface.
136  mutable unsigned HasRedeclaration : 1;
137
138  // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum
139  /// \@required/\@optional
140  unsigned DeclImplementation : 2;
141
142  // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
143  /// in, inout, etc.
144  unsigned objcDeclQualifier : 6;
145
146  /// \brief Indicates whether this method has a related result type.
147  unsigned RelatedResultType : 1;
148
149  /// \brief Whether the locations of the selector identifiers are in a
150  /// "standard" position, a enum SelectorLocationsKind.
151  unsigned SelLocsKind : 2;
152
153  /// \brief Whether this method overrides any other in the class hierarchy.
154  ///
155  /// A method is said to override any method in the class's
156  /// base classes, its protocols, or its categories' protocols, that has
157  /// the same selector and is of the same kind (class or instance).
158  /// A method in an implementation is not considered as overriding the same
159  /// method in the interface or its categories.
160  unsigned IsOverriding : 1;
161
162  /// \brief Indicates if the method was a definition but its body was skipped.
163  unsigned HasSkippedBody : 1;
164
165  // Result type of this method.
166  QualType MethodDeclType;
167
168  // Type source information for the result type.
169  TypeSourceInfo *ResultTInfo;
170
171  /// \brief Array of ParmVarDecls for the formal parameters of this method
172  /// and optionally followed by selector locations.
173  void *ParamsAndSelLocs;
174  unsigned NumParams;
175
176  /// List of attributes for this method declaration.
177  SourceLocation DeclEndLoc; // the location of the ';' or '{'.
178
179  // The following are only used for method definitions, null otherwise.
180  LazyDeclStmtPtr Body;
181
182  /// SelfDecl - Decl for the implicit self parameter. This is lazily
183  /// constructed by createImplicitParams.
184  ImplicitParamDecl *SelfDecl;
185  /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
186  /// constructed by createImplicitParams.
187  ImplicitParamDecl *CmdDecl;
188
189  SelectorLocationsKind getSelLocsKind() const {
190    return (SelectorLocationsKind)SelLocsKind;
191  }
192  bool hasStandardSelLocs() const {
193    return getSelLocsKind() != SelLoc_NonStandard;
194  }
195
196  /// \brief Get a pointer to the stored selector identifiers locations array.
197  /// No locations will be stored if HasStandardSelLocs is true.
198  SourceLocation *getStoredSelLocs() {
199    return reinterpret_cast<SourceLocation*>(getParams() + NumParams);
200  }
201  const SourceLocation *getStoredSelLocs() const {
202    return reinterpret_cast<const SourceLocation*>(getParams() + NumParams);
203  }
204
205  /// \brief Get a pointer to the stored selector identifiers locations array.
206  /// No locations will be stored if HasStandardSelLocs is true.
207  ParmVarDecl **getParams() {
208    return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
209  }
210  const ParmVarDecl *const *getParams() const {
211    return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
212  }
213
214  /// \brief Get the number of stored selector identifiers locations.
215  /// No locations will be stored if HasStandardSelLocs is true.
216  unsigned getNumStoredSelLocs() const {
217    if (hasStandardSelLocs())
218      return 0;
219    return getNumSelectorLocs();
220  }
221
222  void setParamsAndSelLocs(ASTContext &C,
223                           ArrayRef<ParmVarDecl*> Params,
224                           ArrayRef<SourceLocation> SelLocs);
225
226  ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
227                 Selector SelInfo, QualType T,
228                 TypeSourceInfo *ResultTInfo,
229                 DeclContext *contextDecl,
230                 bool isInstance = true,
231                 bool isVariadic = false,
232                 bool isPropertyAccessor = false,
233                 bool isImplicitlyDeclared = false,
234                 bool isDefined = false,
235                 ImplementationControl impControl = None,
236                 bool HasRelatedResultType = false)
237  : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo),
238    DeclContext(ObjCMethod), Family(InvalidObjCMethodFamily),
239    IsInstance(isInstance), IsVariadic(isVariadic),
240    IsPropertyAccessor(isPropertyAccessor),
241    IsDefined(isDefined), IsRedeclaration(0), HasRedeclaration(0),
242    DeclImplementation(impControl), objcDeclQualifier(OBJC_TQ_None),
243    RelatedResultType(HasRelatedResultType),
244    SelLocsKind(SelLoc_StandardNoSpace), IsOverriding(0), HasSkippedBody(0),
245    MethodDeclType(T), ResultTInfo(ResultTInfo),
246    ParamsAndSelLocs(0), NumParams(0),
247    DeclEndLoc(endLoc), Body(), SelfDecl(0), CmdDecl(0) {
248    setImplicit(isImplicitlyDeclared);
249  }
250
251  /// \brief A definition will return its interface declaration.
252  /// An interface declaration will return its definition.
253  /// Otherwise it will return itself.
254  virtual ObjCMethodDecl *getNextRedeclaration();
255
256public:
257  static ObjCMethodDecl *Create(ASTContext &C,
258                                SourceLocation beginLoc,
259                                SourceLocation endLoc,
260                                Selector SelInfo,
261                                QualType T,
262                                TypeSourceInfo *ResultTInfo,
263                                DeclContext *contextDecl,
264                                bool isInstance = true,
265                                bool isVariadic = false,
266                                bool isPropertyAccessor = false,
267                                bool isImplicitlyDeclared = false,
268                                bool isDefined = false,
269                                ImplementationControl impControl = None,
270                                bool HasRelatedResultType = false);
271
272  static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
273
274  virtual ObjCMethodDecl *getCanonicalDecl();
275  const ObjCMethodDecl *getCanonicalDecl() const {
276    return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
277  }
278
279  ObjCDeclQualifier getObjCDeclQualifier() const {
280    return ObjCDeclQualifier(objcDeclQualifier);
281  }
282  void setObjCDeclQualifier(ObjCDeclQualifier QV) { objcDeclQualifier = QV; }
283
284  /// \brief Determine whether this method has a result type that is related
285  /// to the message receiver's type.
286  bool hasRelatedResultType() const { return RelatedResultType; }
287
288  /// \brief Note whether this method has a related result type.
289  void SetRelatedResultType(bool RRT = true) { RelatedResultType = RRT; }
290
291  /// \brief True if this is a method redeclaration in the same interface.
292  bool isRedeclaration() const { return IsRedeclaration; }
293  void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
294
295  /// \brief Returns the location where the declarator ends. It will be
296  /// the location of ';' for a method declaration and the location of '{'
297  /// for a method definition.
298  SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
299
300  // Location information, modeled after the Stmt API.
301  SourceLocation getLocStart() const LLVM_READONLY { return getLocation(); }
302  SourceLocation getLocEnd() const LLVM_READONLY;
303  virtual SourceRange getSourceRange() const LLVM_READONLY {
304    return SourceRange(getLocation(), getLocEnd());
305  }
306
307  SourceLocation getSelectorStartLoc() const {
308    if (isImplicit())
309      return getLocStart();
310    return getSelectorLoc(0);
311  }
312  SourceLocation getSelectorLoc(unsigned Index) const {
313    assert(Index < getNumSelectorLocs() && "Index out of range!");
314    if (hasStandardSelLocs())
315      return getStandardSelectorLoc(Index, getSelector(),
316                                   getSelLocsKind() == SelLoc_StandardWithSpace,
317                      llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
318                                         NumParams),
319                                   DeclEndLoc);
320    return getStoredSelLocs()[Index];
321  }
322
323  void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
324
325  unsigned getNumSelectorLocs() const {
326    if (isImplicit())
327      return 0;
328    Selector Sel = getSelector();
329    if (Sel.isUnarySelector())
330      return 1;
331    return Sel.getNumArgs();
332  }
333
334  ObjCInterfaceDecl *getClassInterface();
335  const ObjCInterfaceDecl *getClassInterface() const {
336    return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
337  }
338
339  Selector getSelector() const { return getDeclName().getObjCSelector(); }
340
341  QualType getResultType() const { return MethodDeclType; }
342  void setResultType(QualType T) { MethodDeclType = T; }
343
344  /// \brief Determine the type of an expression that sends a message to this
345  /// function.
346  QualType getSendResultType() const {
347    return getResultType().getNonLValueExprType(getASTContext());
348  }
349
350  TypeSourceInfo *getResultTypeSourceInfo() const { return ResultTInfo; }
351  void setResultTypeSourceInfo(TypeSourceInfo *TInfo) { ResultTInfo = TInfo; }
352
353  // Iterator access to formal parameters.
354  unsigned param_size() const { return NumParams; }
355  typedef const ParmVarDecl *const *param_const_iterator;
356  typedef ParmVarDecl *const *param_iterator;
357  param_const_iterator param_begin() const { return getParams(); }
358  param_const_iterator param_end() const { return getParams() + NumParams; }
359  param_iterator param_begin() { return getParams(); }
360  param_iterator param_end() { return getParams() + NumParams; }
361  // This method returns and of the parameters which are part of the selector
362  // name mangling requirements.
363  param_const_iterator sel_param_end() const {
364    return param_begin() + getSelector().getNumArgs();
365  }
366
367  /// \brief Sets the method's parameters and selector source locations.
368  /// If the method is implicit (not coming from source) \p SelLocs is
369  /// ignored.
370  void setMethodParams(ASTContext &C,
371                       ArrayRef<ParmVarDecl*> Params,
372                       ArrayRef<SourceLocation> SelLocs =
373                           ArrayRef<SourceLocation>());
374
375  // Iterator access to parameter types.
376  typedef std::const_mem_fun_t<QualType, ParmVarDecl> deref_fun;
377  typedef llvm::mapped_iterator<param_const_iterator, deref_fun>
378      arg_type_iterator;
379
380  arg_type_iterator arg_type_begin() const {
381    return llvm::map_iterator(param_begin(), deref_fun(&ParmVarDecl::getType));
382  }
383  arg_type_iterator arg_type_end() const {
384    return llvm::map_iterator(param_end(), deref_fun(&ParmVarDecl::getType));
385  }
386
387  /// createImplicitParams - Used to lazily create the self and cmd
388  /// implict parameters. This must be called prior to using getSelfDecl()
389  /// or getCmdDecl(). The call is ignored if the implicit paramters
390  /// have already been created.
391  void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
392
393  ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
394  void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
395  ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
396  void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
397
398  /// Determines the family of this method.
399  ObjCMethodFamily getMethodFamily() const;
400
401  bool isInstanceMethod() const { return IsInstance; }
402  void setInstanceMethod(bool isInst) { IsInstance = isInst; }
403  bool isVariadic() const { return IsVariadic; }
404  void setVariadic(bool isVar) { IsVariadic = isVar; }
405
406  bool isClassMethod() const { return !IsInstance; }
407
408  bool isPropertyAccessor() const { return IsPropertyAccessor; }
409  void setPropertyAccessor(bool isAccessor) { IsPropertyAccessor = isAccessor; }
410
411  bool isDefined() const { return IsDefined; }
412  void setDefined(bool isDefined) { IsDefined = isDefined; }
413
414  /// \brief Whether this method overrides any other in the class hierarchy.
415  ///
416  /// A method is said to override any method in the class's
417  /// base classes, its protocols, or its categories' protocols, that has
418  /// the same selector and is of the same kind (class or instance).
419  /// A method in an implementation is not considered as overriding the same
420  /// method in the interface or its categories.
421  bool isOverriding() const { return IsOverriding; }
422  void setOverriding(bool isOverriding) { IsOverriding = isOverriding; }
423
424  /// \brief Return overridden methods for the given \p Method.
425  ///
426  /// An ObjC method is considered to override any method in the class's
427  /// base classes (and base's categories), its protocols, or its categories'
428  /// protocols, that has
429  /// the same selector and is of the same kind (class or instance).
430  /// A method in an implementation is not considered as overriding the same
431  /// method in the interface or its categories.
432  void getOverriddenMethods(
433                     SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
434
435  /// \brief True if the method was a definition but its body was skipped.
436  bool hasSkippedBody() const { return HasSkippedBody; }
437  void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
438
439  /// \brief Returns the property associated with this method's selector.
440  ///
441  /// Note that even if this particular method is not marked as a property
442  /// accessor, it is still possible for it to match a property declared in a
443  /// superclass. Pass \c false if you only want to check the current class.
444  const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
445
446  // Related to protocols declared in  \@protocol
447  void setDeclImplementation(ImplementationControl ic) {
448    DeclImplementation = ic;
449  }
450  ImplementationControl getImplementationControl() const {
451    return ImplementationControl(DeclImplementation);
452  }
453
454  /// \brief Determine whether this method has a body.
455  virtual bool hasBody() const { return Body; }
456
457  /// \brief Retrieve the body of this method, if it has one.
458  virtual Stmt *getBody() const;
459
460  void setLazyBody(uint64_t Offset) { Body = Offset; }
461
462  CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
463  void setBody(Stmt *B) { Body = B; }
464
465  /// \brief Returns whether this specific method is a definition.
466  bool isThisDeclarationADefinition() const { return Body; }
467
468  // Implement isa/cast/dyncast/etc.
469  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
470  static bool classofKind(Kind K) { return K == ObjCMethod; }
471  static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
472    return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
473  }
474  static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
475    return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
476  }
477
478  friend class ASTDeclReader;
479  friend class ASTDeclWriter;
480};
481
482/// ObjCContainerDecl - Represents a container for method declarations.
483/// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
484/// ObjCProtocolDecl, and ObjCImplDecl.
485///
486class ObjCContainerDecl : public NamedDecl, public DeclContext {
487  virtual void anchor();
488
489  SourceLocation AtStart;
490
491  // These two locations in the range mark the end of the method container.
492  // The first points to the '@' token, and the second to the 'end' token.
493  SourceRange AtEnd;
494public:
495
496  ObjCContainerDecl(Kind DK, DeclContext *DC,
497                    IdentifierInfo *Id, SourceLocation nameLoc,
498                    SourceLocation atStartLoc)
499    : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK), AtStart(atStartLoc) {}
500
501  // Iterator access to properties.
502  typedef specific_decl_iterator<ObjCPropertyDecl> prop_iterator;
503  prop_iterator prop_begin() const {
504    return prop_iterator(decls_begin());
505  }
506  prop_iterator prop_end() const {
507    return prop_iterator(decls_end());
508  }
509
510  // Iterator access to instance/class methods.
511  typedef specific_decl_iterator<ObjCMethodDecl> method_iterator;
512  method_iterator meth_begin() const {
513    return method_iterator(decls_begin());
514  }
515  method_iterator meth_end() const {
516    return method_iterator(decls_end());
517  }
518
519  typedef filtered_decl_iterator<ObjCMethodDecl,
520                                 &ObjCMethodDecl::isInstanceMethod>
521    instmeth_iterator;
522  instmeth_iterator instmeth_begin() const {
523    return instmeth_iterator(decls_begin());
524  }
525  instmeth_iterator instmeth_end() const {
526    return instmeth_iterator(decls_end());
527  }
528
529  typedef filtered_decl_iterator<ObjCMethodDecl,
530                                 &ObjCMethodDecl::isClassMethod>
531    classmeth_iterator;
532  classmeth_iterator classmeth_begin() const {
533    return classmeth_iterator(decls_begin());
534  }
535  classmeth_iterator classmeth_end() const {
536    return classmeth_iterator(decls_end());
537  }
538
539  // Get the local instance/class method declared in this interface.
540  ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
541                            bool AllowHidden = false) const;
542  ObjCMethodDecl *getInstanceMethod(Selector Sel,
543                                    bool AllowHidden = false) const {
544    return getMethod(Sel, true/*isInstance*/, AllowHidden);
545  }
546  ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
547    return getMethod(Sel, false/*isInstance*/, AllowHidden);
548  }
549  bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
550  ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
551
552  ObjCPropertyDecl *FindPropertyDeclaration(IdentifierInfo *PropertyId) const;
553
554  typedef llvm::DenseMap<IdentifierInfo*, ObjCPropertyDecl*> PropertyMap;
555
556  typedef llvm::SmallVector<ObjCPropertyDecl*, 8> PropertyDeclOrder;
557
558  /// This routine collects list of properties to be implemented in the class.
559  /// This includes, class's and its conforming protocols' properties.
560  /// Note, the superclass's properties are not included in the list.
561  virtual void collectPropertiesToImplement(PropertyMap &PM,
562                                            PropertyDeclOrder &PO) const {}
563
564  SourceLocation getAtStartLoc() const { return AtStart; }
565  void setAtStartLoc(SourceLocation Loc) { AtStart = Loc; }
566
567  // Marks the end of the container.
568  SourceRange getAtEndRange() const {
569    return AtEnd;
570  }
571  void setAtEndRange(SourceRange atEnd) {
572    AtEnd = atEnd;
573  }
574
575  virtual SourceRange getSourceRange() const LLVM_READONLY {
576    return SourceRange(AtStart, getAtEndRange().getEnd());
577  }
578
579  // Implement isa/cast/dyncast/etc.
580  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
581  static bool classofKind(Kind K) {
582    return K >= firstObjCContainer &&
583           K <= lastObjCContainer;
584  }
585
586  static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
587    return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
588  }
589  static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
590    return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
591  }
592};
593
594/// \brief Represents an ObjC class declaration.
595///
596/// For example:
597///
598/// \code
599///   // MostPrimitive declares no super class (not particularly useful).
600///   \@interface MostPrimitive
601///     // no instance variables or methods.
602///   \@end
603///
604///   // NSResponder inherits from NSObject & implements NSCoding (a protocol).
605///   \@interface NSResponder : NSObject \<NSCoding>
606///   { // instance variables are represented by ObjCIvarDecl.
607///     id nextResponder; // nextResponder instance variable.
608///   }
609///   - (NSResponder *)nextResponder; // return a pointer to NSResponder.
610///   - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
611///   \@end                                    // to an NSEvent.
612/// \endcode
613///
614///   Unlike C/C++, forward class declarations are accomplished with \@class.
615///   Unlike C/C++, \@class allows for a list of classes to be forward declared.
616///   Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
617///   typically inherit from NSObject (an exception is NSProxy).
618///
619class ObjCInterfaceDecl : public ObjCContainerDecl
620                        , public Redeclarable<ObjCInterfaceDecl> {
621  virtual void anchor();
622
623  /// TypeForDecl - This indicates the Type object that represents this
624  /// TypeDecl.  It is a cache maintained by ASTContext::getObjCInterfaceType
625  mutable const Type *TypeForDecl;
626  friend class ASTContext;
627
628  struct DefinitionData {
629    /// \brief The definition of this class, for quick access from any
630    /// declaration.
631    ObjCInterfaceDecl *Definition;
632
633    /// Class's super class.
634    ObjCInterfaceDecl *SuperClass;
635
636    /// Protocols referenced in the \@interface  declaration
637    ObjCProtocolList ReferencedProtocols;
638
639    /// Protocols reference in both the \@interface and class extensions.
640    ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
641
642    /// \brief List of categories and class extensions defined for this class.
643    ///
644    /// Categories are stored as a linked list in the AST, since the categories
645    /// and class extensions come long after the initial interface declaration,
646    /// and we avoid dynamically-resized arrays in the AST wherever possible.
647    ObjCCategoryDecl *CategoryList;
648
649    /// IvarList - List of all ivars defined by this class; including class
650    /// extensions and implementation. This list is built lazily.
651    ObjCIvarDecl *IvarList;
652
653    /// \brief Indicates that the contents of this Objective-C class will be
654    /// completed by the external AST source when required.
655    mutable bool ExternallyCompleted : 1;
656
657    /// \brief Indicates that the ivar cache does not yet include ivars
658    /// declared in the implementation.
659    mutable bool IvarListMissingImplementation : 1;
660
661    /// \brief The location of the superclass, if any.
662    SourceLocation SuperClassLoc;
663
664    /// \brief The location of the last location in this declaration, before
665    /// the properties/methods. For example, this will be the '>', '}', or
666    /// identifier,
667    SourceLocation EndLoc;
668
669    DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarList(),
670                       ExternallyCompleted(),
671                       IvarListMissingImplementation(true) { }
672  };
673
674  ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
675                    SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
676                    bool isInternal);
677
678  void LoadExternalDefinition() const;
679
680  /// \brief Contains a pointer to the data associated with this class,
681  /// which will be NULL if this class has not yet been defined.
682  ///
683  /// The bit indicates when we don't need to check for out-of-date
684  /// declarations. It will be set unless modules are enabled.
685  llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
686
687  DefinitionData &data() const {
688    assert(Data.getPointer() && "Declaration has no definition!");
689    return *Data.getPointer();
690  }
691
692  /// \brief Allocate the definition data for this class.
693  void allocateDefinitionData();
694
695  typedef Redeclarable<ObjCInterfaceDecl> redeclarable_base;
696  virtual ObjCInterfaceDecl *getNextRedeclaration() {
697    return RedeclLink.getNext();
698  }
699  virtual ObjCInterfaceDecl *getPreviousDeclImpl() {
700    return getPreviousDecl();
701  }
702  virtual ObjCInterfaceDecl *getMostRecentDeclImpl() {
703    return getMostRecentDecl();
704  }
705
706public:
707  static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
708                                   SourceLocation atLoc,
709                                   IdentifierInfo *Id,
710                                   ObjCInterfaceDecl *PrevDecl,
711                                   SourceLocation ClassLoc = SourceLocation(),
712                                   bool isInternal = false);
713
714  static ObjCInterfaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
715
716  virtual SourceRange getSourceRange() const LLVM_READONLY {
717    if (isThisDeclarationADefinition())
718      return ObjCContainerDecl::getSourceRange();
719
720    return SourceRange(getAtStartLoc(), getLocation());
721  }
722
723  /// \brief Indicate that this Objective-C class is complete, but that
724  /// the external AST source will be responsible for filling in its contents
725  /// when a complete class is required.
726  void setExternallyCompleted();
727
728  const ObjCProtocolList &getReferencedProtocols() const {
729    assert(hasDefinition() && "Caller did not check for forward reference!");
730    if (data().ExternallyCompleted)
731      LoadExternalDefinition();
732
733    return data().ReferencedProtocols;
734  }
735
736  ObjCImplementationDecl *getImplementation() const;
737  void setImplementation(ObjCImplementationDecl *ImplD);
738
739  ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
740
741  // Get the local instance/class method declared in a category.
742  ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
743  ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
744  ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
745    return isInstance ? getInstanceMethod(Sel)
746                      : getClassMethod(Sel);
747  }
748
749  typedef ObjCProtocolList::iterator protocol_iterator;
750
751  protocol_iterator protocol_begin() const {
752    // FIXME: Should make sure no callers ever do this.
753    if (!hasDefinition())
754      return protocol_iterator();
755
756    if (data().ExternallyCompleted)
757      LoadExternalDefinition();
758
759    return data().ReferencedProtocols.begin();
760  }
761  protocol_iterator protocol_end() const {
762    // FIXME: Should make sure no callers ever do this.
763    if (!hasDefinition())
764      return protocol_iterator();
765
766    if (data().ExternallyCompleted)
767      LoadExternalDefinition();
768
769    return data().ReferencedProtocols.end();
770  }
771
772  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
773
774  protocol_loc_iterator protocol_loc_begin() const {
775    // FIXME: Should make sure no callers ever do this.
776    if (!hasDefinition())
777      return protocol_loc_iterator();
778
779    if (data().ExternallyCompleted)
780      LoadExternalDefinition();
781
782    return data().ReferencedProtocols.loc_begin();
783  }
784
785  protocol_loc_iterator protocol_loc_end() const {
786    // FIXME: Should make sure no callers ever do this.
787    if (!hasDefinition())
788      return protocol_loc_iterator();
789
790    if (data().ExternallyCompleted)
791      LoadExternalDefinition();
792
793    return data().ReferencedProtocols.loc_end();
794  }
795
796  typedef ObjCList<ObjCProtocolDecl>::iterator all_protocol_iterator;
797
798  all_protocol_iterator all_referenced_protocol_begin() const {
799    // FIXME: Should make sure no callers ever do this.
800    if (!hasDefinition())
801      return all_protocol_iterator();
802
803    if (data().ExternallyCompleted)
804      LoadExternalDefinition();
805
806    return data().AllReferencedProtocols.empty()
807             ? protocol_begin()
808             : data().AllReferencedProtocols.begin();
809  }
810  all_protocol_iterator all_referenced_protocol_end() const {
811    // FIXME: Should make sure no callers ever do this.
812    if (!hasDefinition())
813      return all_protocol_iterator();
814
815    if (data().ExternallyCompleted)
816      LoadExternalDefinition();
817
818    return data().AllReferencedProtocols.empty()
819             ? protocol_end()
820             : data().AllReferencedProtocols.end();
821  }
822
823  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
824
825  ivar_iterator ivar_begin() const {
826    if (const ObjCInterfaceDecl *Def = getDefinition())
827      return ivar_iterator(Def->decls_begin());
828
829    // FIXME: Should make sure no callers ever do this.
830    return ivar_iterator();
831  }
832  ivar_iterator ivar_end() const {
833    if (const ObjCInterfaceDecl *Def = getDefinition())
834      return ivar_iterator(Def->decls_end());
835
836    // FIXME: Should make sure no callers ever do this.
837    return ivar_iterator();
838  }
839
840  unsigned ivar_size() const {
841    return std::distance(ivar_begin(), ivar_end());
842  }
843
844  bool ivar_empty() const { return ivar_begin() == ivar_end(); }
845
846  ObjCIvarDecl *all_declared_ivar_begin();
847  const ObjCIvarDecl *all_declared_ivar_begin() const {
848    // Even though this modifies IvarList, it's conceptually const:
849    // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
850    return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
851  }
852  void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
853
854  /// setProtocolList - Set the list of protocols that this interface
855  /// implements.
856  void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
857                       const SourceLocation *Locs, ASTContext &C) {
858    data().ReferencedProtocols.set(List, Num, Locs, C);
859  }
860
861  /// mergeClassExtensionProtocolList - Merge class extension's protocol list
862  /// into the protocol list for this class.
863  void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
864                                       unsigned Num,
865                                       ASTContext &C);
866
867  /// \brief Determine whether this particular declaration of this class is
868  /// actually also a definition.
869  bool isThisDeclarationADefinition() const {
870    return getDefinition() == this;
871  }
872
873  /// \brief Determine whether this class has been defined.
874  bool hasDefinition() const {
875    // If the name of this class is out-of-date, bring it up-to-date, which
876    // might bring in a definition.
877    // Note: a null value indicates that we don't have a definition and that
878    // modules are enabled.
879    if (!Data.getOpaqueValue()) {
880      if (IdentifierInfo *II = getIdentifier()) {
881        if (II->isOutOfDate()) {
882          updateOutOfDate(*II);
883        }
884      }
885    }
886
887    return Data.getPointer();
888  }
889
890  /// \brief Retrieve the definition of this class, or NULL if this class
891  /// has been forward-declared (with \@class) but not yet defined (with
892  /// \@interface).
893  ObjCInterfaceDecl *getDefinition() {
894    return hasDefinition()? Data.getPointer()->Definition : 0;
895  }
896
897  /// \brief Retrieve the definition of this class, or NULL if this class
898  /// has been forward-declared (with \@class) but not yet defined (with
899  /// \@interface).
900  const ObjCInterfaceDecl *getDefinition() const {
901    return hasDefinition()? Data.getPointer()->Definition : 0;
902  }
903
904  /// \brief Starts the definition of this Objective-C class, taking it from
905  /// a forward declaration (\@class) to a definition (\@interface).
906  void startDefinition();
907
908  ObjCInterfaceDecl *getSuperClass() const {
909    // FIXME: Should make sure no callers ever do this.
910    if (!hasDefinition())
911      return 0;
912
913    if (data().ExternallyCompleted)
914      LoadExternalDefinition();
915
916    return data().SuperClass;
917  }
918
919  void setSuperClass(ObjCInterfaceDecl * superCls) {
920    data().SuperClass =
921      (superCls && superCls->hasDefinition()) ? superCls->getDefinition()
922                                              : superCls;
923  }
924
925  /// \brief Iterator that walks over the list of categories, filtering out
926  /// those that do not meet specific criteria.
927  ///
928  /// This class template is used for the various permutations of category
929  /// and extension iterators.
930  template<bool (*Filter)(ObjCCategoryDecl *)>
931  class filtered_category_iterator {
932    ObjCCategoryDecl *Current;
933
934    void findAcceptableCategory();
935
936  public:
937    typedef ObjCCategoryDecl *      value_type;
938    typedef value_type              reference;
939    typedef value_type              pointer;
940    typedef std::ptrdiff_t          difference_type;
941    typedef std::input_iterator_tag iterator_category;
942
943    filtered_category_iterator() : Current(0) { }
944    explicit filtered_category_iterator(ObjCCategoryDecl *Current)
945      : Current(Current)
946    {
947      findAcceptableCategory();
948    }
949
950    reference operator*() const { return Current; }
951    pointer operator->() const { return Current; }
952
953    filtered_category_iterator &operator++();
954
955    filtered_category_iterator operator++(int) {
956      filtered_category_iterator Tmp = *this;
957      ++(*this);
958      return Tmp;
959    }
960
961    friend bool operator==(filtered_category_iterator X,
962                           filtered_category_iterator Y) {
963      return X.Current == Y.Current;
964    }
965
966    friend bool operator!=(filtered_category_iterator X,
967                           filtered_category_iterator Y) {
968      return X.Current != Y.Current;
969    }
970  };
971
972private:
973  /// \brief Test whether the given category is visible.
974  ///
975  /// Used in the \c visible_categories_iterator.
976  static bool isVisibleCategory(ObjCCategoryDecl *Cat);
977
978public:
979  /// \brief Iterator that walks over the list of categories and extensions
980  /// that are visible, i.e., not hidden in a non-imported submodule.
981  typedef filtered_category_iterator<isVisibleCategory>
982    visible_categories_iterator;
983
984  /// \brief Retrieve an iterator to the beginning of the visible-categories
985  /// list.
986  visible_categories_iterator visible_categories_begin() const {
987    return visible_categories_iterator(getCategoryListRaw());
988  }
989
990  /// \brief Retrieve an iterator to the end of the visible-categories list.
991  visible_categories_iterator visible_categories_end() const {
992    return visible_categories_iterator();
993  }
994
995  /// \brief Determine whether the visible-categories list is empty.
996  bool visible_categories_empty() const {
997    return visible_categories_begin() == visible_categories_end();
998  }
999
1000private:
1001  /// \brief Test whether the given category... is a category.
1002  ///
1003  /// Used in the \c known_categories_iterator.
1004  static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1005
1006public:
1007  /// \brief Iterator that walks over all of the known categories and
1008  /// extensions, including those that are hidden.
1009  typedef filtered_category_iterator<isKnownCategory> known_categories_iterator;
1010
1011  /// \brief Retrieve an iterator to the beginning of the known-categories
1012  /// list.
1013  known_categories_iterator known_categories_begin() const {
1014    return known_categories_iterator(getCategoryListRaw());
1015  }
1016
1017  /// \brief Retrieve an iterator to the end of the known-categories list.
1018  known_categories_iterator known_categories_end() const {
1019    return known_categories_iterator();
1020  }
1021
1022  /// \brief Determine whether the known-categories list is empty.
1023  bool known_categories_empty() const {
1024    return known_categories_begin() == known_categories_end();
1025  }
1026
1027private:
1028  /// \brief Test whether the given category is a visible extension.
1029  ///
1030  /// Used in the \c visible_extensions_iterator.
1031  static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1032
1033public:
1034  /// \brief Iterator that walks over all of the visible extensions, skipping
1035  /// any that are known but hidden.
1036  typedef filtered_category_iterator<isVisibleExtension>
1037    visible_extensions_iterator;
1038
1039  /// \brief Retrieve an iterator to the beginning of the visible-extensions
1040  /// list.
1041  visible_extensions_iterator visible_extensions_begin() const {
1042    return visible_extensions_iterator(getCategoryListRaw());
1043  }
1044
1045  /// \brief Retrieve an iterator to the end of the visible-extensions list.
1046  visible_extensions_iterator visible_extensions_end() const {
1047    return visible_extensions_iterator();
1048  }
1049
1050  /// \brief Determine whether the visible-extensions list is empty.
1051  bool visible_extensions_empty() const {
1052    return visible_extensions_begin() == visible_extensions_end();
1053  }
1054
1055private:
1056  /// \brief Test whether the given category is an extension.
1057  ///
1058  /// Used in the \c known_extensions_iterator.
1059  static bool isKnownExtension(ObjCCategoryDecl *Cat);
1060
1061public:
1062  /// \brief Iterator that walks over all of the known extensions.
1063  typedef filtered_category_iterator<isKnownExtension>
1064    known_extensions_iterator;
1065
1066  /// \brief Retrieve an iterator to the beginning of the known-extensions
1067  /// list.
1068  known_extensions_iterator known_extensions_begin() const {
1069    return known_extensions_iterator(getCategoryListRaw());
1070  }
1071
1072  /// \brief Retrieve an iterator to the end of the known-extensions list.
1073  known_extensions_iterator known_extensions_end() const {
1074    return known_extensions_iterator();
1075  }
1076
1077  /// \brief Determine whether the known-extensions list is empty.
1078  bool known_extensions_empty() const {
1079    return known_extensions_begin() == known_extensions_end();
1080  }
1081
1082  /// \brief Retrieve the raw pointer to the start of the category/extension
1083  /// list.
1084  ObjCCategoryDecl* getCategoryListRaw() const {
1085    // FIXME: Should make sure no callers ever do this.
1086    if (!hasDefinition())
1087      return 0;
1088
1089    if (data().ExternallyCompleted)
1090      LoadExternalDefinition();
1091
1092    return data().CategoryList;
1093  }
1094
1095  /// \brief Set the raw pointer to the start of the category/extension
1096  /// list.
1097  void setCategoryListRaw(ObjCCategoryDecl *category) {
1098    data().CategoryList = category;
1099  }
1100
1101  ObjCPropertyDecl
1102    *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId) const;
1103
1104  virtual void collectPropertiesToImplement(PropertyMap &PM,
1105                                            PropertyDeclOrder &PO) const;
1106
1107  /// isSuperClassOf - Return true if this class is the specified class or is a
1108  /// super class of the specified interface class.
1109  bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1110    // If RHS is derived from LHS it is OK; else it is not OK.
1111    while (I != NULL) {
1112      if (declaresSameEntity(this, I))
1113        return true;
1114
1115      I = I->getSuperClass();
1116    }
1117    return false;
1118  }
1119
1120  /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1121  /// to be incompatible with __weak references. Returns true if it is.
1122  bool isArcWeakrefUnavailable() const;
1123
1124  /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1125  /// classes must not be auto-synthesized. Returns class decl. if it must not
1126  /// be; 0, otherwise.
1127  const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1128
1129  ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1130                                       ObjCInterfaceDecl *&ClassDeclared);
1131  ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1132    ObjCInterfaceDecl *ClassDeclared;
1133    return lookupInstanceVariable(IVarName, ClassDeclared);
1134  }
1135
1136  // Lookup a method. First, we search locally. If a method isn't
1137  // found, we search referenced protocols and class categories.
1138  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1139                               bool shallowCategoryLookup= false) const;
1140  ObjCMethodDecl *lookupInstanceMethod(Selector Sel,
1141                            bool shallowCategoryLookup = false) const {
1142    return lookupMethod(Sel, true/*isInstance*/, shallowCategoryLookup);
1143  }
1144  ObjCMethodDecl *lookupClassMethod(Selector Sel,
1145                     bool shallowCategoryLookup = false) const {
1146    return lookupMethod(Sel, false/*isInstance*/, shallowCategoryLookup);
1147  }
1148  ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1149
1150  /// \brief Lookup a method in the classes implementation hierarchy.
1151  ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1152                                      bool Instance=true) const;
1153
1154  ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1155    return lookupPrivateMethod(Sel, false);
1156  }
1157
1158  SourceLocation getEndOfDefinitionLoc() const {
1159    if (!hasDefinition())
1160      return getLocation();
1161
1162    return data().EndLoc;
1163  }
1164
1165  void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1166
1167  void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc = Loc; }
1168  SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; }
1169
1170  /// isImplicitInterfaceDecl - check that this is an implicitly declared
1171  /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1172  /// declaration without an \@interface declaration.
1173  bool isImplicitInterfaceDecl() const {
1174    return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1175  }
1176
1177  /// ClassImplementsProtocol - Checks that 'lProto' protocol
1178  /// has been implemented in IDecl class, its super class or categories (if
1179  /// lookupCategory is true).
1180  bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1181                               bool lookupCategory,
1182                               bool RHSIsQualifiedID = false);
1183
1184  typedef redeclarable_base::redecl_iterator redecl_iterator;
1185  using redeclarable_base::redecls_begin;
1186  using redeclarable_base::redecls_end;
1187  using redeclarable_base::getPreviousDecl;
1188  using redeclarable_base::getMostRecentDecl;
1189
1190  /// Retrieves the canonical declaration of this Objective-C class.
1191  ObjCInterfaceDecl *getCanonicalDecl() {
1192    return getFirstDeclaration();
1193  }
1194  const ObjCInterfaceDecl *getCanonicalDecl() const {
1195    return getFirstDeclaration();
1196  }
1197
1198  // Low-level accessor
1199  const Type *getTypeForDecl() const { return TypeForDecl; }
1200  void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1201
1202  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1203  static bool classofKind(Kind K) { return K == ObjCInterface; }
1204
1205  friend class ASTReader;
1206  friend class ASTDeclReader;
1207  friend class ASTDeclWriter;
1208};
1209
1210/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1211/// instance variables are identical to C. The only exception is Objective-C
1212/// supports C++ style access control. For example:
1213///
1214///   \@interface IvarExample : NSObject
1215///   {
1216///     id defaultToProtected;
1217///   \@public:
1218///     id canBePublic; // same as C++.
1219///   \@protected:
1220///     id canBeProtected; // same as C++.
1221///   \@package:
1222///     id canBePackage; // framework visibility (not available in C++).
1223///   }
1224///
1225class ObjCIvarDecl : public FieldDecl {
1226  virtual void anchor();
1227
1228public:
1229  enum AccessControl {
1230    None, Private, Protected, Public, Package
1231  };
1232
1233private:
1234  ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1235               SourceLocation IdLoc, IdentifierInfo *Id,
1236               QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1237               bool synthesized)
1238    : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1239                /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1240      NextIvar(0), DeclAccess(ac), Synthesized(synthesized) {}
1241
1242public:
1243  static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1244                              SourceLocation StartLoc, SourceLocation IdLoc,
1245                              IdentifierInfo *Id, QualType T,
1246                              TypeSourceInfo *TInfo,
1247                              AccessControl ac, Expr *BW = NULL,
1248                              bool synthesized=false);
1249
1250  static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1251
1252  /// \brief Return the class interface that this ivar is logically contained
1253  /// in; this is either the interface where the ivar was declared, or the
1254  /// interface the ivar is conceptually a part of in the case of synthesized
1255  /// ivars.
1256  const ObjCInterfaceDecl *getContainingInterface() const;
1257
1258  ObjCIvarDecl *getNextIvar() { return NextIvar; }
1259  const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1260  void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1261
1262  void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1263
1264  AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1265
1266  AccessControl getCanonicalAccessControl() const {
1267    return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1268  }
1269
1270  void setSynthesize(bool synth) { Synthesized = synth; }
1271  bool getSynthesize() const { return Synthesized; }
1272
1273  // Implement isa/cast/dyncast/etc.
1274  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1275  static bool classofKind(Kind K) { return K == ObjCIvar; }
1276private:
1277  /// NextIvar - Next Ivar in the list of ivars declared in class; class's
1278  /// extensions and class's implementation
1279  ObjCIvarDecl *NextIvar;
1280
1281  // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
1282  unsigned DeclAccess : 3;
1283  unsigned Synthesized : 1;
1284};
1285
1286
1287/// \brief Represents a field declaration created by an \@defs(...).
1288class ObjCAtDefsFieldDecl : public FieldDecl {
1289  virtual void anchor();
1290  ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
1291                      SourceLocation IdLoc, IdentifierInfo *Id,
1292                      QualType T, Expr *BW)
1293    : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
1294                /*TInfo=*/0, // FIXME: Do ObjCAtDefs have declarators ?
1295                BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
1296
1297public:
1298  static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
1299                                     SourceLocation StartLoc,
1300                                     SourceLocation IdLoc, IdentifierInfo *Id,
1301                                     QualType T, Expr *BW);
1302
1303  static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1304
1305  // Implement isa/cast/dyncast/etc.
1306  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1307  static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
1308};
1309
1310/// \brief Represents an Objective-C protocol declaration.
1311///
1312/// Objective-C protocols declare a pure abstract type (i.e., no instance
1313/// variables are permitted).  Protocols originally drew inspiration from
1314/// C++ pure virtual functions (a C++ feature with nice semantics and lousy
1315/// syntax:-). Here is an example:
1316///
1317/// \code
1318/// \@protocol NSDraggingInfo <refproto1, refproto2>
1319/// - (NSWindow *)draggingDestinationWindow;
1320/// - (NSImage *)draggedImage;
1321/// \@end
1322/// \endcode
1323///
1324/// This says that NSDraggingInfo requires two methods and requires everything
1325/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
1326/// well.
1327///
1328/// \code
1329/// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
1330/// \@end
1331/// \endcode
1332///
1333/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
1334/// protocols are in distinct namespaces. For example, Cocoa defines both
1335/// an NSObject protocol and class (which isn't allowed in Java). As a result,
1336/// protocols are referenced using angle brackets as follows:
1337///
1338/// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
1339///
1340class ObjCProtocolDecl : public ObjCContainerDecl,
1341                         public Redeclarable<ObjCProtocolDecl> {
1342  virtual void anchor();
1343
1344  struct DefinitionData {
1345    // \brief The declaration that defines this protocol.
1346    ObjCProtocolDecl *Definition;
1347
1348    /// \brief Referenced protocols
1349    ObjCProtocolList ReferencedProtocols;
1350  };
1351
1352  /// \brief Contains a pointer to the data associated with this class,
1353  /// which will be NULL if this class has not yet been defined.
1354  ///
1355  /// The bit indicates when we don't need to check for out-of-date
1356  /// declarations. It will be set unless modules are enabled.
1357  llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1358
1359  DefinitionData &data() const {
1360    assert(Data.getPointer() && "Objective-C protocol has no definition!");
1361    return *Data.getPointer();
1362  }
1363
1364  ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
1365                   SourceLocation nameLoc, SourceLocation atStartLoc,
1366                   ObjCProtocolDecl *PrevDecl);
1367
1368  void allocateDefinitionData();
1369
1370  typedef Redeclarable<ObjCProtocolDecl> redeclarable_base;
1371  virtual ObjCProtocolDecl *getNextRedeclaration() {
1372    return RedeclLink.getNext();
1373  }
1374  virtual ObjCProtocolDecl *getPreviousDeclImpl() {
1375    return getPreviousDecl();
1376  }
1377  virtual ObjCProtocolDecl *getMostRecentDeclImpl() {
1378    return getMostRecentDecl();
1379  }
1380
1381public:
1382  static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
1383                                  IdentifierInfo *Id,
1384                                  SourceLocation nameLoc,
1385                                  SourceLocation atStartLoc,
1386                                  ObjCProtocolDecl *PrevDecl);
1387
1388  static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1389
1390  const ObjCProtocolList &getReferencedProtocols() const {
1391    assert(hasDefinition() && "No definition available!");
1392    return data().ReferencedProtocols;
1393  }
1394  typedef ObjCProtocolList::iterator protocol_iterator;
1395  protocol_iterator protocol_begin() const {
1396    if (!hasDefinition())
1397      return protocol_iterator();
1398
1399    return data().ReferencedProtocols.begin();
1400  }
1401  protocol_iterator protocol_end() const {
1402    if (!hasDefinition())
1403      return protocol_iterator();
1404
1405    return data().ReferencedProtocols.end();
1406  }
1407  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1408  protocol_loc_iterator protocol_loc_begin() const {
1409    if (!hasDefinition())
1410      return protocol_loc_iterator();
1411
1412    return data().ReferencedProtocols.loc_begin();
1413  }
1414  protocol_loc_iterator protocol_loc_end() const {
1415    if (!hasDefinition())
1416      return protocol_loc_iterator();
1417
1418    return data().ReferencedProtocols.loc_end();
1419  }
1420  unsigned protocol_size() const {
1421    if (!hasDefinition())
1422      return 0;
1423
1424    return data().ReferencedProtocols.size();
1425  }
1426
1427  /// setProtocolList - Set the list of protocols that this interface
1428  /// implements.
1429  void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1430                       const SourceLocation *Locs, ASTContext &C) {
1431    assert(hasDefinition() && "Protocol is not defined");
1432    data().ReferencedProtocols.set(List, Num, Locs, C);
1433  }
1434
1435  ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
1436
1437  // Lookup a method. First, we search locally. If a method isn't
1438  // found, we search referenced protocols and class categories.
1439  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
1440  ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1441    return lookupMethod(Sel, true/*isInstance*/);
1442  }
1443  ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1444    return lookupMethod(Sel, false/*isInstance*/);
1445  }
1446
1447  /// \brief Determine whether this protocol has a definition.
1448  bool hasDefinition() const {
1449    // If the name of this protocol is out-of-date, bring it up-to-date, which
1450    // might bring in a definition.
1451    // Note: a null value indicates that we don't have a definition and that
1452    // modules are enabled.
1453    if (!Data.getOpaqueValue()) {
1454      if (IdentifierInfo *II = getIdentifier()) {
1455        if (II->isOutOfDate()) {
1456          updateOutOfDate(*II);
1457        }
1458      }
1459    }
1460
1461    return Data.getPointer();
1462  }
1463
1464  /// \brief Retrieve the definition of this protocol, if any.
1465  ObjCProtocolDecl *getDefinition() {
1466    return hasDefinition()? Data.getPointer()->Definition : 0;
1467  }
1468
1469  /// \brief Retrieve the definition of this protocol, if any.
1470  const ObjCProtocolDecl *getDefinition() const {
1471    return hasDefinition()? Data.getPointer()->Definition : 0;
1472  }
1473
1474  /// \brief Determine whether this particular declaration is also the
1475  /// definition.
1476  bool isThisDeclarationADefinition() const {
1477    return getDefinition() == this;
1478  }
1479
1480  /// \brief Starts the definition of this Objective-C protocol.
1481  void startDefinition();
1482
1483  virtual SourceRange getSourceRange() const LLVM_READONLY {
1484    if (isThisDeclarationADefinition())
1485      return ObjCContainerDecl::getSourceRange();
1486
1487    return SourceRange(getAtStartLoc(), getLocation());
1488  }
1489
1490  typedef redeclarable_base::redecl_iterator redecl_iterator;
1491  using redeclarable_base::redecls_begin;
1492  using redeclarable_base::redecls_end;
1493  using redeclarable_base::getPreviousDecl;
1494  using redeclarable_base::getMostRecentDecl;
1495
1496  /// Retrieves the canonical declaration of this Objective-C protocol.
1497  ObjCProtocolDecl *getCanonicalDecl() {
1498    return getFirstDeclaration();
1499  }
1500  const ObjCProtocolDecl *getCanonicalDecl() const {
1501    return getFirstDeclaration();
1502  }
1503
1504  virtual void collectPropertiesToImplement(PropertyMap &PM,
1505                                            PropertyDeclOrder &PO) const;
1506
1507  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1508  static bool classofKind(Kind K) { return K == ObjCProtocol; }
1509
1510  friend class ASTReader;
1511  friend class ASTDeclReader;
1512  friend class ASTDeclWriter;
1513};
1514
1515/// ObjCCategoryDecl - Represents a category declaration. A category allows
1516/// you to add methods to an existing class (without subclassing or modifying
1517/// the original class interface or implementation:-). Categories don't allow
1518/// you to add instance data. The following example adds "myMethod" to all
1519/// NSView's within a process:
1520///
1521/// \@interface NSView (MyViewMethods)
1522/// - myMethod;
1523/// \@end
1524///
1525/// Categories also allow you to split the implementation of a class across
1526/// several files (a feature more naturally supported in C++).
1527///
1528/// Categories were originally inspired by dynamic languages such as Common
1529/// Lisp and Smalltalk.  More traditional class-based languages (C++, Java)
1530/// don't support this level of dynamism, which is both powerful and dangerous.
1531///
1532class ObjCCategoryDecl : public ObjCContainerDecl {
1533  virtual void anchor();
1534
1535  /// Interface belonging to this category
1536  ObjCInterfaceDecl *ClassInterface;
1537
1538  /// referenced protocols in this category.
1539  ObjCProtocolList ReferencedProtocols;
1540
1541  /// Next category belonging to this class.
1542  /// FIXME: this should not be a singly-linked list.  Move storage elsewhere.
1543  ObjCCategoryDecl *NextClassCategory;
1544
1545  /// \brief The location of the category name in this declaration.
1546  SourceLocation CategoryNameLoc;
1547
1548  /// class extension may have private ivars.
1549  SourceLocation IvarLBraceLoc;
1550  SourceLocation IvarRBraceLoc;
1551
1552  ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1553                   SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
1554                   IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1555                   SourceLocation IvarLBraceLoc=SourceLocation(),
1556                   SourceLocation IvarRBraceLoc=SourceLocation())
1557    : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1558      ClassInterface(IDecl), NextClassCategory(0),
1559      CategoryNameLoc(CategoryNameLoc),
1560      IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
1561  }
1562
1563public:
1564
1565  static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
1566                                  SourceLocation AtLoc,
1567                                  SourceLocation ClassNameLoc,
1568                                  SourceLocation CategoryNameLoc,
1569                                  IdentifierInfo *Id,
1570                                  ObjCInterfaceDecl *IDecl,
1571                                  SourceLocation IvarLBraceLoc=SourceLocation(),
1572                                  SourceLocation IvarRBraceLoc=SourceLocation());
1573  static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1574
1575  ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1576  const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1577
1578  ObjCCategoryImplDecl *getImplementation() const;
1579  void setImplementation(ObjCCategoryImplDecl *ImplD);
1580
1581  /// setProtocolList - Set the list of protocols that this interface
1582  /// implements.
1583  void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1584                       const SourceLocation *Locs, ASTContext &C) {
1585    ReferencedProtocols.set(List, Num, Locs, C);
1586  }
1587
1588  const ObjCProtocolList &getReferencedProtocols() const {
1589    return ReferencedProtocols;
1590  }
1591
1592  typedef ObjCProtocolList::iterator protocol_iterator;
1593  protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();}
1594  protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
1595  unsigned protocol_size() const { return ReferencedProtocols.size(); }
1596  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1597  protocol_loc_iterator protocol_loc_begin() const {
1598    return ReferencedProtocols.loc_begin();
1599  }
1600  protocol_loc_iterator protocol_loc_end() const {
1601    return ReferencedProtocols.loc_end();
1602  }
1603
1604  ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
1605
1606  /// \brief Retrieve the pointer to the next stored category (or extension),
1607  /// which may be hidden.
1608  ObjCCategoryDecl *getNextClassCategoryRaw() const {
1609    return NextClassCategory;
1610  }
1611
1612  bool IsClassExtension() const { return getIdentifier() == 0; }
1613
1614  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1615  ivar_iterator ivar_begin() const {
1616    return ivar_iterator(decls_begin());
1617  }
1618  ivar_iterator ivar_end() const {
1619    return ivar_iterator(decls_end());
1620  }
1621  unsigned ivar_size() const {
1622    return std::distance(ivar_begin(), ivar_end());
1623  }
1624  bool ivar_empty() const {
1625    return ivar_begin() == ivar_end();
1626  }
1627
1628  SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1629  void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
1630
1631  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
1632  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
1633  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
1634  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1635
1636  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1637  static bool classofKind(Kind K) { return K == ObjCCategory; }
1638
1639  friend class ASTDeclReader;
1640  friend class ASTDeclWriter;
1641};
1642
1643class ObjCImplDecl : public ObjCContainerDecl {
1644  virtual void anchor();
1645
1646  /// Class interface for this class/category implementation
1647  ObjCInterfaceDecl *ClassInterface;
1648
1649protected:
1650  ObjCImplDecl(Kind DK, DeclContext *DC,
1651               ObjCInterfaceDecl *classInterface,
1652               SourceLocation nameLoc, SourceLocation atStartLoc)
1653    : ObjCContainerDecl(DK, DC,
1654                        classInterface? classInterface->getIdentifier() : 0,
1655                        nameLoc, atStartLoc),
1656      ClassInterface(classInterface) {}
1657
1658public:
1659  const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1660  ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1661  void setClassInterface(ObjCInterfaceDecl *IFace);
1662
1663  void addInstanceMethod(ObjCMethodDecl *method) {
1664    // FIXME: Context should be set correctly before we get here.
1665    method->setLexicalDeclContext(this);
1666    addDecl(method);
1667  }
1668  void addClassMethod(ObjCMethodDecl *method) {
1669    // FIXME: Context should be set correctly before we get here.
1670    method->setLexicalDeclContext(this);
1671    addDecl(method);
1672  }
1673
1674  void addPropertyImplementation(ObjCPropertyImplDecl *property);
1675
1676  ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const;
1677  ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
1678
1679  // Iterator access to properties.
1680  typedef specific_decl_iterator<ObjCPropertyImplDecl> propimpl_iterator;
1681  propimpl_iterator propimpl_begin() const {
1682    return propimpl_iterator(decls_begin());
1683  }
1684  propimpl_iterator propimpl_end() const {
1685    return propimpl_iterator(decls_end());
1686  }
1687
1688  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1689  static bool classofKind(Kind K) {
1690    return K >= firstObjCImpl && K <= lastObjCImpl;
1691  }
1692};
1693
1694/// ObjCCategoryImplDecl - An object of this class encapsulates a category
1695/// \@implementation declaration. If a category class has declaration of a
1696/// property, its implementation must be specified in the category's
1697/// \@implementation declaration. Example:
1698/// \@interface I \@end
1699/// \@interface I(CATEGORY)
1700///    \@property int p1, d1;
1701/// \@end
1702/// \@implementation I(CATEGORY)
1703///  \@dynamic p1,d1;
1704/// \@end
1705///
1706/// ObjCCategoryImplDecl
1707class ObjCCategoryImplDecl : public ObjCImplDecl {
1708  virtual void anchor();
1709
1710  // Category name
1711  IdentifierInfo *Id;
1712
1713  // Category name location
1714  SourceLocation CategoryNameLoc;
1715
1716  ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
1717                       ObjCInterfaceDecl *classInterface,
1718                       SourceLocation nameLoc, SourceLocation atStartLoc,
1719                       SourceLocation CategoryNameLoc)
1720    : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartLoc),
1721      Id(Id), CategoryNameLoc(CategoryNameLoc) {}
1722public:
1723  static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
1724                                      IdentifierInfo *Id,
1725                                      ObjCInterfaceDecl *classInterface,
1726                                      SourceLocation nameLoc,
1727                                      SourceLocation atStartLoc,
1728                                      SourceLocation CategoryNameLoc);
1729  static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1730
1731  /// getIdentifier - Get the identifier that names the category
1732  /// interface associated with this implementation.
1733  /// FIXME: This is a bad API, we are overriding the NamedDecl::getIdentifier()
1734  /// to mean something different. For example:
1735  /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()
1736  /// returns the class interface name, whereas
1737  /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()
1738  /// returns the category name.
1739  IdentifierInfo *getIdentifier() const {
1740    return Id;
1741  }
1742  void setIdentifier(IdentifierInfo *II) { Id = II; }
1743
1744  ObjCCategoryDecl *getCategoryDecl() const;
1745
1746  SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1747
1748  /// getName - Get the name of identifier for the class interface associated
1749  /// with this implementation as a StringRef.
1750  //
1751  // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean
1752  // something different.
1753  StringRef getName() const {
1754    return Id ? Id->getNameStart() : "";
1755  }
1756
1757  /// @brief Get the name of the class associated with this interface.
1758  //
1759  // FIXME: Deprecated, move clients to getName().
1760  std::string getNameAsString() const {
1761    return getName();
1762  }
1763
1764  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1765  static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
1766
1767  friend class ASTDeclReader;
1768  friend class ASTDeclWriter;
1769};
1770
1771raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
1772
1773/// ObjCImplementationDecl - Represents a class definition - this is where
1774/// method definitions are specified. For example:
1775///
1776/// @code
1777/// \@implementation MyClass
1778/// - (void)myMethod { /* do something */ }
1779/// \@end
1780/// @endcode
1781///
1782/// Typically, instance variables are specified in the class interface,
1783/// *not* in the implementation. Nevertheless (for legacy reasons), we
1784/// allow instance variables to be specified in the implementation.  When
1785/// specified, they need to be *identical* to the interface.
1786///
1787class ObjCImplementationDecl : public ObjCImplDecl {
1788  virtual void anchor();
1789  /// Implementation Class's super class.
1790  ObjCInterfaceDecl *SuperClass;
1791  /// \@implementation may have private ivars.
1792  SourceLocation IvarLBraceLoc;
1793  SourceLocation IvarRBraceLoc;
1794
1795  /// Support for ivar initialization.
1796  /// IvarInitializers - The arguments used to initialize the ivars
1797  CXXCtorInitializer **IvarInitializers;
1798  unsigned NumIvarInitializers;
1799
1800  /// Do the ivars of this class require initialization other than
1801  /// zero-initialization?
1802  bool HasNonZeroConstructors : 1;
1803
1804  /// Do the ivars of this class require non-trivial destruction?
1805  bool HasDestructors : 1;
1806
1807  ObjCImplementationDecl(DeclContext *DC,
1808                         ObjCInterfaceDecl *classInterface,
1809                         ObjCInterfaceDecl *superDecl,
1810                         SourceLocation nameLoc, SourceLocation atStartLoc,
1811                         SourceLocation IvarLBraceLoc=SourceLocation(),
1812                         SourceLocation IvarRBraceLoc=SourceLocation())
1813    : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStartLoc),
1814       SuperClass(superDecl), IvarLBraceLoc(IvarLBraceLoc),
1815       IvarRBraceLoc(IvarRBraceLoc),
1816       IvarInitializers(0), NumIvarInitializers(0),
1817       HasNonZeroConstructors(false), HasDestructors(false) {}
1818public:
1819  static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
1820                                        ObjCInterfaceDecl *classInterface,
1821                                        ObjCInterfaceDecl *superDecl,
1822                                        SourceLocation nameLoc,
1823                                        SourceLocation atStartLoc,
1824                                        SourceLocation IvarLBraceLoc=SourceLocation(),
1825                                        SourceLocation IvarRBraceLoc=SourceLocation());
1826
1827  static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1828
1829  /// init_iterator - Iterates through the ivar initializer list.
1830  typedef CXXCtorInitializer **init_iterator;
1831
1832  /// init_const_iterator - Iterates through the ivar initializer list.
1833  typedef CXXCtorInitializer * const * init_const_iterator;
1834
1835  /// init_begin() - Retrieve an iterator to the first initializer.
1836  init_iterator       init_begin()       { return IvarInitializers; }
1837  /// begin() - Retrieve an iterator to the first initializer.
1838  init_const_iterator init_begin() const { return IvarInitializers; }
1839
1840  /// init_end() - Retrieve an iterator past the last initializer.
1841  init_iterator       init_end()       {
1842    return IvarInitializers + NumIvarInitializers;
1843  }
1844  /// end() - Retrieve an iterator past the last initializer.
1845  init_const_iterator init_end() const {
1846    return IvarInitializers + NumIvarInitializers;
1847  }
1848  /// getNumArgs - Number of ivars which must be initialized.
1849  unsigned getNumIvarInitializers() const {
1850    return NumIvarInitializers;
1851  }
1852
1853  void setNumIvarInitializers(unsigned numNumIvarInitializers) {
1854    NumIvarInitializers = numNumIvarInitializers;
1855  }
1856
1857  void setIvarInitializers(ASTContext &C,
1858                           CXXCtorInitializer ** initializers,
1859                           unsigned numInitializers);
1860
1861  /// Do any of the ivars of this class (not counting its base classes)
1862  /// require construction other than zero-initialization?
1863  bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
1864  void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
1865
1866  /// Do any of the ivars of this class (not counting its base classes)
1867  /// require non-trivial destruction?
1868  bool hasDestructors() const { return HasDestructors; }
1869  void setHasDestructors(bool val) { HasDestructors = val; }
1870
1871  /// getIdentifier - Get the identifier that names the class
1872  /// interface associated with this implementation.
1873  IdentifierInfo *getIdentifier() const {
1874    return getClassInterface()->getIdentifier();
1875  }
1876
1877  /// getName - Get the name of identifier for the class interface associated
1878  /// with this implementation as a StringRef.
1879  //
1880  // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean
1881  // something different.
1882  StringRef getName() const {
1883    assert(getIdentifier() && "Name is not a simple identifier");
1884    return getIdentifier()->getName();
1885  }
1886
1887  /// @brief Get the name of the class associated with this interface.
1888  //
1889  // FIXME: Move to StringRef API.
1890  std::string getNameAsString() const {
1891    return getName();
1892  }
1893
1894  const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
1895  ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
1896
1897  void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
1898
1899  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
1900  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
1901  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
1902  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1903
1904  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1905  ivar_iterator ivar_begin() const {
1906    return ivar_iterator(decls_begin());
1907  }
1908  ivar_iterator ivar_end() const {
1909    return ivar_iterator(decls_end());
1910  }
1911  unsigned ivar_size() const {
1912    return std::distance(ivar_begin(), ivar_end());
1913  }
1914  bool ivar_empty() const {
1915    return ivar_begin() == ivar_end();
1916  }
1917
1918  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1919  static bool classofKind(Kind K) { return K == ObjCImplementation; }
1920
1921  friend class ASTDeclReader;
1922  friend class ASTDeclWriter;
1923};
1924
1925raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
1926
1927/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
1928/// declared as \@compatibility_alias alias class.
1929class ObjCCompatibleAliasDecl : public NamedDecl {
1930  virtual void anchor();
1931  /// Class that this is an alias of.
1932  ObjCInterfaceDecl *AliasedClass;
1933
1934  ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
1935                          ObjCInterfaceDecl* aliasedClass)
1936    : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
1937public:
1938  static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
1939                                         SourceLocation L, IdentifierInfo *Id,
1940                                         ObjCInterfaceDecl* aliasedClass);
1941
1942  static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
1943                                                     unsigned ID);
1944
1945  const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
1946  ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
1947  void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
1948
1949  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1950  static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
1951
1952};
1953
1954/// \brief Represents one property declaration in an Objective-C interface.
1955///
1956/// For example:
1957/// \code{.mm}
1958/// \@property (assign, readwrite) int MyProperty;
1959/// \endcode
1960class ObjCPropertyDecl : public NamedDecl {
1961  virtual void anchor();
1962public:
1963  enum PropertyAttributeKind {
1964    OBJC_PR_noattr    = 0x00,
1965    OBJC_PR_readonly  = 0x01,
1966    OBJC_PR_getter    = 0x02,
1967    OBJC_PR_assign    = 0x04,
1968    OBJC_PR_readwrite = 0x08,
1969    OBJC_PR_retain    = 0x10,
1970    OBJC_PR_copy      = 0x20,
1971    OBJC_PR_nonatomic = 0x40,
1972    OBJC_PR_setter    = 0x80,
1973    OBJC_PR_atomic    = 0x100,
1974    OBJC_PR_weak      = 0x200,
1975    OBJC_PR_strong    = 0x400,
1976    OBJC_PR_unsafe_unretained = 0x800
1977    // Adding a property should change NumPropertyAttrsBits
1978  };
1979
1980  enum {
1981    /// \brief Number of bits fitting all the property attributes.
1982    NumPropertyAttrsBits = 12
1983  };
1984
1985  enum SetterKind { Assign, Retain, Copy, Weak };
1986  enum PropertyControl { None, Required, Optional };
1987private:
1988  SourceLocation AtLoc;   // location of \@property
1989  SourceLocation LParenLoc; // location of '(' starting attribute list or null.
1990  TypeSourceInfo *DeclType;
1991  unsigned PropertyAttributes : NumPropertyAttrsBits;
1992  unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
1993  // \@required/\@optional
1994  unsigned PropertyImplementation : 2;
1995
1996  Selector GetterName;    // getter name of NULL if no getter
1997  Selector SetterName;    // setter name of NULL if no setter
1998
1999  ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method
2000  ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method
2001  ObjCIvarDecl *PropertyIvarDecl;   // Synthesize ivar for this property
2002
2003  ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2004                   SourceLocation AtLocation,  SourceLocation LParenLocation,
2005                   TypeSourceInfo *T)
2006    : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
2007      LParenLoc(LParenLocation), DeclType(T),
2008      PropertyAttributes(OBJC_PR_noattr),
2009      PropertyAttributesAsWritten(OBJC_PR_noattr),
2010      PropertyImplementation(None),
2011      GetterName(Selector()),
2012      SetterName(Selector()),
2013      GetterMethodDecl(0), SetterMethodDecl(0) , PropertyIvarDecl(0) {}
2014public:
2015  static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
2016                                  SourceLocation L,
2017                                  IdentifierInfo *Id, SourceLocation AtLocation,
2018                                  SourceLocation LParenLocation,
2019                                  TypeSourceInfo *T,
2020                                  PropertyControl propControl = None);
2021
2022  static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2023
2024  SourceLocation getAtLoc() const { return AtLoc; }
2025  void setAtLoc(SourceLocation L) { AtLoc = L; }
2026
2027  SourceLocation getLParenLoc() const { return LParenLoc; }
2028  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2029
2030  TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
2031  QualType getType() const { return DeclType->getType(); }
2032  void setType(TypeSourceInfo *T) { DeclType = T; }
2033
2034  PropertyAttributeKind getPropertyAttributes() const {
2035    return PropertyAttributeKind(PropertyAttributes);
2036  }
2037  void setPropertyAttributes(PropertyAttributeKind PRVal) {
2038    PropertyAttributes |= PRVal;
2039  }
2040
2041  PropertyAttributeKind getPropertyAttributesAsWritten() const {
2042    return PropertyAttributeKind(PropertyAttributesAsWritten);
2043  }
2044
2045  bool hasWrittenStorageAttribute() const {
2046    return PropertyAttributesAsWritten & (OBJC_PR_assign | OBJC_PR_copy |
2047        OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong |
2048        OBJC_PR_weak);
2049  }
2050
2051  void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
2052    PropertyAttributesAsWritten = PRVal;
2053  }
2054
2055 void makeitReadWriteAttribute() {
2056    PropertyAttributes &= ~OBJC_PR_readonly;
2057    PropertyAttributes |= OBJC_PR_readwrite;
2058 }
2059
2060  // Helper methods for accessing attributes.
2061
2062  /// isReadOnly - Return true iff the property has a setter.
2063  bool isReadOnly() const {
2064    return (PropertyAttributes & OBJC_PR_readonly);
2065  }
2066
2067  /// isAtomic - Return true if the property is atomic.
2068  bool isAtomic() const {
2069    return (PropertyAttributes & OBJC_PR_atomic);
2070  }
2071
2072  /// isRetaining - Return true if the property retains its value.
2073  bool isRetaining() const {
2074    return (PropertyAttributes &
2075            (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
2076  }
2077
2078  /// getSetterKind - Return the method used for doing assignment in
2079  /// the property setter. This is only valid if the property has been
2080  /// defined to have a setter.
2081  SetterKind getSetterKind() const {
2082    if (PropertyAttributes & OBJC_PR_strong)
2083      return getType()->isBlockPointerType() ? Copy : Retain;
2084    if (PropertyAttributes & OBJC_PR_retain)
2085      return Retain;
2086    if (PropertyAttributes & OBJC_PR_copy)
2087      return Copy;
2088    if (PropertyAttributes & OBJC_PR_weak)
2089      return Weak;
2090    return Assign;
2091  }
2092
2093  Selector getGetterName() const { return GetterName; }
2094  void setGetterName(Selector Sel) { GetterName = Sel; }
2095
2096  Selector getSetterName() const { return SetterName; }
2097  void setSetterName(Selector Sel) { SetterName = Sel; }
2098
2099  ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
2100  void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
2101
2102  ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
2103  void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
2104
2105  // Related to \@optional/\@required declared in \@protocol
2106  void setPropertyImplementation(PropertyControl pc) {
2107    PropertyImplementation = pc;
2108  }
2109  PropertyControl getPropertyImplementation() const {
2110    return PropertyControl(PropertyImplementation);
2111  }
2112
2113  void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
2114    PropertyIvarDecl = Ivar;
2115  }
2116  ObjCIvarDecl *getPropertyIvarDecl() const {
2117    return PropertyIvarDecl;
2118  }
2119
2120  virtual SourceRange getSourceRange() const LLVM_READONLY {
2121    return SourceRange(AtLoc, getLocation());
2122  }
2123
2124  /// Get the default name of the synthesized ivar.
2125  IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
2126
2127  /// Lookup a property by name in the specified DeclContext.
2128  static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
2129                                            IdentifierInfo *propertyID);
2130
2131  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2132  static bool classofKind(Kind K) { return K == ObjCProperty; }
2133};
2134
2135/// ObjCPropertyImplDecl - Represents implementation declaration of a property
2136/// in a class or category implementation block. For example:
2137/// \@synthesize prop1 = ivar1;
2138///
2139class ObjCPropertyImplDecl : public Decl {
2140public:
2141  enum Kind {
2142    Synthesize,
2143    Dynamic
2144  };
2145private:
2146  SourceLocation AtLoc;   // location of \@synthesize or \@dynamic
2147
2148  /// \brief For \@synthesize, the location of the ivar, if it was written in
2149  /// the source code.
2150  ///
2151  /// \code
2152  /// \@synthesize int a = b
2153  /// \endcode
2154  SourceLocation IvarLoc;
2155
2156  /// Property declaration being implemented
2157  ObjCPropertyDecl *PropertyDecl;
2158
2159  /// Null for \@dynamic. Required for \@synthesize.
2160  ObjCIvarDecl *PropertyIvarDecl;
2161
2162  /// Null for \@dynamic. Non-null if property must be copy-constructed in
2163  /// getter.
2164  Expr *GetterCXXConstructor;
2165
2166  /// Null for \@dynamic. Non-null if property has assignment operator to call
2167  /// in Setter synthesis.
2168  Expr *SetterCXXAssignment;
2169
2170  ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2171                       ObjCPropertyDecl *property,
2172                       Kind PK,
2173                       ObjCIvarDecl *ivarDecl,
2174                       SourceLocation ivarLoc)
2175    : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2176      IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl),
2177      GetterCXXConstructor(0), SetterCXXAssignment(0) {
2178    assert (PK == Dynamic || PropertyIvarDecl);
2179  }
2180
2181public:
2182  static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2183                                      SourceLocation atLoc, SourceLocation L,
2184                                      ObjCPropertyDecl *property,
2185                                      Kind PK,
2186                                      ObjCIvarDecl *ivarDecl,
2187                                      SourceLocation ivarLoc);
2188
2189  static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2190
2191  virtual SourceRange getSourceRange() const LLVM_READONLY;
2192
2193  SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
2194  void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2195
2196  ObjCPropertyDecl *getPropertyDecl() const {
2197    return PropertyDecl;
2198  }
2199  void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2200
2201  Kind getPropertyImplementation() const {
2202    return PropertyIvarDecl ? Synthesize : Dynamic;
2203  }
2204
2205  ObjCIvarDecl *getPropertyIvarDecl() const {
2206    return PropertyIvarDecl;
2207  }
2208  SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2209
2210  void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2211                           SourceLocation IvarLoc) {
2212    PropertyIvarDecl = Ivar;
2213    this->IvarLoc = IvarLoc;
2214  }
2215
2216  /// \brief For \@synthesize, returns true if an ivar name was explicitly
2217  /// specified.
2218  ///
2219  /// \code
2220  /// \@synthesize int a = b; // true
2221  /// \@synthesize int a; // false
2222  /// \endcode
2223  bool isIvarNameSpecified() const {
2224    return IvarLoc.isValid() && IvarLoc != getLocation();
2225  }
2226
2227  Expr *getGetterCXXConstructor() const {
2228    return GetterCXXConstructor;
2229  }
2230  void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2231    GetterCXXConstructor = getterCXXConstructor;
2232  }
2233
2234  Expr *getSetterCXXAssignment() const {
2235    return SetterCXXAssignment;
2236  }
2237  void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2238    SetterCXXAssignment = setterCXXAssignment;
2239  }
2240
2241  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2242  static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2243
2244  friend class ASTDeclReader;
2245};
2246
2247template<bool (*Filter)(ObjCCategoryDecl *)>
2248void
2249ObjCInterfaceDecl::filtered_category_iterator<Filter>::
2250findAcceptableCategory() {
2251  while (Current && !Filter(Current))
2252    Current = Current->getNextClassCategoryRaw();
2253}
2254
2255template<bool (*Filter)(ObjCCategoryDecl *)>
2256inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2257ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2258  Current = Current->getNextClassCategoryRaw();
2259  findAcceptableCategory();
2260  return *this;
2261}
2262
2263inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2264  return !Cat->isHidden();
2265}
2266
2267inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2268  return Cat->IsClassExtension() && !Cat->isHidden();
2269}
2270
2271inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2272  return Cat->IsClassExtension();
2273}
2274
2275}  // end namespace clang
2276#endif
2277