DeclObjC.h revision b36ea375e20f71df19c101fa2399b7ea3a607e04
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  virtual void collectPropertiesToImplement(PropertyMap& PM) const {}
549
550  SourceLocation getAtStartLoc() const { return AtStart; }
551  void setAtStartLoc(SourceLocation Loc) { AtStart = Loc; }
552
553  // Marks the end of the container.
554  SourceRange getAtEndRange() const {
555    return AtEnd;
556  }
557  void setAtEndRange(SourceRange atEnd) {
558    AtEnd = atEnd;
559  }
560
561  virtual SourceRange getSourceRange() const LLVM_READONLY {
562    return SourceRange(AtStart, getAtEndRange().getEnd());
563  }
564
565  // Implement isa/cast/dyncast/etc.
566  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
567  static bool classofKind(Kind K) {
568    return K >= firstObjCContainer &&
569           K <= lastObjCContainer;
570  }
571
572  static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
573    return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
574  }
575  static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
576    return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
577  }
578};
579
580/// \brief Represents an ObjC class declaration.
581///
582/// For example:
583///
584/// \code
585///   // MostPrimitive declares no super class (not particularly useful).
586///   \@interface MostPrimitive
587///     // no instance variables or methods.
588///   \@end
589///
590///   // NSResponder inherits from NSObject & implements NSCoding (a protocol).
591///   \@interface NSResponder : NSObject \<NSCoding>
592///   { // instance variables are represented by ObjCIvarDecl.
593///     id nextResponder; // nextResponder instance variable.
594///   }
595///   - (NSResponder *)nextResponder; // return a pointer to NSResponder.
596///   - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
597///   \@end                                    // to an NSEvent.
598/// \endcode
599///
600///   Unlike C/C++, forward class declarations are accomplished with \@class.
601///   Unlike C/C++, \@class allows for a list of classes to be forward declared.
602///   Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
603///   typically inherit from NSObject (an exception is NSProxy).
604///
605class ObjCInterfaceDecl : public ObjCContainerDecl
606                        , public Redeclarable<ObjCInterfaceDecl> {
607  virtual void anchor();
608
609  /// TypeForDecl - This indicates the Type object that represents this
610  /// TypeDecl.  It is a cache maintained by ASTContext::getObjCInterfaceType
611  mutable const Type *TypeForDecl;
612  friend class ASTContext;
613
614  struct DefinitionData {
615    /// \brief The definition of this class, for quick access from any
616    /// declaration.
617    ObjCInterfaceDecl *Definition;
618
619    /// Class's super class.
620    ObjCInterfaceDecl *SuperClass;
621
622    /// Protocols referenced in the \@interface  declaration
623    ObjCProtocolList ReferencedProtocols;
624
625    /// Protocols reference in both the \@interface and class extensions.
626    ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
627
628    /// \brief List of categories and class extensions defined for this class.
629    ///
630    /// Categories are stored as a linked list in the AST, since the categories
631    /// and class extensions come long after the initial interface declaration,
632    /// and we avoid dynamically-resized arrays in the AST wherever possible.
633    ObjCCategoryDecl *CategoryList;
634
635    /// IvarList - List of all ivars defined by this class; including class
636    /// extensions and implementation. This list is built lazily.
637    ObjCIvarDecl *IvarList;
638
639    /// \brief Indicates that the contents of this Objective-C class will be
640    /// completed by the external AST source when required.
641    mutable bool ExternallyCompleted : 1;
642
643    /// \brief The location of the superclass, if any.
644    SourceLocation SuperClassLoc;
645
646    /// \brief The location of the last location in this declaration, before
647    /// the properties/methods. For example, this will be the '>', '}', or
648    /// identifier,
649    SourceLocation EndLoc;
650
651    DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarList(),
652                       ExternallyCompleted() { }
653  };
654
655  ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
656                    SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
657                    bool isInternal);
658
659  void LoadExternalDefinition() const;
660
661  /// \brief Contains a pointer to the data associated with this class,
662  /// which will be NULL if this class has not yet been defined.
663  DefinitionData *Data;
664
665  DefinitionData &data() const {
666    assert(Data != 0 && "Declaration has no definition!");
667    return *Data;
668  }
669
670  /// \brief Allocate the definition data for this class.
671  void allocateDefinitionData();
672
673  typedef Redeclarable<ObjCInterfaceDecl> redeclarable_base;
674  virtual ObjCInterfaceDecl *getNextRedeclaration() {
675    return RedeclLink.getNext();
676  }
677  virtual ObjCInterfaceDecl *getPreviousDeclImpl() {
678    return getPreviousDecl();
679  }
680  virtual ObjCInterfaceDecl *getMostRecentDeclImpl() {
681    return getMostRecentDecl();
682  }
683
684public:
685  static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
686                                   SourceLocation atLoc,
687                                   IdentifierInfo *Id,
688                                   ObjCInterfaceDecl *PrevDecl,
689                                   SourceLocation ClassLoc = SourceLocation(),
690                                   bool isInternal = false);
691
692  static ObjCInterfaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
693
694  virtual SourceRange getSourceRange() const LLVM_READONLY {
695    if (isThisDeclarationADefinition())
696      return ObjCContainerDecl::getSourceRange();
697
698    return SourceRange(getAtStartLoc(), getLocation());
699  }
700
701  /// \brief Indicate that this Objective-C class is complete, but that
702  /// the external AST source will be responsible for filling in its contents
703  /// when a complete class is required.
704  void setExternallyCompleted();
705
706  const ObjCProtocolList &getReferencedProtocols() const {
707    assert(hasDefinition() && "Caller did not check for forward reference!");
708    if (data().ExternallyCompleted)
709      LoadExternalDefinition();
710
711    return data().ReferencedProtocols;
712  }
713
714  ObjCImplementationDecl *getImplementation() const;
715  void setImplementation(ObjCImplementationDecl *ImplD);
716
717  ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
718
719  // Get the local instance/class method declared in a category.
720  ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
721  ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
722  ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
723    return isInstance ? getInstanceMethod(Sel)
724                      : getClassMethod(Sel);
725  }
726
727  typedef ObjCProtocolList::iterator protocol_iterator;
728
729  protocol_iterator protocol_begin() const {
730    // FIXME: Should make sure no callers ever do this.
731    if (!hasDefinition())
732      return protocol_iterator();
733
734    if (data().ExternallyCompleted)
735      LoadExternalDefinition();
736
737    return data().ReferencedProtocols.begin();
738  }
739  protocol_iterator protocol_end() const {
740    // FIXME: Should make sure no callers ever do this.
741    if (!hasDefinition())
742      return protocol_iterator();
743
744    if (data().ExternallyCompleted)
745      LoadExternalDefinition();
746
747    return data().ReferencedProtocols.end();
748  }
749
750  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
751
752  protocol_loc_iterator protocol_loc_begin() const {
753    // FIXME: Should make sure no callers ever do this.
754    if (!hasDefinition())
755      return protocol_loc_iterator();
756
757    if (data().ExternallyCompleted)
758      LoadExternalDefinition();
759
760    return data().ReferencedProtocols.loc_begin();
761  }
762
763  protocol_loc_iterator protocol_loc_end() const {
764    // FIXME: Should make sure no callers ever do this.
765    if (!hasDefinition())
766      return protocol_loc_iterator();
767
768    if (data().ExternallyCompleted)
769      LoadExternalDefinition();
770
771    return data().ReferencedProtocols.loc_end();
772  }
773
774  typedef ObjCList<ObjCProtocolDecl>::iterator all_protocol_iterator;
775
776  all_protocol_iterator all_referenced_protocol_begin() const {
777    // FIXME: Should make sure no callers ever do this.
778    if (!hasDefinition())
779      return all_protocol_iterator();
780
781    if (data().ExternallyCompleted)
782      LoadExternalDefinition();
783
784    return data().AllReferencedProtocols.empty()
785             ? protocol_begin()
786             : data().AllReferencedProtocols.begin();
787  }
788  all_protocol_iterator all_referenced_protocol_end() const {
789    // FIXME: Should make sure no callers ever do this.
790    if (!hasDefinition())
791      return all_protocol_iterator();
792
793    if (data().ExternallyCompleted)
794      LoadExternalDefinition();
795
796    return data().AllReferencedProtocols.empty()
797             ? protocol_end()
798             : data().AllReferencedProtocols.end();
799  }
800
801  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
802
803  ivar_iterator ivar_begin() const {
804    if (const ObjCInterfaceDecl *Def = getDefinition())
805      return ivar_iterator(Def->decls_begin());
806
807    // FIXME: Should make sure no callers ever do this.
808    return ivar_iterator();
809  }
810  ivar_iterator ivar_end() const {
811    if (const ObjCInterfaceDecl *Def = getDefinition())
812      return ivar_iterator(Def->decls_end());
813
814    // FIXME: Should make sure no callers ever do this.
815    return ivar_iterator();
816  }
817
818  unsigned ivar_size() const {
819    return std::distance(ivar_begin(), ivar_end());
820  }
821
822  bool ivar_empty() const { return ivar_begin() == ivar_end(); }
823
824  ObjCIvarDecl *all_declared_ivar_begin();
825  const ObjCIvarDecl *all_declared_ivar_begin() const {
826    // Even though this modifies IvarList, it's conceptually const:
827    // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
828    return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
829  }
830  void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
831
832  /// setProtocolList - Set the list of protocols that this interface
833  /// implements.
834  void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
835                       const SourceLocation *Locs, ASTContext &C) {
836    data().ReferencedProtocols.set(List, Num, Locs, C);
837  }
838
839  /// mergeClassExtensionProtocolList - Merge class extension's protocol list
840  /// into the protocol list for this class.
841  void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
842                                       unsigned Num,
843                                       ASTContext &C);
844
845  /// \brief Determine whether this particular declaration of this class is
846  /// actually also a definition.
847  bool isThisDeclarationADefinition() const {
848    return Data && Data->Definition == this;
849  }
850
851  /// \brief Determine whether this class has been defined.
852  bool hasDefinition() const { return Data; }
853
854  /// \brief Retrieve the definition of this class, or NULL if this class
855  /// has been forward-declared (with \@class) but not yet defined (with
856  /// \@interface).
857  ObjCInterfaceDecl *getDefinition() {
858    return hasDefinition()? Data->Definition : 0;
859  }
860
861  /// \brief Retrieve the definition of this class, or NULL if this class
862  /// has been forward-declared (with \@class) but not yet defined (with
863  /// \@interface).
864  const ObjCInterfaceDecl *getDefinition() const {
865    return hasDefinition()? Data->Definition : 0;
866  }
867
868  /// \brief Starts the definition of this Objective-C class, taking it from
869  /// a forward declaration (\@class) to a definition (\@interface).
870  void startDefinition();
871
872  ObjCInterfaceDecl *getSuperClass() const {
873    // FIXME: Should make sure no callers ever do this.
874    if (!hasDefinition())
875      return 0;
876
877    if (data().ExternallyCompleted)
878      LoadExternalDefinition();
879
880    return data().SuperClass;
881  }
882
883  void setSuperClass(ObjCInterfaceDecl * superCls) {
884    data().SuperClass =
885      (superCls && superCls->hasDefinition()) ? superCls->getDefinition()
886                                              : superCls;
887  }
888
889  ObjCCategoryDecl* getCategoryList() const {
890    // FIXME: Should make sure no callers ever do this.
891    if (!hasDefinition())
892      return 0;
893
894    if (data().ExternallyCompleted)
895      LoadExternalDefinition();
896
897    return data().CategoryList;
898  }
899
900  void setCategoryList(ObjCCategoryDecl *category) {
901    data().CategoryList = category;
902  }
903
904  ObjCCategoryDecl* getFirstClassExtension() const;
905
906  ObjCPropertyDecl
907    *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId) const;
908
909  virtual void collectPropertiesToImplement(PropertyMap& PM) const;
910
911  /// isSuperClassOf - Return true if this class is the specified class or is a
912  /// super class of the specified interface class.
913  bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
914    // If RHS is derived from LHS it is OK; else it is not OK.
915    while (I != NULL) {
916      if (declaresSameEntity(this, I))
917        return true;
918
919      I = I->getSuperClass();
920    }
921    return false;
922  }
923
924  /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
925  /// to be incompatible with __weak references. Returns true if it is.
926  bool isArcWeakrefUnavailable() const {
927    const ObjCInterfaceDecl *Class = this;
928    while (Class) {
929      if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
930        return true;
931      Class = Class->getSuperClass();
932   }
933   return false;
934  }
935
936  /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
937  /// classes must not be auto-synthesized. Returns class decl. if it must not
938  /// be; 0, otherwise.
939  const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const {
940    const ObjCInterfaceDecl *Class = this;
941    while (Class) {
942      if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
943        return Class;
944      Class = Class->getSuperClass();
945   }
946   return 0;
947  }
948
949  ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
950                                       ObjCInterfaceDecl *&ClassDeclared);
951  ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
952    ObjCInterfaceDecl *ClassDeclared;
953    return lookupInstanceVariable(IVarName, ClassDeclared);
954  }
955
956  // Lookup a method. First, we search locally. If a method isn't
957  // found, we search referenced protocols and class categories.
958  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
959                               bool shallowCategoryLookup= false) const;
960  ObjCMethodDecl *lookupInstanceMethod(Selector Sel,
961                            bool shallowCategoryLookup = false) const {
962    return lookupMethod(Sel, true/*isInstance*/, shallowCategoryLookup);
963  }
964  ObjCMethodDecl *lookupClassMethod(Selector Sel,
965                     bool shallowCategoryLookup = false) const {
966    return lookupMethod(Sel, false/*isInstance*/, shallowCategoryLookup);
967  }
968  ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
969
970  /// \brief Lookup a method in the classes implementation hierarchy.
971  ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
972                                      bool Instance=true) const;
973
974  ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
975    return lookupPrivateMethod(Sel, false);
976  }
977
978  SourceLocation getEndOfDefinitionLoc() const {
979    if (!hasDefinition())
980      return getLocation();
981
982    return data().EndLoc;
983  }
984
985  void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
986
987  void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc = Loc; }
988  SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; }
989
990  /// isImplicitInterfaceDecl - check that this is an implicitly declared
991  /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
992  /// declaration without an \@interface declaration.
993  bool isImplicitInterfaceDecl() const {
994    return hasDefinition() ? Data->Definition->isImplicit() : isImplicit();
995  }
996
997  /// ClassImplementsProtocol - Checks that 'lProto' protocol
998  /// has been implemented in IDecl class, its super class or categories (if
999  /// lookupCategory is true).
1000  bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1001                               bool lookupCategory,
1002                               bool RHSIsQualifiedID = false);
1003
1004  typedef redeclarable_base::redecl_iterator redecl_iterator;
1005  using redeclarable_base::redecls_begin;
1006  using redeclarable_base::redecls_end;
1007  using redeclarable_base::getPreviousDecl;
1008  using redeclarable_base::getMostRecentDecl;
1009
1010  /// Retrieves the canonical declaration of this Objective-C class.
1011  ObjCInterfaceDecl *getCanonicalDecl() {
1012    return getFirstDeclaration();
1013  }
1014  const ObjCInterfaceDecl *getCanonicalDecl() const {
1015    return getFirstDeclaration();
1016  }
1017
1018  // Low-level accessor
1019  const Type *getTypeForDecl() const { return TypeForDecl; }
1020  void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1021
1022  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1023  static bool classofKind(Kind K) { return K == ObjCInterface; }
1024
1025  friend class ASTReader;
1026  friend class ASTDeclReader;
1027  friend class ASTDeclWriter;
1028};
1029
1030/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1031/// instance variables are identical to C. The only exception is Objective-C
1032/// supports C++ style access control. For example:
1033///
1034///   \@interface IvarExample : NSObject
1035///   {
1036///     id defaultToProtected;
1037///   \@public:
1038///     id canBePublic; // same as C++.
1039///   \@protected:
1040///     id canBeProtected; // same as C++.
1041///   \@package:
1042///     id canBePackage; // framework visibility (not available in C++).
1043///   }
1044///
1045class ObjCIvarDecl : public FieldDecl {
1046  virtual void anchor();
1047
1048public:
1049  enum AccessControl {
1050    None, Private, Protected, Public, Package
1051  };
1052
1053private:
1054  ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1055               SourceLocation IdLoc, IdentifierInfo *Id,
1056               QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1057               bool synthesized)
1058    : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1059                /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1060      NextIvar(0), DeclAccess(ac), Synthesized(synthesized) {}
1061
1062public:
1063  static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1064                              SourceLocation StartLoc, SourceLocation IdLoc,
1065                              IdentifierInfo *Id, QualType T,
1066                              TypeSourceInfo *TInfo,
1067                              AccessControl ac, Expr *BW = NULL,
1068                              bool synthesized=false);
1069
1070  static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1071
1072  /// \brief Return the class interface that this ivar is logically contained
1073  /// in; this is either the interface where the ivar was declared, or the
1074  /// interface the ivar is conceptually a part of in the case of synthesized
1075  /// ivars.
1076  const ObjCInterfaceDecl *getContainingInterface() const;
1077
1078  ObjCIvarDecl *getNextIvar() { return NextIvar; }
1079  const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1080  void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1081
1082  void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1083
1084  AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1085
1086  AccessControl getCanonicalAccessControl() const {
1087    return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1088  }
1089
1090  void setSynthesize(bool synth) { Synthesized = synth; }
1091  bool getSynthesize() const { return Synthesized; }
1092
1093  // Implement isa/cast/dyncast/etc.
1094  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1095  static bool classofKind(Kind K) { return K == ObjCIvar; }
1096private:
1097  /// NextIvar - Next Ivar in the list of ivars declared in class; class's
1098  /// extensions and class's implementation
1099  ObjCIvarDecl *NextIvar;
1100
1101  // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
1102  unsigned DeclAccess : 3;
1103  unsigned Synthesized : 1;
1104};
1105
1106
1107/// \brief Represents a field declaration created by an \@defs(...).
1108class ObjCAtDefsFieldDecl : public FieldDecl {
1109  virtual void anchor();
1110  ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
1111                      SourceLocation IdLoc, IdentifierInfo *Id,
1112                      QualType T, Expr *BW)
1113    : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
1114                /*TInfo=*/0, // FIXME: Do ObjCAtDefs have declarators ?
1115                BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
1116
1117public:
1118  static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
1119                                     SourceLocation StartLoc,
1120                                     SourceLocation IdLoc, IdentifierInfo *Id,
1121                                     QualType T, Expr *BW);
1122
1123  static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1124
1125  // Implement isa/cast/dyncast/etc.
1126  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1127  static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
1128};
1129
1130/// \brief Represents an Objective-C protocol declaration.
1131///
1132/// Objective-C protocols declare a pure abstract type (i.e., no instance
1133/// variables are permitted).  Protocols originally drew inspiration from
1134/// C++ pure virtual functions (a C++ feature with nice semantics and lousy
1135/// syntax:-). Here is an example:
1136///
1137/// \code
1138/// \@protocol NSDraggingInfo <refproto1, refproto2>
1139/// - (NSWindow *)draggingDestinationWindow;
1140/// - (NSImage *)draggedImage;
1141/// \@end
1142/// \endcode
1143///
1144/// This says that NSDraggingInfo requires two methods and requires everything
1145/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
1146/// well.
1147///
1148/// \code
1149/// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
1150/// \@end
1151/// \endcode
1152///
1153/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
1154/// protocols are in distinct namespaces. For example, Cocoa defines both
1155/// an NSObject protocol and class (which isn't allowed in Java). As a result,
1156/// protocols are referenced using angle brackets as follows:
1157///
1158/// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
1159///
1160class ObjCProtocolDecl : public ObjCContainerDecl,
1161                         public Redeclarable<ObjCProtocolDecl> {
1162  virtual void anchor();
1163
1164  struct DefinitionData {
1165    // \brief The declaration that defines this protocol.
1166    ObjCProtocolDecl *Definition;
1167
1168    /// \brief Referenced protocols
1169    ObjCProtocolList ReferencedProtocols;
1170  };
1171
1172  DefinitionData *Data;
1173
1174  DefinitionData &data() const {
1175    assert(Data && "Objective-C protocol has no definition!");
1176    return *Data;
1177  }
1178
1179  ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
1180                   SourceLocation nameLoc, SourceLocation atStartLoc,
1181                   ObjCProtocolDecl *PrevDecl);
1182
1183  void allocateDefinitionData();
1184
1185  typedef Redeclarable<ObjCProtocolDecl> redeclarable_base;
1186  virtual ObjCProtocolDecl *getNextRedeclaration() {
1187    return RedeclLink.getNext();
1188  }
1189  virtual ObjCProtocolDecl *getPreviousDeclImpl() {
1190    return getPreviousDecl();
1191  }
1192  virtual ObjCProtocolDecl *getMostRecentDeclImpl() {
1193    return getMostRecentDecl();
1194  }
1195
1196public:
1197  static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
1198                                  IdentifierInfo *Id,
1199                                  SourceLocation nameLoc,
1200                                  SourceLocation atStartLoc,
1201                                  ObjCProtocolDecl *PrevDecl);
1202
1203  static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1204
1205  const ObjCProtocolList &getReferencedProtocols() const {
1206    assert(hasDefinition() && "No definition available!");
1207    return data().ReferencedProtocols;
1208  }
1209  typedef ObjCProtocolList::iterator protocol_iterator;
1210  protocol_iterator protocol_begin() const {
1211    if (!hasDefinition())
1212      return protocol_iterator();
1213
1214    return data().ReferencedProtocols.begin();
1215  }
1216  protocol_iterator protocol_end() const {
1217    if (!hasDefinition())
1218      return protocol_iterator();
1219
1220    return data().ReferencedProtocols.end();
1221  }
1222  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1223  protocol_loc_iterator protocol_loc_begin() const {
1224    if (!hasDefinition())
1225      return protocol_loc_iterator();
1226
1227    return data().ReferencedProtocols.loc_begin();
1228  }
1229  protocol_loc_iterator protocol_loc_end() const {
1230    if (!hasDefinition())
1231      return protocol_loc_iterator();
1232
1233    return data().ReferencedProtocols.loc_end();
1234  }
1235  unsigned protocol_size() const {
1236    if (!hasDefinition())
1237      return 0;
1238
1239    return data().ReferencedProtocols.size();
1240  }
1241
1242  /// setProtocolList - Set the list of protocols that this interface
1243  /// implements.
1244  void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1245                       const SourceLocation *Locs, ASTContext &C) {
1246    assert(Data && "Protocol is not defined");
1247    data().ReferencedProtocols.set(List, Num, Locs, C);
1248  }
1249
1250  ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
1251
1252  // Lookup a method. First, we search locally. If a method isn't
1253  // found, we search referenced protocols and class categories.
1254  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
1255  ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1256    return lookupMethod(Sel, true/*isInstance*/);
1257  }
1258  ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1259    return lookupMethod(Sel, false/*isInstance*/);
1260  }
1261
1262  /// \brief Determine whether this protocol has a definition.
1263  bool hasDefinition() const { return Data != 0; }
1264
1265  /// \brief Retrieve the definition of this protocol, if any.
1266  ObjCProtocolDecl *getDefinition() {
1267    return Data? Data->Definition : 0;
1268  }
1269
1270  /// \brief Retrieve the definition of this protocol, if any.
1271  const ObjCProtocolDecl *getDefinition() const {
1272    return Data? Data->Definition : 0;
1273  }
1274
1275  /// \brief Determine whether this particular declaration is also the
1276  /// definition.
1277  bool isThisDeclarationADefinition() const {
1278    return getDefinition() == this;
1279  }
1280
1281  /// \brief Starts the definition of this Objective-C protocol.
1282  void startDefinition();
1283
1284  virtual SourceRange getSourceRange() const LLVM_READONLY {
1285    if (isThisDeclarationADefinition())
1286      return ObjCContainerDecl::getSourceRange();
1287
1288    return SourceRange(getAtStartLoc(), getLocation());
1289  }
1290
1291  typedef redeclarable_base::redecl_iterator redecl_iterator;
1292  using redeclarable_base::redecls_begin;
1293  using redeclarable_base::redecls_end;
1294  using redeclarable_base::getPreviousDecl;
1295  using redeclarable_base::getMostRecentDecl;
1296
1297  /// Retrieves the canonical declaration of this Objective-C protocol.
1298  ObjCProtocolDecl *getCanonicalDecl() {
1299    return getFirstDeclaration();
1300  }
1301  const ObjCProtocolDecl *getCanonicalDecl() const {
1302    return getFirstDeclaration();
1303  }
1304
1305  virtual void collectPropertiesToImplement(PropertyMap& PM) const;
1306
1307  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1308  static bool classofKind(Kind K) { return K == ObjCProtocol; }
1309
1310  friend class ASTReader;
1311  friend class ASTDeclReader;
1312  friend class ASTDeclWriter;
1313};
1314
1315/// ObjCCategoryDecl - Represents a category declaration. A category allows
1316/// you to add methods to an existing class (without subclassing or modifying
1317/// the original class interface or implementation:-). Categories don't allow
1318/// you to add instance data. The following example adds "myMethod" to all
1319/// NSView's within a process:
1320///
1321/// \@interface NSView (MyViewMethods)
1322/// - myMethod;
1323/// \@end
1324///
1325/// Categories also allow you to split the implementation of a class across
1326/// several files (a feature more naturally supported in C++).
1327///
1328/// Categories were originally inspired by dynamic languages such as Common
1329/// Lisp and Smalltalk.  More traditional class-based languages (C++, Java)
1330/// don't support this level of dynamism, which is both powerful and dangerous.
1331///
1332class ObjCCategoryDecl : public ObjCContainerDecl {
1333  virtual void anchor();
1334
1335  /// Interface belonging to this category
1336  ObjCInterfaceDecl *ClassInterface;
1337
1338  /// referenced protocols in this category.
1339  ObjCProtocolList ReferencedProtocols;
1340
1341  /// Next category belonging to this class.
1342  /// FIXME: this should not be a singly-linked list.  Move storage elsewhere.
1343  ObjCCategoryDecl *NextClassCategory;
1344
1345  /// \brief The location of the category name in this declaration.
1346  SourceLocation CategoryNameLoc;
1347
1348  /// class extension may have private ivars.
1349  SourceLocation IvarLBraceLoc;
1350  SourceLocation IvarRBraceLoc;
1351
1352  ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1353                   SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
1354                   IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1355                   SourceLocation IvarLBraceLoc=SourceLocation(),
1356                   SourceLocation IvarRBraceLoc=SourceLocation())
1357    : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1358      ClassInterface(IDecl), NextClassCategory(0),
1359      CategoryNameLoc(CategoryNameLoc),
1360      IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
1361  }
1362public:
1363
1364  static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
1365                                  SourceLocation AtLoc,
1366                                  SourceLocation ClassNameLoc,
1367                                  SourceLocation CategoryNameLoc,
1368                                  IdentifierInfo *Id,
1369                                  ObjCInterfaceDecl *IDecl,
1370                                  SourceLocation IvarLBraceLoc=SourceLocation(),
1371                                  SourceLocation IvarRBraceLoc=SourceLocation());
1372  static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1373
1374  ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1375  const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1376
1377  ObjCCategoryImplDecl *getImplementation() const;
1378  void setImplementation(ObjCCategoryImplDecl *ImplD);
1379
1380  /// setProtocolList - Set the list of protocols that this interface
1381  /// implements.
1382  void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1383                       const SourceLocation *Locs, ASTContext &C) {
1384    ReferencedProtocols.set(List, Num, Locs, C);
1385  }
1386
1387  const ObjCProtocolList &getReferencedProtocols() const {
1388    return ReferencedProtocols;
1389  }
1390
1391  typedef ObjCProtocolList::iterator protocol_iterator;
1392  protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();}
1393  protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
1394  unsigned protocol_size() const { return ReferencedProtocols.size(); }
1395  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1396  protocol_loc_iterator protocol_loc_begin() const {
1397    return ReferencedProtocols.loc_begin();
1398  }
1399  protocol_loc_iterator protocol_loc_end() const {
1400    return ReferencedProtocols.loc_end();
1401  }
1402
1403  ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
1404
1405  bool IsClassExtension() const { return getIdentifier() == 0; }
1406  const ObjCCategoryDecl *getNextClassExtension() const;
1407
1408  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1409  ivar_iterator ivar_begin() const {
1410    return ivar_iterator(decls_begin());
1411  }
1412  ivar_iterator ivar_end() const {
1413    return ivar_iterator(decls_end());
1414  }
1415  unsigned ivar_size() const {
1416    return std::distance(ivar_begin(), ivar_end());
1417  }
1418  bool ivar_empty() const {
1419    return ivar_begin() == ivar_end();
1420  }
1421
1422  SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1423  void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
1424
1425  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
1426  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
1427  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
1428  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1429
1430  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1431  static bool classofKind(Kind K) { return K == ObjCCategory; }
1432
1433  friend class ASTDeclReader;
1434  friend class ASTDeclWriter;
1435};
1436
1437class ObjCImplDecl : public ObjCContainerDecl {
1438  virtual void anchor();
1439
1440  /// Class interface for this class/category implementation
1441  ObjCInterfaceDecl *ClassInterface;
1442
1443protected:
1444  ObjCImplDecl(Kind DK, DeclContext *DC,
1445               ObjCInterfaceDecl *classInterface,
1446               SourceLocation nameLoc, SourceLocation atStartLoc)
1447    : ObjCContainerDecl(DK, DC,
1448                        classInterface? classInterface->getIdentifier() : 0,
1449                        nameLoc, atStartLoc),
1450      ClassInterface(classInterface) {}
1451
1452public:
1453  const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1454  ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1455  void setClassInterface(ObjCInterfaceDecl *IFace);
1456
1457  void addInstanceMethod(ObjCMethodDecl *method) {
1458    // FIXME: Context should be set correctly before we get here.
1459    method->setLexicalDeclContext(this);
1460    addDecl(method);
1461  }
1462  void addClassMethod(ObjCMethodDecl *method) {
1463    // FIXME: Context should be set correctly before we get here.
1464    method->setLexicalDeclContext(this);
1465    addDecl(method);
1466  }
1467
1468  void addPropertyImplementation(ObjCPropertyImplDecl *property);
1469
1470  ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const;
1471  ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
1472
1473  // Iterator access to properties.
1474  typedef specific_decl_iterator<ObjCPropertyImplDecl> propimpl_iterator;
1475  propimpl_iterator propimpl_begin() const {
1476    return propimpl_iterator(decls_begin());
1477  }
1478  propimpl_iterator propimpl_end() const {
1479    return propimpl_iterator(decls_end());
1480  }
1481
1482  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1483  static bool classofKind(Kind K) {
1484    return K >= firstObjCImpl && K <= lastObjCImpl;
1485  }
1486};
1487
1488/// ObjCCategoryImplDecl - An object of this class encapsulates a category
1489/// \@implementation declaration. If a category class has declaration of a
1490/// property, its implementation must be specified in the category's
1491/// \@implementation declaration. Example:
1492/// \@interface I \@end
1493/// \@interface I(CATEGORY)
1494///    \@property int p1, d1;
1495/// \@end
1496/// \@implementation I(CATEGORY)
1497///  \@dynamic p1,d1;
1498/// \@end
1499///
1500/// ObjCCategoryImplDecl
1501class ObjCCategoryImplDecl : public ObjCImplDecl {
1502  virtual void anchor();
1503
1504  // Category name
1505  IdentifierInfo *Id;
1506
1507  // Category name location
1508  SourceLocation CategoryNameLoc;
1509
1510  ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
1511                       ObjCInterfaceDecl *classInterface,
1512                       SourceLocation nameLoc, SourceLocation atStartLoc,
1513                       SourceLocation CategoryNameLoc)
1514    : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartLoc),
1515      Id(Id), CategoryNameLoc(CategoryNameLoc) {}
1516public:
1517  static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
1518                                      IdentifierInfo *Id,
1519                                      ObjCInterfaceDecl *classInterface,
1520                                      SourceLocation nameLoc,
1521                                      SourceLocation atStartLoc,
1522                                      SourceLocation CategoryNameLoc);
1523  static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1524
1525  /// getIdentifier - Get the identifier that names the category
1526  /// interface associated with this implementation.
1527  /// FIXME: This is a bad API, we are overriding the NamedDecl::getIdentifier()
1528  /// to mean something different. For example:
1529  /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()
1530  /// returns the class interface name, whereas
1531  /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()
1532  /// returns the category name.
1533  IdentifierInfo *getIdentifier() const {
1534    return Id;
1535  }
1536  void setIdentifier(IdentifierInfo *II) { Id = II; }
1537
1538  ObjCCategoryDecl *getCategoryDecl() const;
1539
1540  SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1541
1542  /// getName - Get the name of identifier for the class interface associated
1543  /// with this implementation as a StringRef.
1544  //
1545  // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean
1546  // something different.
1547  StringRef getName() const {
1548    return Id ? Id->getNameStart() : "";
1549  }
1550
1551  /// @brief Get the name of the class associated with this interface.
1552  //
1553  // FIXME: Deprecated, move clients to getName().
1554  std::string getNameAsString() const {
1555    return getName();
1556  }
1557
1558  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1559  static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
1560
1561  friend class ASTDeclReader;
1562  friend class ASTDeclWriter;
1563};
1564
1565raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
1566
1567/// ObjCImplementationDecl - Represents a class definition - this is where
1568/// method definitions are specified. For example:
1569///
1570/// @code
1571/// \@implementation MyClass
1572/// - (void)myMethod { /* do something */ }
1573/// \@end
1574/// @endcode
1575///
1576/// Typically, instance variables are specified in the class interface,
1577/// *not* in the implementation. Nevertheless (for legacy reasons), we
1578/// allow instance variables to be specified in the implementation.  When
1579/// specified, they need to be *identical* to the interface.
1580///
1581class ObjCImplementationDecl : public ObjCImplDecl {
1582  virtual void anchor();
1583  /// Implementation Class's super class.
1584  ObjCInterfaceDecl *SuperClass;
1585  /// \@implementation may have private ivars.
1586  SourceLocation IvarLBraceLoc;
1587  SourceLocation IvarRBraceLoc;
1588
1589  /// Support for ivar initialization.
1590  /// IvarInitializers - The arguments used to initialize the ivars
1591  CXXCtorInitializer **IvarInitializers;
1592  unsigned NumIvarInitializers;
1593
1594  /// Do the ivars of this class require initialization other than
1595  /// zero-initialization?
1596  bool HasNonZeroConstructors : 1;
1597
1598  /// Do the ivars of this class require non-trivial destruction?
1599  bool HasDestructors : 1;
1600
1601  ObjCImplementationDecl(DeclContext *DC,
1602                         ObjCInterfaceDecl *classInterface,
1603                         ObjCInterfaceDecl *superDecl,
1604                         SourceLocation nameLoc, SourceLocation atStartLoc,
1605                         SourceLocation IvarLBraceLoc=SourceLocation(),
1606                         SourceLocation IvarRBraceLoc=SourceLocation())
1607    : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStartLoc),
1608       SuperClass(superDecl), IvarLBraceLoc(IvarLBraceLoc),
1609       IvarRBraceLoc(IvarRBraceLoc),
1610       IvarInitializers(0), NumIvarInitializers(0),
1611       HasNonZeroConstructors(false), HasDestructors(false) {}
1612public:
1613  static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
1614                                        ObjCInterfaceDecl *classInterface,
1615                                        ObjCInterfaceDecl *superDecl,
1616                                        SourceLocation nameLoc,
1617                                        SourceLocation atStartLoc,
1618                                        SourceLocation IvarLBraceLoc=SourceLocation(),
1619                                        SourceLocation IvarRBraceLoc=SourceLocation());
1620
1621  static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1622
1623  /// init_iterator - Iterates through the ivar initializer list.
1624  typedef CXXCtorInitializer **init_iterator;
1625
1626  /// init_const_iterator - Iterates through the ivar initializer list.
1627  typedef CXXCtorInitializer * const * init_const_iterator;
1628
1629  /// init_begin() - Retrieve an iterator to the first initializer.
1630  init_iterator       init_begin()       { return IvarInitializers; }
1631  /// begin() - Retrieve an iterator to the first initializer.
1632  init_const_iterator init_begin() const { return IvarInitializers; }
1633
1634  /// init_end() - Retrieve an iterator past the last initializer.
1635  init_iterator       init_end()       {
1636    return IvarInitializers + NumIvarInitializers;
1637  }
1638  /// end() - Retrieve an iterator past the last initializer.
1639  init_const_iterator init_end() const {
1640    return IvarInitializers + NumIvarInitializers;
1641  }
1642  /// getNumArgs - Number of ivars which must be initialized.
1643  unsigned getNumIvarInitializers() const {
1644    return NumIvarInitializers;
1645  }
1646
1647  void setNumIvarInitializers(unsigned numNumIvarInitializers) {
1648    NumIvarInitializers = numNumIvarInitializers;
1649  }
1650
1651  void setIvarInitializers(ASTContext &C,
1652                           CXXCtorInitializer ** initializers,
1653                           unsigned numInitializers);
1654
1655  /// Do any of the ivars of this class (not counting its base classes)
1656  /// require construction other than zero-initialization?
1657  bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
1658  void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
1659
1660  /// Do any of the ivars of this class (not counting its base classes)
1661  /// require non-trivial destruction?
1662  bool hasDestructors() const { return HasDestructors; }
1663  void setHasDestructors(bool val) { HasDestructors = val; }
1664
1665  /// getIdentifier - Get the identifier that names the class
1666  /// interface associated with this implementation.
1667  IdentifierInfo *getIdentifier() const {
1668    return getClassInterface()->getIdentifier();
1669  }
1670
1671  /// getName - Get the name of identifier for the class interface associated
1672  /// with this implementation as a StringRef.
1673  //
1674  // FIXME: This is a bad API, we are overriding the NamedDecl::getName, to mean
1675  // something different.
1676  StringRef getName() const {
1677    assert(getIdentifier() && "Name is not a simple identifier");
1678    return getIdentifier()->getName();
1679  }
1680
1681  /// @brief Get the name of the class associated with this interface.
1682  //
1683  // FIXME: Move to StringRef API.
1684  std::string getNameAsString() const {
1685    return getName();
1686  }
1687
1688  const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
1689  ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
1690
1691  void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
1692
1693  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
1694  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
1695  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
1696  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1697
1698  typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1699  ivar_iterator ivar_begin() const {
1700    return ivar_iterator(decls_begin());
1701  }
1702  ivar_iterator ivar_end() const {
1703    return ivar_iterator(decls_end());
1704  }
1705  unsigned ivar_size() const {
1706    return std::distance(ivar_begin(), ivar_end());
1707  }
1708  bool ivar_empty() const {
1709    return ivar_begin() == ivar_end();
1710  }
1711
1712  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1713  static bool classofKind(Kind K) { return K == ObjCImplementation; }
1714
1715  friend class ASTDeclReader;
1716  friend class ASTDeclWriter;
1717};
1718
1719raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
1720
1721/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
1722/// declared as \@compatibility_alias alias class.
1723class ObjCCompatibleAliasDecl : public NamedDecl {
1724  virtual void anchor();
1725  /// Class that this is an alias of.
1726  ObjCInterfaceDecl *AliasedClass;
1727
1728  ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
1729                          ObjCInterfaceDecl* aliasedClass)
1730    : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
1731public:
1732  static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
1733                                         SourceLocation L, IdentifierInfo *Id,
1734                                         ObjCInterfaceDecl* aliasedClass);
1735
1736  static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
1737                                                     unsigned ID);
1738
1739  const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
1740  ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
1741  void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
1742
1743  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1744  static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
1745
1746};
1747
1748/// \brief Represents one property declaration in an Objective-C interface.
1749///
1750/// For example:
1751/// \code{.mm}
1752/// \@property (assign, readwrite) int MyProperty;
1753/// \endcode
1754class ObjCPropertyDecl : public NamedDecl {
1755  virtual void anchor();
1756public:
1757  enum PropertyAttributeKind {
1758    OBJC_PR_noattr    = 0x00,
1759    OBJC_PR_readonly  = 0x01,
1760    OBJC_PR_getter    = 0x02,
1761    OBJC_PR_assign    = 0x04,
1762    OBJC_PR_readwrite = 0x08,
1763    OBJC_PR_retain    = 0x10,
1764    OBJC_PR_copy      = 0x20,
1765    OBJC_PR_nonatomic = 0x40,
1766    OBJC_PR_setter    = 0x80,
1767    OBJC_PR_atomic    = 0x100,
1768    OBJC_PR_weak      = 0x200,
1769    OBJC_PR_strong    = 0x400,
1770    OBJC_PR_unsafe_unretained = 0x800
1771    // Adding a property should change NumPropertyAttrsBits
1772  };
1773
1774  enum {
1775    /// \brief Number of bits fitting all the property attributes.
1776    NumPropertyAttrsBits = 12
1777  };
1778
1779  enum SetterKind { Assign, Retain, Copy, Weak };
1780  enum PropertyControl { None, Required, Optional };
1781private:
1782  SourceLocation AtLoc;   // location of \@property
1783  SourceLocation LParenLoc; // location of '(' starting attribute list or null.
1784  TypeSourceInfo *DeclType;
1785  unsigned PropertyAttributes : NumPropertyAttrsBits;
1786  unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
1787  // \@required/\@optional
1788  unsigned PropertyImplementation : 2;
1789
1790  Selector GetterName;    // getter name of NULL if no getter
1791  Selector SetterName;    // setter name of NULL if no setter
1792
1793  ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method
1794  ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method
1795  ObjCIvarDecl *PropertyIvarDecl;   // Synthesize ivar for this property
1796
1797  ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
1798                   SourceLocation AtLocation,  SourceLocation LParenLocation,
1799                   TypeSourceInfo *T)
1800    : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
1801      LParenLoc(LParenLocation), DeclType(T),
1802      PropertyAttributes(OBJC_PR_noattr),
1803      PropertyAttributesAsWritten(OBJC_PR_noattr),
1804      PropertyImplementation(None),
1805      GetterName(Selector()),
1806      SetterName(Selector()),
1807      GetterMethodDecl(0), SetterMethodDecl(0) , PropertyIvarDecl(0) {}
1808public:
1809  static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
1810                                  SourceLocation L,
1811                                  IdentifierInfo *Id, SourceLocation AtLocation,
1812                                  SourceLocation LParenLocation,
1813                                  TypeSourceInfo *T,
1814                                  PropertyControl propControl = None);
1815
1816  static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1817
1818  SourceLocation getAtLoc() const { return AtLoc; }
1819  void setAtLoc(SourceLocation L) { AtLoc = L; }
1820
1821  SourceLocation getLParenLoc() const { return LParenLoc; }
1822  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1823
1824  TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
1825  QualType getType() const { return DeclType->getType(); }
1826  void setType(TypeSourceInfo *T) { DeclType = T; }
1827
1828  PropertyAttributeKind getPropertyAttributes() const {
1829    return PropertyAttributeKind(PropertyAttributes);
1830  }
1831  void setPropertyAttributes(PropertyAttributeKind PRVal) {
1832    PropertyAttributes |= PRVal;
1833  }
1834
1835  PropertyAttributeKind getPropertyAttributesAsWritten() const {
1836    return PropertyAttributeKind(PropertyAttributesAsWritten);
1837  }
1838
1839  bool hasWrittenStorageAttribute() const {
1840    return PropertyAttributesAsWritten & (OBJC_PR_assign | OBJC_PR_copy |
1841        OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong |
1842        OBJC_PR_weak);
1843  }
1844
1845  void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
1846    PropertyAttributesAsWritten = PRVal;
1847  }
1848
1849 void makeitReadWriteAttribute(void) {
1850    PropertyAttributes &= ~OBJC_PR_readonly;
1851    PropertyAttributes |= OBJC_PR_readwrite;
1852 }
1853
1854  // Helper methods for accessing attributes.
1855
1856  /// isReadOnly - Return true iff the property has a setter.
1857  bool isReadOnly() const {
1858    return (PropertyAttributes & OBJC_PR_readonly);
1859  }
1860
1861  /// isAtomic - Return true if the property is atomic.
1862  bool isAtomic() const {
1863    return (PropertyAttributes & OBJC_PR_atomic);
1864  }
1865
1866  /// isRetaining - Return true if the property retains its value.
1867  bool isRetaining() const {
1868    return (PropertyAttributes &
1869            (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
1870  }
1871
1872  /// getSetterKind - Return the method used for doing assignment in
1873  /// the property setter. This is only valid if the property has been
1874  /// defined to have a setter.
1875  SetterKind getSetterKind() const {
1876    if (PropertyAttributes & OBJC_PR_strong)
1877      return getType()->isBlockPointerType() ? Copy : Retain;
1878    if (PropertyAttributes & OBJC_PR_retain)
1879      return Retain;
1880    if (PropertyAttributes & OBJC_PR_copy)
1881      return Copy;
1882    if (PropertyAttributes & OBJC_PR_weak)
1883      return Weak;
1884    return Assign;
1885  }
1886
1887  Selector getGetterName() const { return GetterName; }
1888  void setGetterName(Selector Sel) { GetterName = Sel; }
1889
1890  Selector getSetterName() const { return SetterName; }
1891  void setSetterName(Selector Sel) { SetterName = Sel; }
1892
1893  ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
1894  void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
1895
1896  ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
1897  void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
1898
1899  // Related to \@optional/\@required declared in \@protocol
1900  void setPropertyImplementation(PropertyControl pc) {
1901    PropertyImplementation = pc;
1902  }
1903  PropertyControl getPropertyImplementation() const {
1904    return PropertyControl(PropertyImplementation);
1905  }
1906
1907  void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
1908    PropertyIvarDecl = Ivar;
1909  }
1910  ObjCIvarDecl *getPropertyIvarDecl() const {
1911    return PropertyIvarDecl;
1912  }
1913
1914  virtual SourceRange getSourceRange() const LLVM_READONLY {
1915    return SourceRange(AtLoc, getLocation());
1916  }
1917
1918  /// Get the default name of the synthesized ivar.
1919  IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
1920
1921  /// Lookup a property by name in the specified DeclContext.
1922  static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
1923                                            IdentifierInfo *propertyID);
1924
1925  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1926  static bool classofKind(Kind K) { return K == ObjCProperty; }
1927};
1928
1929/// ObjCPropertyImplDecl - Represents implementation declaration of a property
1930/// in a class or category implementation block. For example:
1931/// \@synthesize prop1 = ivar1;
1932///
1933class ObjCPropertyImplDecl : public Decl {
1934public:
1935  enum Kind {
1936    Synthesize,
1937    Dynamic
1938  };
1939private:
1940  SourceLocation AtLoc;   // location of \@synthesize or \@dynamic
1941
1942  /// \brief For \@synthesize, the location of the ivar, if it was written in
1943  /// the source code.
1944  ///
1945  /// \code
1946  /// \@synthesize int a = b
1947  /// \endcode
1948  SourceLocation IvarLoc;
1949
1950  /// Property declaration being implemented
1951  ObjCPropertyDecl *PropertyDecl;
1952
1953  /// Null for \@dynamic. Required for \@synthesize.
1954  ObjCIvarDecl *PropertyIvarDecl;
1955
1956  /// Null for \@dynamic. Non-null if property must be copy-constructed in
1957  /// getter.
1958  Expr *GetterCXXConstructor;
1959
1960  /// Null for \@dynamic. Non-null if property has assignment operator to call
1961  /// in Setter synthesis.
1962  Expr *SetterCXXAssignment;
1963
1964  ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
1965                       ObjCPropertyDecl *property,
1966                       Kind PK,
1967                       ObjCIvarDecl *ivarDecl,
1968                       SourceLocation ivarLoc)
1969    : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
1970      IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl),
1971      GetterCXXConstructor(0), SetterCXXAssignment(0) {
1972    assert (PK == Dynamic || PropertyIvarDecl);
1973  }
1974
1975public:
1976  static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
1977                                      SourceLocation atLoc, SourceLocation L,
1978                                      ObjCPropertyDecl *property,
1979                                      Kind PK,
1980                                      ObjCIvarDecl *ivarDecl,
1981                                      SourceLocation ivarLoc);
1982
1983  static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1984
1985  virtual SourceRange getSourceRange() const LLVM_READONLY;
1986
1987  SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
1988  void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
1989
1990  ObjCPropertyDecl *getPropertyDecl() const {
1991    return PropertyDecl;
1992  }
1993  void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
1994
1995  Kind getPropertyImplementation() const {
1996    return PropertyIvarDecl ? Synthesize : Dynamic;
1997  }
1998
1999  ObjCIvarDecl *getPropertyIvarDecl() const {
2000    return PropertyIvarDecl;
2001  }
2002  SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2003
2004  void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2005                           SourceLocation IvarLoc) {
2006    PropertyIvarDecl = Ivar;
2007    this->IvarLoc = IvarLoc;
2008  }
2009
2010  /// \brief For \@synthesize, returns true if an ivar name was explicitly
2011  /// specified.
2012  ///
2013  /// \code
2014  /// \@synthesize int a = b; // true
2015  /// \@synthesize int a; // false
2016  /// \endcode
2017  bool isIvarNameSpecified() const {
2018    return IvarLoc.isValid() && IvarLoc != getLocation();
2019  }
2020
2021  Expr *getGetterCXXConstructor() const {
2022    return GetterCXXConstructor;
2023  }
2024  void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2025    GetterCXXConstructor = getterCXXConstructor;
2026  }
2027
2028  Expr *getSetterCXXAssignment() const {
2029    return SetterCXXAssignment;
2030  }
2031  void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2032    SetterCXXAssignment = setterCXXAssignment;
2033  }
2034
2035  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2036  static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2037
2038  friend class ASTDeclReader;
2039};
2040
2041}  // end namespace clang
2042#endif
2043