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