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