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