1 //===--- DeclObjC.h - Classes for representing declarations -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the DeclObjC interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECLOBJC_H
15 #define LLVM_CLANG_AST_DECLOBJC_H
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/SelectorLocationsKind.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Compiler.h"
29 class ObjCProtocolDecl;
30 class ObjCCategoryDecl;
31 class ObjCPropertyDecl;
32 class ObjCPropertyImplDecl;
33 class CXXCtorInitializer;
36 ObjCListBase(const ObjCListBase &) = delete;
37 void operator=(const ObjCListBase &) = delete;
39 /// List is an array of pointers to objects that are not owned by this object.
44 ObjCListBase() : List(nullptr), NumElts(0) {}
45 unsigned size() const { return NumElts; }
46 bool empty() const { return NumElts == 0; }
49 void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
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
58 class ObjCList : public ObjCListBase {
60 void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
61 ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
64 typedef T* const * iterator;
65 iterator begin() const { return (iterator)List; }
66 iterator end() const { return (iterator)List+NumElts; }
68 T* operator[](unsigned Idx) const {
69 assert(Idx < NumElts && "Invalid access");
74 /// \brief A list of Objective-C protocols, along with the source
75 /// locations at which they were referenced.
76 class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
77 SourceLocation *Locations;
79 using ObjCList<ObjCProtocolDecl>::set;
82 ObjCProtocolList() : ObjCList<ObjCProtocolDecl>(), Locations(nullptr) { }
84 typedef const SourceLocation *loc_iterator;
85 loc_iterator loc_begin() const { return Locations; }
86 loc_iterator loc_end() const { return Locations + size(); }
88 void set(ObjCProtocolDecl* const* InList, unsigned Elts,
89 const SourceLocation *Locs, ASTContext &Ctx);
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:
100 /// Setter/getter instance methods:
101 /// - (void)setMenu:(NSMenu *)menu;
102 /// - (NSMenu *)menu;
104 /// Instance method that takes 2 NSView arguments:
105 /// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
107 /// Getter class method:
108 /// + (NSMenu *)defaultMenu;
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.
113 class ObjCMethodDecl : public NamedDecl, public DeclContext {
115 enum ImplementationControl { None, Required, Optional };
117 // The conventional meaning of this method; an ObjCMethodFamily.
118 // This is not serialized; instead, it is computed on demand and
120 mutable unsigned Family : ObjCMethodFamilyBitWidth;
122 /// instance (true) or class (false) method.
123 unsigned IsInstance : 1;
124 unsigned IsVariadic : 1;
126 /// True if this method is the getter or setter for an explicit property.
127 unsigned IsPropertyAccessor : 1;
129 // Method has a definition.
130 unsigned IsDefined : 1;
132 /// \brief Method redeclaration in the same interface.
133 unsigned IsRedeclaration : 1;
135 /// \brief Is redeclared in the same interface.
136 mutable unsigned HasRedeclaration : 1;
138 // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum
139 /// \@required/\@optional
140 unsigned DeclImplementation : 2;
142 // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
144 unsigned objcDeclQualifier : 6;
146 /// \brief Indicates whether this method has a related result type.
147 unsigned RelatedResultType : 1;
149 /// \brief Whether the locations of the selector identifiers are in a
150 /// "standard" position, a enum SelectorLocationsKind.
151 unsigned SelLocsKind : 2;
153 /// \brief Whether this method overrides any other in the class hierarchy.
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;
162 /// \brief Indicates if the method was a definition but its body was skipped.
163 unsigned HasSkippedBody : 1;
165 // Return type of this method.
166 QualType MethodDeclType;
168 // Type source information for the return type.
169 TypeSourceInfo *ReturnTInfo;
171 /// \brief Array of ParmVarDecls for the formal parameters of this method
172 /// and optionally followed by selector locations.
173 void *ParamsAndSelLocs;
176 /// List of attributes for this method declaration.
177 SourceLocation DeclEndLoc; // the location of the ';' or '{'.
179 // The following are only used for method definitions, null otherwise.
180 LazyDeclStmtPtr Body;
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;
189 SelectorLocationsKind getSelLocsKind() const {
190 return (SelectorLocationsKind)SelLocsKind;
192 bool hasStandardSelLocs() const {
193 return getSelLocsKind() != SelLoc_NonStandard;
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);
201 const SourceLocation *getStoredSelLocs() const {
202 return reinterpret_cast<const SourceLocation*>(getParams() + NumParams);
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);
210 const ParmVarDecl *const *getParams() const {
211 return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
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())
219 return getNumSelectorLocs();
222 void setParamsAndSelLocs(ASTContext &C,
223 ArrayRef<ParmVarDecl*> Params,
224 ArrayRef<SourceLocation> SelLocs);
226 ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
227 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
228 DeclContext *contextDecl, bool isInstance = true,
229 bool isVariadic = false, bool isPropertyAccessor = false,
230 bool isImplicitlyDeclared = false, bool isDefined = false,
231 ImplementationControl impControl = None,
232 bool HasRelatedResultType = false)
233 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo),
234 DeclContext(ObjCMethod), Family(InvalidObjCMethodFamily),
235 IsInstance(isInstance), IsVariadic(isVariadic),
236 IsPropertyAccessor(isPropertyAccessor), IsDefined(isDefined),
237 IsRedeclaration(0), HasRedeclaration(0), DeclImplementation(impControl),
238 objcDeclQualifier(OBJC_TQ_None),
239 RelatedResultType(HasRelatedResultType),
240 SelLocsKind(SelLoc_StandardNoSpace), IsOverriding(0), HasSkippedBody(0),
241 MethodDeclType(T), ReturnTInfo(ReturnTInfo), ParamsAndSelLocs(nullptr),
242 NumParams(0), DeclEndLoc(endLoc), Body(), SelfDecl(nullptr),
244 setImplicit(isImplicitlyDeclared);
247 /// \brief A definition will return its interface declaration.
248 /// An interface declaration will return its definition.
249 /// Otherwise it will return itself.
250 ObjCMethodDecl *getNextRedeclarationImpl() override;
253 static ObjCMethodDecl *
254 Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
255 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
256 DeclContext *contextDecl, bool isInstance = true,
257 bool isVariadic = false, bool isPropertyAccessor = false,
258 bool isImplicitlyDeclared = false, bool isDefined = false,
259 ImplementationControl impControl = None,
260 bool HasRelatedResultType = false);
262 static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
264 ObjCMethodDecl *getCanonicalDecl() override;
265 const ObjCMethodDecl *getCanonicalDecl() const {
266 return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
269 ObjCDeclQualifier getObjCDeclQualifier() const {
270 return ObjCDeclQualifier(objcDeclQualifier);
272 void setObjCDeclQualifier(ObjCDeclQualifier QV) { objcDeclQualifier = QV; }
274 /// \brief Determine whether this method has a result type that is related
275 /// to the message receiver's type.
276 bool hasRelatedResultType() const { return RelatedResultType; }
278 /// \brief Note whether this method has a related result type.
279 void SetRelatedResultType(bool RRT = true) { RelatedResultType = RRT; }
281 /// \brief True if this is a method redeclaration in the same interface.
282 bool isRedeclaration() const { return IsRedeclaration; }
283 void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
285 /// \brief Returns the location where the declarator ends. It will be
286 /// the location of ';' for a method declaration and the location of '{'
287 /// for a method definition.
288 SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
290 // Location information, modeled after the Stmt API.
291 SourceLocation getLocStart() const LLVM_READONLY { return getLocation(); }
292 SourceLocation getLocEnd() const LLVM_READONLY;
293 SourceRange getSourceRange() const override LLVM_READONLY {
294 return SourceRange(getLocation(), getLocEnd());
297 SourceLocation getSelectorStartLoc() const {
299 return getLocStart();
300 return getSelectorLoc(0);
302 SourceLocation getSelectorLoc(unsigned Index) const {
303 assert(Index < getNumSelectorLocs() && "Index out of range!");
304 if (hasStandardSelLocs())
305 return getStandardSelectorLoc(Index, getSelector(),
306 getSelLocsKind() == SelLoc_StandardWithSpace,
309 return getStoredSelLocs()[Index];
312 void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
314 unsigned getNumSelectorLocs() const {
317 Selector Sel = getSelector();
318 if (Sel.isUnarySelector())
320 return Sel.getNumArgs();
323 ObjCInterfaceDecl *getClassInterface();
324 const ObjCInterfaceDecl *getClassInterface() const {
325 return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
328 Selector getSelector() const { return getDeclName().getObjCSelector(); }
330 QualType getReturnType() const { return MethodDeclType; }
331 void setReturnType(QualType T) { MethodDeclType = T; }
332 SourceRange getReturnTypeSourceRange() const;
334 /// \brief Determine the type of an expression that sends a message to this
336 QualType getSendResultType() const {
337 return getReturnType().getNonLValueExprType(getASTContext());
340 TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
341 void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
343 // Iterator access to formal parameters.
344 unsigned param_size() const { return NumParams; }
345 typedef const ParmVarDecl *const *param_const_iterator;
346 typedef ParmVarDecl *const *param_iterator;
347 typedef llvm::iterator_range<param_iterator> param_range;
348 typedef llvm::iterator_range<param_const_iterator> param_const_range;
350 param_range params() { return param_range(param_begin(), param_end()); }
351 param_const_range params() const {
352 return param_const_range(param_begin(), param_end());
355 param_const_iterator param_begin() const {
356 return param_const_iterator(getParams());
358 param_const_iterator param_end() const {
359 return param_const_iterator(getParams() + NumParams);
361 param_iterator param_begin() { return param_iterator(getParams()); }
362 param_iterator param_end() { return param_iterator(getParams() + NumParams); }
364 // This method returns and of the parameters which are part of the selector
365 // name mangling requirements.
366 param_const_iterator sel_param_end() const {
367 return param_begin() + getSelector().getNumArgs();
370 // ArrayRef access to formal parameters. This should eventually
371 // replace the iterator interface above.
372 ArrayRef<ParmVarDecl*> parameters() const {
373 return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
377 /// \brief Sets the method's parameters and selector source locations.
378 /// If the method is implicit (not coming from source) \p SelLocs is
380 void setMethodParams(ASTContext &C,
381 ArrayRef<ParmVarDecl*> Params,
382 ArrayRef<SourceLocation> SelLocs = llvm::None);
384 // Iterator access to parameter types.
385 typedef std::const_mem_fun_t<QualType, ParmVarDecl> deref_fun;
386 typedef llvm::mapped_iterator<param_const_iterator, deref_fun>
389 param_type_iterator param_type_begin() const {
390 return llvm::map_iterator(param_begin(), deref_fun(&ParmVarDecl::getType));
392 param_type_iterator param_type_end() const {
393 return llvm::map_iterator(param_end(), deref_fun(&ParmVarDecl::getType));
396 /// createImplicitParams - Used to lazily create the self and cmd
397 /// implict parameters. This must be called prior to using getSelfDecl()
398 /// or getCmdDecl(). The call is ignored if the implicit paramters
399 /// have already been created.
400 void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
402 ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
403 void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
404 ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
405 void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
407 /// Determines the family of this method.
408 ObjCMethodFamily getMethodFamily() const;
410 bool isInstanceMethod() const { return IsInstance; }
411 void setInstanceMethod(bool isInst) { IsInstance = isInst; }
412 bool isVariadic() const { return IsVariadic; }
413 void setVariadic(bool isVar) { IsVariadic = isVar; }
415 bool isClassMethod() const { return !IsInstance; }
417 bool isPropertyAccessor() const { return IsPropertyAccessor; }
418 void setPropertyAccessor(bool isAccessor) { IsPropertyAccessor = isAccessor; }
420 bool isDefined() const { return IsDefined; }
421 void setDefined(bool isDefined) { IsDefined = isDefined; }
423 /// \brief Whether this method overrides any other in the class hierarchy.
425 /// A method is said to override any method in the class's
426 /// base classes, its protocols, or its categories' protocols, that has
427 /// the same selector and is of the same kind (class or instance).
428 /// A method in an implementation is not considered as overriding the same
429 /// method in the interface or its categories.
430 bool isOverriding() const { return IsOverriding; }
431 void setOverriding(bool isOverriding) { IsOverriding = isOverriding; }
433 /// \brief Return overridden methods for the given \p Method.
435 /// An ObjC method is considered to override any method in the class's
436 /// base classes (and base's categories), its protocols, or its categories'
437 /// protocols, that has
438 /// the same selector and is of the same kind (class or instance).
439 /// A method in an implementation is not considered as overriding the same
440 /// method in the interface or its categories.
441 void getOverriddenMethods(
442 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
444 /// \brief True if the method was a definition but its body was skipped.
445 bool hasSkippedBody() const { return HasSkippedBody; }
446 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
448 /// \brief Returns the property associated with this method's selector.
450 /// Note that even if this particular method is not marked as a property
451 /// accessor, it is still possible for it to match a property declared in a
452 /// superclass. Pass \c false if you only want to check the current class.
453 const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
455 // Related to protocols declared in \@protocol
456 void setDeclImplementation(ImplementationControl ic) {
457 DeclImplementation = ic;
459 ImplementationControl getImplementationControl() const {
460 return ImplementationControl(DeclImplementation);
463 /// Returns true if this specific method declaration is marked with the
464 /// designated initializer attribute.
465 bool isThisDeclarationADesignatedInitializer() const;
467 /// Returns true if the method selector resolves to a designated initializer
468 /// in the class's interface.
470 /// \param InitMethod if non-null and the function returns true, it receives
471 /// the method declaration that was marked with the designated initializer
473 bool isDesignatedInitializerForTheInterface(
474 const ObjCMethodDecl **InitMethod = nullptr) const;
476 /// \brief Determine whether this method has a body.
477 bool hasBody() const override { return Body.isValid(); }
479 /// \brief Retrieve the body of this method, if it has one.
480 Stmt *getBody() const override;
482 void setLazyBody(uint64_t Offset) { Body = Offset; }
484 CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
485 void setBody(Stmt *B) { Body = B; }
487 /// \brief Returns whether this specific method is a definition.
488 bool isThisDeclarationADefinition() const { return hasBody(); }
490 // Implement isa/cast/dyncast/etc.
491 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
492 static bool classofKind(Kind K) { return K == ObjCMethod; }
493 static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
494 return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
496 static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
497 return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
500 friend class ASTDeclReader;
501 friend class ASTDeclWriter;
504 /// ObjCContainerDecl - Represents a container for method declarations.
505 /// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
506 /// ObjCProtocolDecl, and ObjCImplDecl.
508 class ObjCContainerDecl : public NamedDecl, public DeclContext {
509 void anchor() override;
511 SourceLocation AtStart;
513 // These two locations in the range mark the end of the method container.
514 // The first points to the '@' token, and the second to the 'end' token.
518 ObjCContainerDecl(Kind DK, DeclContext *DC,
519 IdentifierInfo *Id, SourceLocation nameLoc,
520 SourceLocation atStartLoc)
521 : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK), AtStart(atStartLoc) {}
523 // Iterator access to properties.
524 typedef specific_decl_iterator<ObjCPropertyDecl> prop_iterator;
525 typedef llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>
528 prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
529 prop_iterator prop_begin() const {
530 return prop_iterator(decls_begin());
532 prop_iterator prop_end() const {
533 return prop_iterator(decls_end());
536 // Iterator access to instance/class methods.
537 typedef specific_decl_iterator<ObjCMethodDecl> method_iterator;
538 typedef llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>
541 method_range methods() const {
542 return method_range(meth_begin(), meth_end());
544 method_iterator meth_begin() const {
545 return method_iterator(decls_begin());
547 method_iterator meth_end() const {
548 return method_iterator(decls_end());
551 typedef filtered_decl_iterator<ObjCMethodDecl,
552 &ObjCMethodDecl::isInstanceMethod>
554 typedef llvm::iterator_range<instmeth_iterator> instmeth_range;
556 instmeth_range instance_methods() const {
557 return instmeth_range(instmeth_begin(), instmeth_end());
559 instmeth_iterator instmeth_begin() const {
560 return instmeth_iterator(decls_begin());
562 instmeth_iterator instmeth_end() const {
563 return instmeth_iterator(decls_end());
566 typedef filtered_decl_iterator<ObjCMethodDecl,
567 &ObjCMethodDecl::isClassMethod>
569 typedef llvm::iterator_range<classmeth_iterator> classmeth_range;
571 classmeth_range class_methods() const {
572 return classmeth_range(classmeth_begin(), classmeth_end());
574 classmeth_iterator classmeth_begin() const {
575 return classmeth_iterator(decls_begin());
577 classmeth_iterator classmeth_end() const {
578 return classmeth_iterator(decls_end());
581 // Get the local instance/class method declared in this interface.
582 ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
583 bool AllowHidden = false) const;
584 ObjCMethodDecl *getInstanceMethod(Selector Sel,
585 bool AllowHidden = false) const {
586 return getMethod(Sel, true/*isInstance*/, AllowHidden);
588 ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
589 return getMethod(Sel, false/*isInstance*/, AllowHidden);
591 bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
592 ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
595 FindPropertyDeclaration(const IdentifierInfo *PropertyId) const;
597 typedef llvm::DenseMap<IdentifierInfo*, ObjCPropertyDecl*> PropertyMap;
599 typedef llvm::DenseMap<const ObjCProtocolDecl *, ObjCPropertyDecl*>
602 typedef llvm::SmallVector<ObjCPropertyDecl*, 8> PropertyDeclOrder;
604 /// This routine collects list of properties to be implemented in the class.
605 /// This includes, class's and its conforming protocols' properties.
606 /// Note, the superclass's properties are not included in the list.
607 virtual void collectPropertiesToImplement(PropertyMap &PM,
608 PropertyDeclOrder &PO) const {}
610 SourceLocation getAtStartLoc() const { return AtStart; }
611 void setAtStartLoc(SourceLocation Loc) { AtStart = Loc; }
613 // Marks the end of the container.
614 SourceRange getAtEndRange() const {
617 void setAtEndRange(SourceRange atEnd) {
621 SourceRange getSourceRange() const override LLVM_READONLY {
622 return SourceRange(AtStart, getAtEndRange().getEnd());
625 // Implement isa/cast/dyncast/etc.
626 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
627 static bool classofKind(Kind K) {
628 return K >= firstObjCContainer &&
629 K <= lastObjCContainer;
632 static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
633 return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
635 static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
636 return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
640 /// \brief Represents an ObjC class declaration.
645 /// // MostPrimitive declares no super class (not particularly useful).
646 /// \@interface MostPrimitive
647 /// // no instance variables or methods.
650 /// // NSResponder inherits from NSObject & implements NSCoding (a protocol).
651 /// \@interface NSResponder : NSObject \<NSCoding>
652 /// { // instance variables are represented by ObjCIvarDecl.
653 /// id nextResponder; // nextResponder instance variable.
655 /// - (NSResponder *)nextResponder; // return a pointer to NSResponder.
656 /// - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
657 /// \@end // to an NSEvent.
660 /// Unlike C/C++, forward class declarations are accomplished with \@class.
661 /// Unlike C/C++, \@class allows for a list of classes to be forward declared.
662 /// Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
663 /// typically inherit from NSObject (an exception is NSProxy).
665 class ObjCInterfaceDecl : public ObjCContainerDecl
666 , public Redeclarable<ObjCInterfaceDecl> {
667 void anchor() override;
669 /// TypeForDecl - This indicates the Type object that represents this
670 /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType
671 mutable const Type *TypeForDecl;
672 friend class ASTContext;
674 struct DefinitionData {
675 /// \brief The definition of this class, for quick access from any
677 ObjCInterfaceDecl *Definition;
679 /// Class's super class.
680 ObjCInterfaceDecl *SuperClass;
682 /// Protocols referenced in the \@interface declaration
683 ObjCProtocolList ReferencedProtocols;
685 /// Protocols reference in both the \@interface and class extensions.
686 ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
688 /// \brief List of categories and class extensions defined for this class.
690 /// Categories are stored as a linked list in the AST, since the categories
691 /// and class extensions come long after the initial interface declaration,
692 /// and we avoid dynamically-resized arrays in the AST wherever possible.
693 ObjCCategoryDecl *CategoryList;
695 /// IvarList - List of all ivars defined by this class; including class
696 /// extensions and implementation. This list is built lazily.
697 ObjCIvarDecl *IvarList;
699 /// \brief Indicates that the contents of this Objective-C class will be
700 /// completed by the external AST source when required.
701 mutable bool ExternallyCompleted : 1;
703 /// \brief Indicates that the ivar cache does not yet include ivars
704 /// declared in the implementation.
705 mutable bool IvarListMissingImplementation : 1;
707 /// Indicates that this interface decl contains at least one initializer
708 /// marked with the 'objc_designated_initializer' attribute.
709 bool HasDesignatedInitializers : 1;
711 enum InheritedDesignatedInitializersState {
712 /// We didn't calculate whether the designated initializers should be
713 /// inherited or not.
715 /// Designated initializers are inherited for the super class.
717 /// The class does not inherit designated initializers.
720 /// One of the \c InheritedDesignatedInitializersState enumeratos.
721 mutable unsigned InheritedDesignatedInitializers : 2;
723 /// \brief The location of the superclass, if any.
724 SourceLocation SuperClassLoc;
726 /// \brief The location of the last location in this declaration, before
727 /// the properties/methods. For example, this will be the '>', '}', or
729 SourceLocation EndLoc;
731 DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarList(),
732 ExternallyCompleted(),
733 IvarListMissingImplementation(true),
734 HasDesignatedInitializers(),
735 InheritedDesignatedInitializers(IDI_Unknown) { }
738 ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
739 IdentifierInfo *Id, SourceLocation CLoc,
740 ObjCInterfaceDecl *PrevDecl, bool IsInternal);
742 void LoadExternalDefinition() const;
744 /// \brief Contains a pointer to the data associated with this class,
745 /// which will be NULL if this class has not yet been defined.
747 /// The bit indicates when we don't need to check for out-of-date
748 /// declarations. It will be set unless modules are enabled.
749 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
751 DefinitionData &data() const {
752 assert(Data.getPointer() && "Declaration has no definition!");
753 return *Data.getPointer();
756 /// \brief Allocate the definition data for this class.
757 void allocateDefinitionData();
759 typedef Redeclarable<ObjCInterfaceDecl> redeclarable_base;
760 ObjCInterfaceDecl *getNextRedeclarationImpl() override {
761 return getNextRedeclaration();
763 ObjCInterfaceDecl *getPreviousDeclImpl() override {
764 return getPreviousDecl();
766 ObjCInterfaceDecl *getMostRecentDeclImpl() override {
767 return getMostRecentDecl();
771 static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
772 SourceLocation atLoc,
774 ObjCInterfaceDecl *PrevDecl,
775 SourceLocation ClassLoc = SourceLocation(),
776 bool isInternal = false);
778 static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
780 SourceRange getSourceRange() const override LLVM_READONLY {
781 if (isThisDeclarationADefinition())
782 return ObjCContainerDecl::getSourceRange();
784 return SourceRange(getAtStartLoc(), getLocation());
787 /// \brief Indicate that this Objective-C class is complete, but that
788 /// the external AST source will be responsible for filling in its contents
789 /// when a complete class is required.
790 void setExternallyCompleted();
792 /// Indicate that this interface decl contains at least one initializer
793 /// marked with the 'objc_designated_initializer' attribute.
794 void setHasDesignatedInitializers();
796 /// Returns true if this interface decl contains at least one initializer
797 /// marked with the 'objc_designated_initializer' attribute.
798 bool hasDesignatedInitializers() const;
800 /// Returns true if this interface decl declares a designated initializer
801 /// or it inherites one from its super class.
802 bool declaresOrInheritsDesignatedInitializers() const {
803 return hasDesignatedInitializers() || inheritsDesignatedInitializers();
806 const ObjCProtocolList &getReferencedProtocols() const {
807 assert(hasDefinition() && "Caller did not check for forward reference!");
808 if (data().ExternallyCompleted)
809 LoadExternalDefinition();
811 return data().ReferencedProtocols;
814 ObjCImplementationDecl *getImplementation() const;
815 void setImplementation(ObjCImplementationDecl *ImplD);
817 ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
819 // Get the local instance/class method declared in a category.
820 ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
821 ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
822 ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
823 return isInstance ? getCategoryInstanceMethod(Sel)
824 : getCategoryClassMethod(Sel);
827 typedef ObjCProtocolList::iterator protocol_iterator;
828 typedef llvm::iterator_range<protocol_iterator> protocol_range;
830 protocol_range protocols() const {
831 return protocol_range(protocol_begin(), protocol_end());
833 protocol_iterator protocol_begin() const {
834 // FIXME: Should make sure no callers ever do this.
835 if (!hasDefinition())
836 return protocol_iterator();
838 if (data().ExternallyCompleted)
839 LoadExternalDefinition();
841 return data().ReferencedProtocols.begin();
843 protocol_iterator protocol_end() const {
844 // FIXME: Should make sure no callers ever do this.
845 if (!hasDefinition())
846 return protocol_iterator();
848 if (data().ExternallyCompleted)
849 LoadExternalDefinition();
851 return data().ReferencedProtocols.end();
854 typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
855 typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
857 protocol_loc_range protocol_locs() const {
858 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
860 protocol_loc_iterator protocol_loc_begin() const {
861 // FIXME: Should make sure no callers ever do this.
862 if (!hasDefinition())
863 return protocol_loc_iterator();
865 if (data().ExternallyCompleted)
866 LoadExternalDefinition();
868 return data().ReferencedProtocols.loc_begin();
871 protocol_loc_iterator protocol_loc_end() const {
872 // FIXME: Should make sure no callers ever do this.
873 if (!hasDefinition())
874 return protocol_loc_iterator();
876 if (data().ExternallyCompleted)
877 LoadExternalDefinition();
879 return data().ReferencedProtocols.loc_end();
882 typedef ObjCList<ObjCProtocolDecl>::iterator all_protocol_iterator;
883 typedef llvm::iterator_range<all_protocol_iterator> all_protocol_range;
885 all_protocol_range all_referenced_protocols() const {
886 return all_protocol_range(all_referenced_protocol_begin(),
887 all_referenced_protocol_end());
889 all_protocol_iterator all_referenced_protocol_begin() const {
890 // FIXME: Should make sure no callers ever do this.
891 if (!hasDefinition())
892 return all_protocol_iterator();
894 if (data().ExternallyCompleted)
895 LoadExternalDefinition();
897 return data().AllReferencedProtocols.empty()
899 : data().AllReferencedProtocols.begin();
901 all_protocol_iterator all_referenced_protocol_end() const {
902 // FIXME: Should make sure no callers ever do this.
903 if (!hasDefinition())
904 return all_protocol_iterator();
906 if (data().ExternallyCompleted)
907 LoadExternalDefinition();
909 return data().AllReferencedProtocols.empty()
911 : data().AllReferencedProtocols.end();
914 typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
915 typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
917 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
918 ivar_iterator ivar_begin() const {
919 if (const ObjCInterfaceDecl *Def = getDefinition())
920 return ivar_iterator(Def->decls_begin());
922 // FIXME: Should make sure no callers ever do this.
923 return ivar_iterator();
925 ivar_iterator ivar_end() const {
926 if (const ObjCInterfaceDecl *Def = getDefinition())
927 return ivar_iterator(Def->decls_end());
929 // FIXME: Should make sure no callers ever do this.
930 return ivar_iterator();
933 unsigned ivar_size() const {
934 return std::distance(ivar_begin(), ivar_end());
937 bool ivar_empty() const { return ivar_begin() == ivar_end(); }
939 ObjCIvarDecl *all_declared_ivar_begin();
940 const ObjCIvarDecl *all_declared_ivar_begin() const {
941 // Even though this modifies IvarList, it's conceptually const:
942 // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
943 return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
945 void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
947 /// setProtocolList - Set the list of protocols that this interface
949 void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
950 const SourceLocation *Locs, ASTContext &C) {
951 data().ReferencedProtocols.set(List, Num, Locs, C);
954 /// mergeClassExtensionProtocolList - Merge class extension's protocol list
955 /// into the protocol list for this class.
956 void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
960 /// Produce a name to be used for class's metadata. It comes either via
961 /// objc_runtime_name attribute or class name.
962 StringRef getObjCRuntimeNameAsString() const;
964 /// Returns the designated initializers for the interface.
966 /// If this declaration does not have methods marked as designated
967 /// initializers then the interface inherits the designated initializers of
969 void getDesignatedInitializers(
970 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
972 /// Returns true if the given selector is a designated initializer for the
975 /// If this declaration does not have methods marked as designated
976 /// initializers then the interface inherits the designated initializers of
979 /// \param InitMethod if non-null and the function returns true, it receives
980 /// the method that was marked as a designated initializer.
982 isDesignatedInitializer(Selector Sel,
983 const ObjCMethodDecl **InitMethod = nullptr) const;
985 /// \brief Determine whether this particular declaration of this class is
986 /// actually also a definition.
987 bool isThisDeclarationADefinition() const {
988 return getDefinition() == this;
991 /// \brief Determine whether this class has been defined.
992 bool hasDefinition() const {
993 // If the name of this class is out-of-date, bring it up-to-date, which
994 // might bring in a definition.
995 // Note: a null value indicates that we don't have a definition and that
996 // modules are enabled.
997 if (!Data.getOpaqueValue()) {
998 if (IdentifierInfo *II = getIdentifier()) {
999 if (II->isOutOfDate()) {
1000 updateOutOfDate(*II);
1005 return Data.getPointer();
1008 /// \brief Retrieve the definition of this class, or NULL if this class
1009 /// has been forward-declared (with \@class) but not yet defined (with
1011 ObjCInterfaceDecl *getDefinition() {
1012 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1015 /// \brief Retrieve the definition of this class, or NULL if this class
1016 /// has been forward-declared (with \@class) but not yet defined (with
1018 const ObjCInterfaceDecl *getDefinition() const {
1019 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1022 /// \brief Starts the definition of this Objective-C class, taking it from
1023 /// a forward declaration (\@class) to a definition (\@interface).
1024 void startDefinition();
1026 ObjCInterfaceDecl *getSuperClass() const {
1027 // FIXME: Should make sure no callers ever do this.
1028 if (!hasDefinition())
1031 if (data().ExternallyCompleted)
1032 LoadExternalDefinition();
1034 return data().SuperClass;
1037 void setSuperClass(ObjCInterfaceDecl * superCls) {
1039 (superCls && superCls->hasDefinition()) ? superCls->getDefinition()
1043 /// \brief Iterator that walks over the list of categories, filtering out
1044 /// those that do not meet specific criteria.
1046 /// This class template is used for the various permutations of category
1047 /// and extension iterators.
1048 template<bool (*Filter)(ObjCCategoryDecl *)>
1049 class filtered_category_iterator {
1050 ObjCCategoryDecl *Current;
1052 void findAcceptableCategory();
1055 typedef ObjCCategoryDecl * value_type;
1056 typedef value_type reference;
1057 typedef value_type pointer;
1058 typedef std::ptrdiff_t difference_type;
1059 typedef std::input_iterator_tag iterator_category;
1061 filtered_category_iterator() : Current(nullptr) { }
1062 explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1065 findAcceptableCategory();
1068 reference operator*() const { return Current; }
1069 pointer operator->() const { return Current; }
1071 filtered_category_iterator &operator++();
1073 filtered_category_iterator operator++(int) {
1074 filtered_category_iterator Tmp = *this;
1079 friend bool operator==(filtered_category_iterator X,
1080 filtered_category_iterator Y) {
1081 return X.Current == Y.Current;
1084 friend bool operator!=(filtered_category_iterator X,
1085 filtered_category_iterator Y) {
1086 return X.Current != Y.Current;
1091 /// \brief Test whether the given category is visible.
1093 /// Used in the \c visible_categories_iterator.
1094 static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1097 /// \brief Iterator that walks over the list of categories and extensions
1098 /// that are visible, i.e., not hidden in a non-imported submodule.
1099 typedef filtered_category_iterator<isVisibleCategory>
1100 visible_categories_iterator;
1102 typedef llvm::iterator_range<visible_categories_iterator>
1103 visible_categories_range;
1105 visible_categories_range visible_categories() const {
1106 return visible_categories_range(visible_categories_begin(),
1107 visible_categories_end());
1110 /// \brief Retrieve an iterator to the beginning of the visible-categories
1112 visible_categories_iterator visible_categories_begin() const {
1113 return visible_categories_iterator(getCategoryListRaw());
1116 /// \brief Retrieve an iterator to the end of the visible-categories list.
1117 visible_categories_iterator visible_categories_end() const {
1118 return visible_categories_iterator();
1121 /// \brief Determine whether the visible-categories list is empty.
1122 bool visible_categories_empty() const {
1123 return visible_categories_begin() == visible_categories_end();
1127 /// \brief Test whether the given category... is a category.
1129 /// Used in the \c known_categories_iterator.
1130 static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1133 /// \brief Iterator that walks over all of the known categories and
1134 /// extensions, including those that are hidden.
1135 typedef filtered_category_iterator<isKnownCategory> known_categories_iterator;
1136 typedef llvm::iterator_range<known_categories_iterator>
1137 known_categories_range;
1139 known_categories_range known_categories() const {
1140 return known_categories_range(known_categories_begin(),
1141 known_categories_end());
1144 /// \brief Retrieve an iterator to the beginning of the known-categories
1146 known_categories_iterator known_categories_begin() const {
1147 return known_categories_iterator(getCategoryListRaw());
1150 /// \brief Retrieve an iterator to the end of the known-categories list.
1151 known_categories_iterator known_categories_end() const {
1152 return known_categories_iterator();
1155 /// \brief Determine whether the known-categories list is empty.
1156 bool known_categories_empty() const {
1157 return known_categories_begin() == known_categories_end();
1161 /// \brief Test whether the given category is a visible extension.
1163 /// Used in the \c visible_extensions_iterator.
1164 static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1167 /// \brief Iterator that walks over all of the visible extensions, skipping
1168 /// any that are known but hidden.
1169 typedef filtered_category_iterator<isVisibleExtension>
1170 visible_extensions_iterator;
1172 typedef llvm::iterator_range<visible_extensions_iterator>
1173 visible_extensions_range;
1175 visible_extensions_range visible_extensions() const {
1176 return visible_extensions_range(visible_extensions_begin(),
1177 visible_extensions_end());
1180 /// \brief Retrieve an iterator to the beginning of the visible-extensions
1182 visible_extensions_iterator visible_extensions_begin() const {
1183 return visible_extensions_iterator(getCategoryListRaw());
1186 /// \brief Retrieve an iterator to the end of the visible-extensions list.
1187 visible_extensions_iterator visible_extensions_end() const {
1188 return visible_extensions_iterator();
1191 /// \brief Determine whether the visible-extensions list is empty.
1192 bool visible_extensions_empty() const {
1193 return visible_extensions_begin() == visible_extensions_end();
1197 /// \brief Test whether the given category is an extension.
1199 /// Used in the \c known_extensions_iterator.
1200 static bool isKnownExtension(ObjCCategoryDecl *Cat);
1203 /// \brief Iterator that walks over all of the known extensions.
1204 typedef filtered_category_iterator<isKnownExtension>
1205 known_extensions_iterator;
1206 typedef llvm::iterator_range<known_extensions_iterator>
1207 known_extensions_range;
1209 known_extensions_range known_extensions() const {
1210 return known_extensions_range(known_extensions_begin(),
1211 known_extensions_end());
1214 /// \brief Retrieve an iterator to the beginning of the known-extensions
1216 known_extensions_iterator known_extensions_begin() const {
1217 return known_extensions_iterator(getCategoryListRaw());
1220 /// \brief Retrieve an iterator to the end of the known-extensions list.
1221 known_extensions_iterator known_extensions_end() const {
1222 return known_extensions_iterator();
1225 /// \brief Determine whether the known-extensions list is empty.
1226 bool known_extensions_empty() const {
1227 return known_extensions_begin() == known_extensions_end();
1230 /// \brief Retrieve the raw pointer to the start of the category/extension
1232 ObjCCategoryDecl* getCategoryListRaw() const {
1233 // FIXME: Should make sure no callers ever do this.
1234 if (!hasDefinition())
1237 if (data().ExternallyCompleted)
1238 LoadExternalDefinition();
1240 return data().CategoryList;
1243 /// \brief Set the raw pointer to the start of the category/extension
1245 void setCategoryListRaw(ObjCCategoryDecl *category) {
1246 data().CategoryList = category;
1250 *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId) const;
1252 void collectPropertiesToImplement(PropertyMap &PM,
1253 PropertyDeclOrder &PO) const override;
1255 /// isSuperClassOf - Return true if this class is the specified class or is a
1256 /// super class of the specified interface class.
1257 bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1258 // If RHS is derived from LHS it is OK; else it is not OK.
1259 while (I != nullptr) {
1260 if (declaresSameEntity(this, I))
1263 I = I->getSuperClass();
1268 /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1269 /// to be incompatible with __weak references. Returns true if it is.
1270 bool isArcWeakrefUnavailable() const;
1272 /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1273 /// classes must not be auto-synthesized. Returns class decl. if it must not
1274 /// be; 0, otherwise.
1275 const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1277 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1278 ObjCInterfaceDecl *&ClassDeclared);
1279 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1280 ObjCInterfaceDecl *ClassDeclared;
1281 return lookupInstanceVariable(IVarName, ClassDeclared);
1284 ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1286 // Lookup a method. First, we search locally. If a method isn't
1287 // found, we search referenced protocols and class categories.
1288 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1289 bool shallowCategoryLookup = false,
1290 bool followSuper = true,
1291 const ObjCCategoryDecl *C = nullptr) const;
1293 /// Lookup an instance method for a given selector.
1294 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1295 return lookupMethod(Sel, true/*isInstance*/);
1298 /// Lookup a class method for a given selector.
1299 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1300 return lookupMethod(Sel, false/*isInstance*/);
1302 ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1304 /// \brief Lookup a method in the classes implementation hierarchy.
1305 ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1306 bool Instance=true) const;
1308 ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1309 return lookupPrivateMethod(Sel, false);
1312 /// \brief Lookup a setter or getter in the class hierarchy,
1313 /// including in all categories except for category passed
1315 ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1316 const ObjCCategoryDecl *Cat) const {
1317 return lookupMethod(Sel, true/*isInstance*/,
1318 false/*shallowCategoryLookup*/,
1319 true /* followsSuper */,
1323 SourceLocation getEndOfDefinitionLoc() const {
1324 if (!hasDefinition())
1325 return getLocation();
1327 return data().EndLoc;
1330 void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1332 void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc = Loc; }
1333 SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; }
1335 /// isImplicitInterfaceDecl - check that this is an implicitly declared
1336 /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1337 /// declaration without an \@interface declaration.
1338 bool isImplicitInterfaceDecl() const {
1339 return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1342 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1343 /// has been implemented in IDecl class, its super class or categories (if
1344 /// lookupCategory is true).
1345 bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1346 bool lookupCategory,
1347 bool RHSIsQualifiedID = false);
1349 typedef redeclarable_base::redecl_range redecl_range;
1350 typedef redeclarable_base::redecl_iterator redecl_iterator;
1351 using redeclarable_base::redecls_begin;
1352 using redeclarable_base::redecls_end;
1353 using redeclarable_base::redecls;
1354 using redeclarable_base::getPreviousDecl;
1355 using redeclarable_base::getMostRecentDecl;
1356 using redeclarable_base::isFirstDecl;
1358 /// Retrieves the canonical declaration of this Objective-C class.
1359 ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
1360 const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1362 // Low-level accessor
1363 const Type *getTypeForDecl() const { return TypeForDecl; }
1364 void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1366 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1367 static bool classofKind(Kind K) { return K == ObjCInterface; }
1369 friend class ASTReader;
1370 friend class ASTDeclReader;
1371 friend class ASTDeclWriter;
1374 const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1375 bool inheritsDesignatedInitializers() const;
1378 /// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1379 /// instance variables are identical to C. The only exception is Objective-C
1380 /// supports C++ style access control. For example:
1382 /// \@interface IvarExample : NSObject
1384 /// id defaultToProtected;
1386 /// id canBePublic; // same as C++.
1388 /// id canBeProtected; // same as C++.
1390 /// id canBePackage; // framework visibility (not available in C++).
1393 class ObjCIvarDecl : public FieldDecl {
1394 void anchor() override;
1397 enum AccessControl {
1398 None, Private, Protected, Public, Package
1402 ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1403 SourceLocation IdLoc, IdentifierInfo *Id,
1404 QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1406 : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1407 /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1408 NextIvar(nullptr), DeclAccess(ac), Synthesized(synthesized) {}
1411 static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1412 SourceLocation StartLoc, SourceLocation IdLoc,
1413 IdentifierInfo *Id, QualType T,
1414 TypeSourceInfo *TInfo,
1415 AccessControl ac, Expr *BW = nullptr,
1416 bool synthesized=false);
1418 static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1420 /// \brief Return the class interface that this ivar is logically contained
1421 /// in; this is either the interface where the ivar was declared, or the
1422 /// interface the ivar is conceptually a part of in the case of synthesized
1424 const ObjCInterfaceDecl *getContainingInterface() const;
1426 ObjCIvarDecl *getNextIvar() { return NextIvar; }
1427 const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1428 void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1430 void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1432 AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1434 AccessControl getCanonicalAccessControl() const {
1435 return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1438 void setSynthesize(bool synth) { Synthesized = synth; }
1439 bool getSynthesize() const { return Synthesized; }
1441 // Implement isa/cast/dyncast/etc.
1442 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1443 static bool classofKind(Kind K) { return K == ObjCIvar; }
1445 /// NextIvar - Next Ivar in the list of ivars declared in class; class's
1446 /// extensions and class's implementation
1447 ObjCIvarDecl *NextIvar;
1449 // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
1450 unsigned DeclAccess : 3;
1451 unsigned Synthesized : 1;
1455 /// \brief Represents a field declaration created by an \@defs(...).
1456 class ObjCAtDefsFieldDecl : public FieldDecl {
1457 void anchor() override;
1458 ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
1459 SourceLocation IdLoc, IdentifierInfo *Id,
1460 QualType T, Expr *BW)
1461 : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
1462 /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
1463 BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
1466 static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
1467 SourceLocation StartLoc,
1468 SourceLocation IdLoc, IdentifierInfo *Id,
1469 QualType T, Expr *BW);
1471 static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1473 // Implement isa/cast/dyncast/etc.
1474 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1475 static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
1478 /// \brief Represents an Objective-C protocol declaration.
1480 /// Objective-C protocols declare a pure abstract type (i.e., no instance
1481 /// variables are permitted). Protocols originally drew inspiration from
1482 /// C++ pure virtual functions (a C++ feature with nice semantics and lousy
1483 /// syntax:-). Here is an example:
1486 /// \@protocol NSDraggingInfo <refproto1, refproto2>
1487 /// - (NSWindow *)draggingDestinationWindow;
1488 /// - (NSImage *)draggedImage;
1492 /// This says that NSDraggingInfo requires two methods and requires everything
1493 /// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
1497 /// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
1501 /// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
1502 /// protocols are in distinct namespaces. For example, Cocoa defines both
1503 /// an NSObject protocol and class (which isn't allowed in Java). As a result,
1504 /// protocols are referenced using angle brackets as follows:
1506 /// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
1508 class ObjCProtocolDecl : public ObjCContainerDecl,
1509 public Redeclarable<ObjCProtocolDecl> {
1510 void anchor() override;
1512 struct DefinitionData {
1513 // \brief The declaration that defines this protocol.
1514 ObjCProtocolDecl *Definition;
1516 /// \brief Referenced protocols
1517 ObjCProtocolList ReferencedProtocols;
1520 /// \brief Contains a pointer to the data associated with this class,
1521 /// which will be NULL if this class has not yet been defined.
1523 /// The bit indicates when we don't need to check for out-of-date
1524 /// declarations. It will be set unless modules are enabled.
1525 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1527 DefinitionData &data() const {
1528 assert(Data.getPointer() && "Objective-C protocol has no definition!");
1529 return *Data.getPointer();
1532 ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
1533 SourceLocation nameLoc, SourceLocation atStartLoc,
1534 ObjCProtocolDecl *PrevDecl);
1536 void allocateDefinitionData();
1538 typedef Redeclarable<ObjCProtocolDecl> redeclarable_base;
1539 ObjCProtocolDecl *getNextRedeclarationImpl() override {
1540 return getNextRedeclaration();
1542 ObjCProtocolDecl *getPreviousDeclImpl() override {
1543 return getPreviousDecl();
1545 ObjCProtocolDecl *getMostRecentDeclImpl() override {
1546 return getMostRecentDecl();
1550 static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
1552 SourceLocation nameLoc,
1553 SourceLocation atStartLoc,
1554 ObjCProtocolDecl *PrevDecl);
1556 static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1558 const ObjCProtocolList &getReferencedProtocols() const {
1559 assert(hasDefinition() && "No definition available!");
1560 return data().ReferencedProtocols;
1562 typedef ObjCProtocolList::iterator protocol_iterator;
1563 typedef llvm::iterator_range<protocol_iterator> protocol_range;
1565 protocol_range protocols() const {
1566 return protocol_range(protocol_begin(), protocol_end());
1568 protocol_iterator protocol_begin() const {
1569 if (!hasDefinition())
1570 return protocol_iterator();
1572 return data().ReferencedProtocols.begin();
1574 protocol_iterator protocol_end() const {
1575 if (!hasDefinition())
1576 return protocol_iterator();
1578 return data().ReferencedProtocols.end();
1580 typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1581 typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
1583 protocol_loc_range protocol_locs() const {
1584 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1586 protocol_loc_iterator protocol_loc_begin() const {
1587 if (!hasDefinition())
1588 return protocol_loc_iterator();
1590 return data().ReferencedProtocols.loc_begin();
1592 protocol_loc_iterator protocol_loc_end() const {
1593 if (!hasDefinition())
1594 return protocol_loc_iterator();
1596 return data().ReferencedProtocols.loc_end();
1598 unsigned protocol_size() const {
1599 if (!hasDefinition())
1602 return data().ReferencedProtocols.size();
1605 /// setProtocolList - Set the list of protocols that this interface
1607 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1608 const SourceLocation *Locs, ASTContext &C) {
1609 assert(hasDefinition() && "Protocol is not defined");
1610 data().ReferencedProtocols.set(List, Num, Locs, C);
1613 ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
1615 // Lookup a method. First, we search locally. If a method isn't
1616 // found, we search referenced protocols and class categories.
1617 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
1618 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1619 return lookupMethod(Sel, true/*isInstance*/);
1621 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1622 return lookupMethod(Sel, false/*isInstance*/);
1625 /// \brief Determine whether this protocol has a definition.
1626 bool hasDefinition() const {
1627 // If the name of this protocol is out-of-date, bring it up-to-date, which
1628 // might bring in a definition.
1629 // Note: a null value indicates that we don't have a definition and that
1630 // modules are enabled.
1631 if (!Data.getOpaqueValue()) {
1632 if (IdentifierInfo *II = getIdentifier()) {
1633 if (II->isOutOfDate()) {
1634 updateOutOfDate(*II);
1639 return Data.getPointer();
1642 /// \brief Retrieve the definition of this protocol, if any.
1643 ObjCProtocolDecl *getDefinition() {
1644 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1647 /// \brief Retrieve the definition of this protocol, if any.
1648 const ObjCProtocolDecl *getDefinition() const {
1649 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1652 /// \brief Determine whether this particular declaration is also the
1654 bool isThisDeclarationADefinition() const {
1655 return getDefinition() == this;
1658 /// \brief Starts the definition of this Objective-C protocol.
1659 void startDefinition();
1661 /// Produce a name to be used for protocol's metadata. It comes either via
1662 /// objc_runtime_name attribute or protocol name.
1663 StringRef getObjCRuntimeNameAsString() const;
1665 SourceRange getSourceRange() const override LLVM_READONLY {
1666 if (isThisDeclarationADefinition())
1667 return ObjCContainerDecl::getSourceRange();
1669 return SourceRange(getAtStartLoc(), getLocation());
1672 typedef redeclarable_base::redecl_range redecl_range;
1673 typedef redeclarable_base::redecl_iterator redecl_iterator;
1674 using redeclarable_base::redecls_begin;
1675 using redeclarable_base::redecls_end;
1676 using redeclarable_base::redecls;
1677 using redeclarable_base::getPreviousDecl;
1678 using redeclarable_base::getMostRecentDecl;
1679 using redeclarable_base::isFirstDecl;
1681 /// Retrieves the canonical declaration of this Objective-C protocol.
1682 ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
1683 const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
1685 void collectPropertiesToImplement(PropertyMap &PM,
1686 PropertyDeclOrder &PO) const override;
1688 void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
1689 ProtocolPropertyMap &PM) const;
1691 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1692 static bool classofKind(Kind K) { return K == ObjCProtocol; }
1694 friend class ASTReader;
1695 friend class ASTDeclReader;
1696 friend class ASTDeclWriter;
1699 /// ObjCCategoryDecl - Represents a category declaration. A category allows
1700 /// you to add methods to an existing class (without subclassing or modifying
1701 /// the original class interface or implementation:-). Categories don't allow
1702 /// you to add instance data. The following example adds "myMethod" to all
1703 /// NSView's within a process:
1705 /// \@interface NSView (MyViewMethods)
1709 /// Categories also allow you to split the implementation of a class across
1710 /// several files (a feature more naturally supported in C++).
1712 /// Categories were originally inspired by dynamic languages such as Common
1713 /// Lisp and Smalltalk. More traditional class-based languages (C++, Java)
1714 /// don't support this level of dynamism, which is both powerful and dangerous.
1716 class ObjCCategoryDecl : public ObjCContainerDecl {
1717 void anchor() override;
1719 /// Interface belonging to this category
1720 ObjCInterfaceDecl *ClassInterface;
1722 /// referenced protocols in this category.
1723 ObjCProtocolList ReferencedProtocols;
1725 /// Next category belonging to this class.
1726 /// FIXME: this should not be a singly-linked list. Move storage elsewhere.
1727 ObjCCategoryDecl *NextClassCategory;
1729 /// \brief The location of the category name in this declaration.
1730 SourceLocation CategoryNameLoc;
1732 /// class extension may have private ivars.
1733 SourceLocation IvarLBraceLoc;
1734 SourceLocation IvarRBraceLoc;
1736 ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1737 SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
1738 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1739 SourceLocation IvarLBraceLoc=SourceLocation(),
1740 SourceLocation IvarRBraceLoc=SourceLocation())
1741 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1742 ClassInterface(IDecl), NextClassCategory(nullptr),
1743 CategoryNameLoc(CategoryNameLoc),
1744 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
1749 static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
1750 SourceLocation AtLoc,
1751 SourceLocation ClassNameLoc,
1752 SourceLocation CategoryNameLoc,
1754 ObjCInterfaceDecl *IDecl,
1755 SourceLocation IvarLBraceLoc=SourceLocation(),
1756 SourceLocation IvarRBraceLoc=SourceLocation());
1757 static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1759 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1760 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1762 ObjCCategoryImplDecl *getImplementation() const;
1763 void setImplementation(ObjCCategoryImplDecl *ImplD);
1765 /// setProtocolList - Set the list of protocols that this interface
1767 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1768 const SourceLocation *Locs, ASTContext &C) {
1769 ReferencedProtocols.set(List, Num, Locs, C);
1772 const ObjCProtocolList &getReferencedProtocols() const {
1773 return ReferencedProtocols;
1776 typedef ObjCProtocolList::iterator protocol_iterator;
1777 typedef llvm::iterator_range<protocol_iterator> protocol_range;
1779 protocol_range protocols() const {
1780 return protocol_range(protocol_begin(), protocol_end());
1782 protocol_iterator protocol_begin() const {
1783 return ReferencedProtocols.begin();
1785 protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
1786 unsigned protocol_size() const { return ReferencedProtocols.size(); }
1787 typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1788 typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
1790 protocol_loc_range protocol_locs() const {
1791 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1793 protocol_loc_iterator protocol_loc_begin() const {
1794 return ReferencedProtocols.loc_begin();
1796 protocol_loc_iterator protocol_loc_end() const {
1797 return ReferencedProtocols.loc_end();
1800 ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
1802 /// \brief Retrieve the pointer to the next stored category (or extension),
1803 /// which may be hidden.
1804 ObjCCategoryDecl *getNextClassCategoryRaw() const {
1805 return NextClassCategory;
1808 bool IsClassExtension() const { return getIdentifier() == nullptr; }
1810 typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1811 typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
1813 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
1814 ivar_iterator ivar_begin() const {
1815 return ivar_iterator(decls_begin());
1817 ivar_iterator ivar_end() const {
1818 return ivar_iterator(decls_end());
1820 unsigned ivar_size() const {
1821 return std::distance(ivar_begin(), ivar_end());
1823 bool ivar_empty() const {
1824 return ivar_begin() == ivar_end();
1827 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1828 void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
1830 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
1831 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
1832 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
1833 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1835 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1836 static bool classofKind(Kind K) { return K == ObjCCategory; }
1838 friend class ASTDeclReader;
1839 friend class ASTDeclWriter;
1842 class ObjCImplDecl : public ObjCContainerDecl {
1843 void anchor() override;
1845 /// Class interface for this class/category implementation
1846 ObjCInterfaceDecl *ClassInterface;
1849 ObjCImplDecl(Kind DK, DeclContext *DC,
1850 ObjCInterfaceDecl *classInterface,
1851 SourceLocation nameLoc, SourceLocation atStartLoc)
1852 : ObjCContainerDecl(DK, DC,
1853 classInterface? classInterface->getIdentifier()
1855 nameLoc, atStartLoc),
1856 ClassInterface(classInterface) {}
1859 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1860 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1861 void setClassInterface(ObjCInterfaceDecl *IFace);
1863 void addInstanceMethod(ObjCMethodDecl *method) {
1864 // FIXME: Context should be set correctly before we get here.
1865 method->setLexicalDeclContext(this);
1868 void addClassMethod(ObjCMethodDecl *method) {
1869 // FIXME: Context should be set correctly before we get here.
1870 method->setLexicalDeclContext(this);
1874 void addPropertyImplementation(ObjCPropertyImplDecl *property);
1876 ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const;
1877 ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
1879 // Iterator access to properties.
1880 typedef specific_decl_iterator<ObjCPropertyImplDecl> propimpl_iterator;
1881 typedef llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>
1884 propimpl_range property_impls() const {
1885 return propimpl_range(propimpl_begin(), propimpl_end());
1887 propimpl_iterator propimpl_begin() const {
1888 return propimpl_iterator(decls_begin());
1890 propimpl_iterator propimpl_end() const {
1891 return propimpl_iterator(decls_end());
1894 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1895 static bool classofKind(Kind K) {
1896 return K >= firstObjCImpl && K <= lastObjCImpl;
1900 /// ObjCCategoryImplDecl - An object of this class encapsulates a category
1901 /// \@implementation declaration. If a category class has declaration of a
1902 /// property, its implementation must be specified in the category's
1903 /// \@implementation declaration. Example:
1904 /// \@interface I \@end
1905 /// \@interface I(CATEGORY)
1906 /// \@property int p1, d1;
1908 /// \@implementation I(CATEGORY)
1909 /// \@dynamic p1,d1;
1912 /// ObjCCategoryImplDecl
1913 class ObjCCategoryImplDecl : public ObjCImplDecl {
1914 void anchor() override;
1919 // Category name location
1920 SourceLocation CategoryNameLoc;
1922 ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
1923 ObjCInterfaceDecl *classInterface,
1924 SourceLocation nameLoc, SourceLocation atStartLoc,
1925 SourceLocation CategoryNameLoc)
1926 : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartLoc),
1927 Id(Id), CategoryNameLoc(CategoryNameLoc) {}
1929 static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
1931 ObjCInterfaceDecl *classInterface,
1932 SourceLocation nameLoc,
1933 SourceLocation atStartLoc,
1934 SourceLocation CategoryNameLoc);
1935 static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1937 /// getIdentifier - Get the identifier that names the category
1938 /// interface associated with this implementation.
1939 /// FIXME: This is a bad API, we are hiding NamedDecl::getIdentifier()
1940 /// with a different meaning. For example:
1941 /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()
1942 /// returns the class interface name, whereas
1943 /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()
1944 /// returns the category name.
1945 IdentifierInfo *getIdentifier() const {
1948 void setIdentifier(IdentifierInfo *II) { Id = II; }
1950 ObjCCategoryDecl *getCategoryDecl() const;
1952 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1954 /// getName - Get the name of identifier for the class interface associated
1955 /// with this implementation as a StringRef.
1957 // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
1959 StringRef getName() const { return Id ? Id->getName() : StringRef(); }
1961 /// @brief Get the name of the class associated with this interface.
1963 // FIXME: Deprecated, move clients to getName().
1964 std::string getNameAsString() const {
1968 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1969 static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
1971 friend class ASTDeclReader;
1972 friend class ASTDeclWriter;
1975 raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
1977 /// ObjCImplementationDecl - Represents a class definition - this is where
1978 /// method definitions are specified. For example:
1981 /// \@implementation MyClass
1982 /// - (void)myMethod { /* do something */ }
1986 /// In a non-fragile runtime, instance variables can appear in the class
1987 /// interface, class extensions (nameless categories), and in the implementation
1988 /// itself, as well as being synthesized as backing storage for properties.
1990 /// In a fragile runtime, instance variables are specified in the class
1991 /// interface, \em not in the implementation. Nevertheless (for legacy reasons),
1992 /// we allow instance variables to be specified in the implementation. When
1993 /// specified, they need to be \em identical to the interface.
1994 class ObjCImplementationDecl : public ObjCImplDecl {
1995 void anchor() override;
1996 /// Implementation Class's super class.
1997 ObjCInterfaceDecl *SuperClass;
1998 SourceLocation SuperLoc;
2000 /// \@implementation may have private ivars.
2001 SourceLocation IvarLBraceLoc;
2002 SourceLocation IvarRBraceLoc;
2004 /// Support for ivar initialization.
2005 /// \brief The arguments used to initialize the ivars
2006 LazyCXXCtorInitializersPtr IvarInitializers;
2007 unsigned NumIvarInitializers;
2009 /// Do the ivars of this class require initialization other than
2010 /// zero-initialization?
2011 bool HasNonZeroConstructors : 1;
2013 /// Do the ivars of this class require non-trivial destruction?
2014 bool HasDestructors : 1;
2016 ObjCImplementationDecl(DeclContext *DC,
2017 ObjCInterfaceDecl *classInterface,
2018 ObjCInterfaceDecl *superDecl,
2019 SourceLocation nameLoc, SourceLocation atStartLoc,
2020 SourceLocation superLoc = SourceLocation(),
2021 SourceLocation IvarLBraceLoc=SourceLocation(),
2022 SourceLocation IvarRBraceLoc=SourceLocation())
2023 : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStartLoc),
2024 SuperClass(superDecl), SuperLoc(superLoc), IvarLBraceLoc(IvarLBraceLoc),
2025 IvarRBraceLoc(IvarRBraceLoc),
2026 IvarInitializers(nullptr), NumIvarInitializers(0),
2027 HasNonZeroConstructors(false), HasDestructors(false) {}
2029 static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2030 ObjCInterfaceDecl *classInterface,
2031 ObjCInterfaceDecl *superDecl,
2032 SourceLocation nameLoc,
2033 SourceLocation atStartLoc,
2034 SourceLocation superLoc = SourceLocation(),
2035 SourceLocation IvarLBraceLoc=SourceLocation(),
2036 SourceLocation IvarRBraceLoc=SourceLocation());
2038 static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2040 /// init_iterator - Iterates through the ivar initializer list.
2041 typedef CXXCtorInitializer **init_iterator;
2043 /// init_const_iterator - Iterates through the ivar initializer list.
2044 typedef CXXCtorInitializer * const * init_const_iterator;
2046 typedef llvm::iterator_range<init_iterator> init_range;
2047 typedef llvm::iterator_range<init_const_iterator> init_const_range;
2049 init_range inits() { return init_range(init_begin(), init_end()); }
2050 init_const_range inits() const {
2051 return init_const_range(init_begin(), init_end());
2054 /// init_begin() - Retrieve an iterator to the first initializer.
2055 init_iterator init_begin() {
2056 const auto *ConstThis = this;
2057 return const_cast<init_iterator>(ConstThis->init_begin());
2059 /// begin() - Retrieve an iterator to the first initializer.
2060 init_const_iterator init_begin() const;
2062 /// init_end() - Retrieve an iterator past the last initializer.
2063 init_iterator init_end() {
2064 return init_begin() + NumIvarInitializers;
2066 /// end() - Retrieve an iterator past the last initializer.
2067 init_const_iterator init_end() const {
2068 return init_begin() + NumIvarInitializers;
2070 /// getNumArgs - Number of ivars which must be initialized.
2071 unsigned getNumIvarInitializers() const {
2072 return NumIvarInitializers;
2075 void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2076 NumIvarInitializers = numNumIvarInitializers;
2079 void setIvarInitializers(ASTContext &C,
2080 CXXCtorInitializer ** initializers,
2081 unsigned numInitializers);
2083 /// Do any of the ivars of this class (not counting its base classes)
2084 /// require construction other than zero-initialization?
2085 bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
2086 void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2088 /// Do any of the ivars of this class (not counting its base classes)
2089 /// require non-trivial destruction?
2090 bool hasDestructors() const { return HasDestructors; }
2091 void setHasDestructors(bool val) { HasDestructors = val; }
2093 /// getIdentifier - Get the identifier that names the class
2094 /// interface associated with this implementation.
2095 IdentifierInfo *getIdentifier() const {
2096 return getClassInterface()->getIdentifier();
2099 /// getName - Get the name of identifier for the class interface associated
2100 /// with this implementation as a StringRef.
2102 // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2104 StringRef getName() const {
2105 assert(getIdentifier() && "Name is not a simple identifier");
2106 return getIdentifier()->getName();
2109 /// @brief Get the name of the class associated with this interface.
2111 // FIXME: Move to StringRef API.
2112 std::string getNameAsString() const {
2116 /// Produce a name to be used for class's metadata. It comes either via
2117 /// class's objc_runtime_name attribute or class name.
2118 StringRef getObjCRuntimeNameAsString() const;
2120 const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
2121 ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
2122 SourceLocation getSuperClassLoc() const { return SuperLoc; }
2124 void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2126 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2127 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2128 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2129 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2131 typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
2132 typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
2134 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2135 ivar_iterator ivar_begin() const {
2136 return ivar_iterator(decls_begin());
2138 ivar_iterator ivar_end() const {
2139 return ivar_iterator(decls_end());
2141 unsigned ivar_size() const {
2142 return std::distance(ivar_begin(), ivar_end());
2144 bool ivar_empty() const {
2145 return ivar_begin() == ivar_end();
2148 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2149 static bool classofKind(Kind K) { return K == ObjCImplementation; }
2151 friend class ASTDeclReader;
2152 friend class ASTDeclWriter;
2155 raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2157 /// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2158 /// declared as \@compatibility_alias alias class.
2159 class ObjCCompatibleAliasDecl : public NamedDecl {
2160 void anchor() override;
2161 /// Class that this is an alias of.
2162 ObjCInterfaceDecl *AliasedClass;
2164 ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2165 ObjCInterfaceDecl* aliasedClass)
2166 : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2168 static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2169 SourceLocation L, IdentifierInfo *Id,
2170 ObjCInterfaceDecl* aliasedClass);
2172 static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2175 const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
2176 ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
2177 void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2179 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2180 static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2184 /// \brief Represents one property declaration in an Objective-C interface.
2188 /// \@property (assign, readwrite) int MyProperty;
2190 class ObjCPropertyDecl : public NamedDecl {
2191 void anchor() override;
2193 enum PropertyAttributeKind {
2194 OBJC_PR_noattr = 0x00,
2195 OBJC_PR_readonly = 0x01,
2196 OBJC_PR_getter = 0x02,
2197 OBJC_PR_assign = 0x04,
2198 OBJC_PR_readwrite = 0x08,
2199 OBJC_PR_retain = 0x10,
2200 OBJC_PR_copy = 0x20,
2201 OBJC_PR_nonatomic = 0x40,
2202 OBJC_PR_setter = 0x80,
2203 OBJC_PR_atomic = 0x100,
2204 OBJC_PR_weak = 0x200,
2205 OBJC_PR_strong = 0x400,
2206 OBJC_PR_unsafe_unretained = 0x800
2207 // Adding a property should change NumPropertyAttrsBits
2211 /// \brief Number of bits fitting all the property attributes.
2212 NumPropertyAttrsBits = 12
2215 enum SetterKind { Assign, Retain, Copy, Weak };
2216 enum PropertyControl { None, Required, Optional };
2218 SourceLocation AtLoc; // location of \@property
2219 SourceLocation LParenLoc; // location of '(' starting attribute list or null.
2220 TypeSourceInfo *DeclType;
2221 unsigned PropertyAttributes : NumPropertyAttrsBits;
2222 unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
2223 // \@required/\@optional
2224 unsigned PropertyImplementation : 2;
2226 Selector GetterName; // getter name of NULL if no getter
2227 Selector SetterName; // setter name of NULL if no setter
2229 ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method
2230 ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method
2231 ObjCIvarDecl *PropertyIvarDecl; // Synthesize ivar for this property
2233 ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2234 SourceLocation AtLocation, SourceLocation LParenLocation,
2236 : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
2237 LParenLoc(LParenLocation), DeclType(T),
2238 PropertyAttributes(OBJC_PR_noattr),
2239 PropertyAttributesAsWritten(OBJC_PR_noattr),
2240 PropertyImplementation(None),
2241 GetterName(Selector()),
2242 SetterName(Selector()),
2243 GetterMethodDecl(nullptr), SetterMethodDecl(nullptr),
2244 PropertyIvarDecl(nullptr) {}
2247 static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
2249 IdentifierInfo *Id, SourceLocation AtLocation,
2250 SourceLocation LParenLocation,
2252 PropertyControl propControl = None);
2254 static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2256 SourceLocation getAtLoc() const { return AtLoc; }
2257 void setAtLoc(SourceLocation L) { AtLoc = L; }
2259 SourceLocation getLParenLoc() const { return LParenLoc; }
2260 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2262 TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
2263 QualType getType() const { return DeclType->getType(); }
2264 void setType(TypeSourceInfo *T) { DeclType = T; }
2266 PropertyAttributeKind getPropertyAttributes() const {
2267 return PropertyAttributeKind(PropertyAttributes);
2269 void setPropertyAttributes(PropertyAttributeKind PRVal) {
2270 PropertyAttributes |= PRVal;
2273 PropertyAttributeKind getPropertyAttributesAsWritten() const {
2274 return PropertyAttributeKind(PropertyAttributesAsWritten);
2277 bool hasWrittenStorageAttribute() const {
2278 return PropertyAttributesAsWritten & (OBJC_PR_assign | OBJC_PR_copy |
2279 OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong |
2283 void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
2284 PropertyAttributesAsWritten = PRVal;
2287 void makeitReadWriteAttribute() {
2288 PropertyAttributes &= ~OBJC_PR_readonly;
2289 PropertyAttributes |= OBJC_PR_readwrite;
2292 // Helper methods for accessing attributes.
2294 /// isReadOnly - Return true iff the property has a setter.
2295 bool isReadOnly() const {
2296 return (PropertyAttributes & OBJC_PR_readonly);
2299 /// isAtomic - Return true if the property is atomic.
2300 bool isAtomic() const {
2301 return (PropertyAttributes & OBJC_PR_atomic);
2304 /// isRetaining - Return true if the property retains its value.
2305 bool isRetaining() const {
2306 return (PropertyAttributes &
2307 (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
2310 /// getSetterKind - Return the method used for doing assignment in
2311 /// the property setter. This is only valid if the property has been
2312 /// defined to have a setter.
2313 SetterKind getSetterKind() const {
2314 if (PropertyAttributes & OBJC_PR_strong)
2315 return getType()->isBlockPointerType() ? Copy : Retain;
2316 if (PropertyAttributes & OBJC_PR_retain)
2318 if (PropertyAttributes & OBJC_PR_copy)
2320 if (PropertyAttributes & OBJC_PR_weak)
2325 Selector getGetterName() const { return GetterName; }
2326 void setGetterName(Selector Sel) { GetterName = Sel; }
2328 Selector getSetterName() const { return SetterName; }
2329 void setSetterName(Selector Sel) { SetterName = Sel; }
2331 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
2332 void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
2334 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
2335 void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
2337 // Related to \@optional/\@required declared in \@protocol
2338 void setPropertyImplementation(PropertyControl pc) {
2339 PropertyImplementation = pc;
2341 PropertyControl getPropertyImplementation() const {
2342 return PropertyControl(PropertyImplementation);
2345 void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
2346 PropertyIvarDecl = Ivar;
2348 ObjCIvarDecl *getPropertyIvarDecl() const {
2349 return PropertyIvarDecl;
2352 SourceRange getSourceRange() const override LLVM_READONLY {
2353 return SourceRange(AtLoc, getLocation());
2356 /// Get the default name of the synthesized ivar.
2357 IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
2359 /// Lookup a property by name in the specified DeclContext.
2360 static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
2361 const IdentifierInfo *propertyID);
2363 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2364 static bool classofKind(Kind K) { return K == ObjCProperty; }
2367 /// ObjCPropertyImplDecl - Represents implementation declaration of a property
2368 /// in a class or category implementation block. For example:
2369 /// \@synthesize prop1 = ivar1;
2371 class ObjCPropertyImplDecl : public Decl {
2378 SourceLocation AtLoc; // location of \@synthesize or \@dynamic
2380 /// \brief For \@synthesize, the location of the ivar, if it was written in
2381 /// the source code.
2384 /// \@synthesize int a = b
2386 SourceLocation IvarLoc;
2388 /// Property declaration being implemented
2389 ObjCPropertyDecl *PropertyDecl;
2391 /// Null for \@dynamic. Required for \@synthesize.
2392 ObjCIvarDecl *PropertyIvarDecl;
2394 /// Null for \@dynamic. Non-null if property must be copy-constructed in
2396 Expr *GetterCXXConstructor;
2398 /// Null for \@dynamic. Non-null if property has assignment operator to call
2399 /// in Setter synthesis.
2400 Expr *SetterCXXAssignment;
2402 ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2403 ObjCPropertyDecl *property,
2405 ObjCIvarDecl *ivarDecl,
2406 SourceLocation ivarLoc)
2407 : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2408 IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl),
2409 GetterCXXConstructor(nullptr), SetterCXXAssignment(nullptr) {
2410 assert (PK == Dynamic || PropertyIvarDecl);
2414 static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2415 SourceLocation atLoc, SourceLocation L,
2416 ObjCPropertyDecl *property,
2418 ObjCIvarDecl *ivarDecl,
2419 SourceLocation ivarLoc);
2421 static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2423 SourceRange getSourceRange() const override LLVM_READONLY;
2425 SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
2426 void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2428 ObjCPropertyDecl *getPropertyDecl() const {
2429 return PropertyDecl;
2431 void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2433 Kind getPropertyImplementation() const {
2434 return PropertyIvarDecl ? Synthesize : Dynamic;
2437 ObjCIvarDecl *getPropertyIvarDecl() const {
2438 return PropertyIvarDecl;
2440 SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2442 void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2443 SourceLocation IvarLoc) {
2444 PropertyIvarDecl = Ivar;
2445 this->IvarLoc = IvarLoc;
2448 /// \brief For \@synthesize, returns true if an ivar name was explicitly
2452 /// \@synthesize int a = b; // true
2453 /// \@synthesize int a; // false
2455 bool isIvarNameSpecified() const {
2456 return IvarLoc.isValid() && IvarLoc != getLocation();
2459 Expr *getGetterCXXConstructor() const {
2460 return GetterCXXConstructor;
2462 void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2463 GetterCXXConstructor = getterCXXConstructor;
2466 Expr *getSetterCXXAssignment() const {
2467 return SetterCXXAssignment;
2469 void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2470 SetterCXXAssignment = setterCXXAssignment;
2473 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2474 static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2476 friend class ASTDeclReader;
2479 template<bool (*Filter)(ObjCCategoryDecl *)>
2481 ObjCInterfaceDecl::filtered_category_iterator<Filter>::
2482 findAcceptableCategory() {
2483 while (Current && !Filter(Current))
2484 Current = Current->getNextClassCategoryRaw();
2487 template<bool (*Filter)(ObjCCategoryDecl *)>
2488 inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2489 ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2490 Current = Current->getNextClassCategoryRaw();
2491 findAcceptableCategory();
2495 inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2496 return !Cat->isHidden();
2499 inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2500 return Cat->IsClassExtension() && !Cat->isHidden();
2503 inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2504 return Cat->IsClassExtension();
2507 } // end namespace clang