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