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/DeclBase.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/Redeclarable.h"
21#include "clang/AST/SelectorLocationsKind.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/IdentifierTable.h"
24#include "clang/Basic/LLVM.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Basic/Specifiers.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/None.h"
31#include "llvm/ADT/PointerIntPair.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/iterator_range.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/TrailingObjects.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <string>
42#include <utility>
43
44namespace clang {
45
46class ASTContext;
47class CompoundStmt;
48class CXXCtorInitializer;
49class Expr;
50class ObjCCategoryDecl;
51class ObjCCategoryImplDecl;
52class ObjCImplementationDecl;
53class ObjCInterfaceDecl;
54class ObjCIvarDecl;
55class ObjCPropertyDecl;
56class ObjCPropertyImplDecl;
57class ObjCProtocolDecl;
58class Stmt;
59
60class ObjCListBase {
61protected:
62 /// List is an array of pointers to objects that are not owned by this object.
63 void **List = nullptr;
64 unsigned NumElts = 0;
65
66public:
67 ObjCListBase() = default;
68 ObjCListBase(const ObjCListBase &) = delete;
69 ObjCListBase &operator=(const ObjCListBase &) = delete;
70
71 unsigned size() const { return NumElts; }
72 bool empty() const { return NumElts == 0; }
73
74protected:
75 void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
76};
77
78/// ObjCList - This is a simple template class used to hold various lists of
79/// decls etc, which is heavily used by the ObjC front-end. This only use case
80/// this supports is setting the list all at once and then reading elements out
81/// of it.
82template <typename T>
83class ObjCList : public ObjCListBase {
84public:
85 void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
86 ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
87 }
88
89 using iterator = T* const *;
90
91 iterator begin() const { return (iterator)List; }
92 iterator end() const { return (iterator)List+NumElts; }
93
94 T* operator[](unsigned Idx) const {
95 assert(Idx < NumElts && "Invalid access");
96 return (T*)List[Idx];
97 }
98};
99
100/// A list of Objective-C protocols, along with the source
101/// locations at which they were referenced.
102class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
103 SourceLocation *Locations = nullptr;
104
105 using ObjCList<ObjCProtocolDecl>::set;
106
107public:
108 ObjCProtocolList() = default;
109
110 using loc_iterator = const SourceLocation *;
111
112 loc_iterator loc_begin() const { return Locations; }
113 loc_iterator loc_end() const { return Locations + size(); }
114
115 void set(ObjCProtocolDecl* const* InList, unsigned Elts,
116 const SourceLocation *Locs, ASTContext &Ctx);
117};
118
119/// ObjCMethodDecl - Represents an instance or class method declaration.
120/// ObjC methods can be declared within 4 contexts: class interfaces,
121/// categories, protocols, and class implementations. While C++ member
122/// functions leverage C syntax, Objective-C method syntax is modeled after
123/// Smalltalk (using colons to specify argument types/expressions).
124/// Here are some brief examples:
125///
126/// Setter/getter instance methods:
127/// - (void)setMenu:(NSMenu *)menu;
128/// - (NSMenu *)menu;
129///
130/// Instance method that takes 2 NSView arguments:
131/// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
132///
133/// Getter class method:
134/// + (NSMenu *)defaultMenu;
135///
136/// A selector represents a unique name for a method. The selector names for
137/// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
138///
139class ObjCMethodDecl : public NamedDecl, public DeclContext {
140 // This class stores some data in DeclContext::ObjCMethodDeclBits
141 // to save some space. Use the provided accessors to access it.
142
143public:
144 enum ImplementationControl { None, Required, Optional };
145
146private:
147 /// Return type of this method.
148 QualType MethodDeclType;
149
150 /// Type source information for the return type.
151 TypeSourceInfo *ReturnTInfo;
152
153 /// Array of ParmVarDecls for the formal parameters of this method
154 /// and optionally followed by selector locations.
155 void *ParamsAndSelLocs = nullptr;
156 unsigned NumParams = 0;
157
158 /// List of attributes for this method declaration.
159 SourceLocation DeclEndLoc; // the location of the ';' or '{'.
160
161 /// The following are only used for method definitions, null otherwise.
162 LazyDeclStmtPtr Body;
163
164 /// SelfDecl - Decl for the implicit self parameter. This is lazily
165 /// constructed by createImplicitParams.
166 ImplicitParamDecl *SelfDecl = nullptr;
167
168 /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
169 /// constructed by createImplicitParams.
170 ImplicitParamDecl *CmdDecl = nullptr;
171
172 ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
173 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
174 DeclContext *contextDecl, bool isInstance = true,
175 bool isVariadic = false, bool isPropertyAccessor = false,
176 bool isImplicitlyDeclared = false, bool isDefined = false,
177 ImplementationControl impControl = None,
178 bool HasRelatedResultType = false);
179
180 SelectorLocationsKind getSelLocsKind() const {
181 return static_cast<SelectorLocationsKind>(ObjCMethodDeclBits.SelLocsKind);
182 }
183
184 void setSelLocsKind(SelectorLocationsKind Kind) {
185 ObjCMethodDeclBits.SelLocsKind = Kind;
186 }
187
188 bool hasStandardSelLocs() const {
189 return getSelLocsKind() != SelLoc_NonStandard;
190 }
191
192 /// Get a pointer to the stored selector identifiers locations array.
193 /// No locations will be stored if HasStandardSelLocs is true.
194 SourceLocation *getStoredSelLocs() {
195 return reinterpret_cast<SourceLocation *>(getParams() + NumParams);
196 }
197 const SourceLocation *getStoredSelLocs() const {
198 return reinterpret_cast<const SourceLocation *>(getParams() + NumParams);
199 }
200
201 /// Get a pointer to the stored selector identifiers locations array.
202 /// No locations will be stored if HasStandardSelLocs is true.
203 ParmVarDecl **getParams() {
204 return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
205 }
206 const ParmVarDecl *const *getParams() const {
207 return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
208 }
209
210 /// Get the number of stored selector identifiers locations.
211 /// No locations will be stored if HasStandardSelLocs is true.
212 unsigned getNumStoredSelLocs() const {
213 if (hasStandardSelLocs())
214 return 0;
215 return getNumSelectorLocs();
216 }
217
218 void setParamsAndSelLocs(ASTContext &C,
219 ArrayRef<ParmVarDecl*> Params,
220 ArrayRef<SourceLocation> SelLocs);
221
222 /// A definition will return its interface declaration.
223 /// An interface declaration will return its definition.
224 /// Otherwise it will return itself.
225 ObjCMethodDecl *getNextRedeclarationImpl() override;
226
227public:
228 friend class ASTDeclReader;
229 friend class ASTDeclWriter;
230
231 static ObjCMethodDecl *
232 Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
233 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
234 DeclContext *contextDecl, bool isInstance = true,
235 bool isVariadic = false, bool isPropertyAccessor = false,
236 bool isImplicitlyDeclared = false, bool isDefined = false,
237 ImplementationControl impControl = None,
238 bool HasRelatedResultType = false);
239
240 static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
241
242 ObjCMethodDecl *getCanonicalDecl() override;
243 const ObjCMethodDecl *getCanonicalDecl() const {
244 return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
245 }
246
247 ObjCDeclQualifier getObjCDeclQualifier() const {
248 return static_cast<ObjCDeclQualifier>(ObjCMethodDeclBits.objcDeclQualifier);
249 }
250
251 void setObjCDeclQualifier(ObjCDeclQualifier QV) {
252 ObjCMethodDeclBits.objcDeclQualifier = QV;
253 }
254
255 /// Determine whether this method has a result type that is related
256 /// to the message receiver's type.
257 bool hasRelatedResultType() const {
258 return ObjCMethodDeclBits.RelatedResultType;
259 }
260
261 /// Note whether this method has a related result type.
262 void setRelatedResultType(bool RRT = true) {
263 ObjCMethodDeclBits.RelatedResultType = RRT;
264 }
265
266 /// True if this is a method redeclaration in the same interface.
267 bool isRedeclaration() const { return ObjCMethodDeclBits.IsRedeclaration; }
268 void setIsRedeclaration(bool RD) { ObjCMethodDeclBits.IsRedeclaration = RD; }
269 void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
270
271 /// True if redeclared in the same interface.
272 bool hasRedeclaration() const { return ObjCMethodDeclBits.HasRedeclaration; }
273 void setHasRedeclaration(bool HRD) const {
274 ObjCMethodDeclBits.HasRedeclaration = HRD;
275 }
276
277 /// Returns the location where the declarator ends. It will be
278 /// the location of ';' for a method declaration and the location of '{'
279 /// for a method definition.
280 SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
281
282 // Location information, modeled after the Stmt API.
283 SourceLocation getBeginLoc() const LLVM_READONLY { return getLocation(); }
284 SourceLocation getEndLoc() const LLVM_READONLY;
285 SourceRange getSourceRange() const override LLVM_READONLY {
286 return SourceRange(getLocation(), getEndLoc());
287 }
288
289 SourceLocation getSelectorStartLoc() const {
290 if (isImplicit())
291 return getBeginLoc();
292 return getSelectorLoc(0);
293 }
294
295 SourceLocation getSelectorLoc(unsigned Index) const {
296 assert(Index < getNumSelectorLocs() && "Index out of range!");
297 if (hasStandardSelLocs())
298 return getStandardSelectorLoc(Index, getSelector(),
299 getSelLocsKind() == SelLoc_StandardWithSpace,
300 parameters(),
301 DeclEndLoc);
302 return getStoredSelLocs()[Index];
303 }
304
305 void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
306
307 unsigned getNumSelectorLocs() const {
308 if (isImplicit())
309 return 0;
310 Selector Sel = getSelector();
311 if (Sel.isUnarySelector())
312 return 1;
313 return Sel.getNumArgs();
314 }
315
316 ObjCInterfaceDecl *getClassInterface();
317 const ObjCInterfaceDecl *getClassInterface() const {
318 return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
319 }
320
321 Selector getSelector() const { return getDeclName().getObjCSelector(); }
322
323 QualType getReturnType() const { return MethodDeclType; }
324 void setReturnType(QualType T) { MethodDeclType = T; }
325 SourceRange getReturnTypeSourceRange() const;
326
327 /// Determine the type of an expression that sends a message to this
328 /// function. This replaces the type parameters with the types they would
329 /// get if the receiver was parameterless (e.g. it may replace the type
330 /// parameter with 'id').
331 QualType getSendResultType() const;
332
333 /// Determine the type of an expression that sends a message to this
334 /// function with the given receiver type.
335 QualType getSendResultType(QualType receiverType) const;
336
337 TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
338 void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
339
340 // Iterator access to formal parameters.
341 unsigned param_size() const { return NumParams; }
342
343 using param_const_iterator = const ParmVarDecl *const *;
344 using param_iterator = ParmVarDecl *const *;
345 using param_range = llvm::iterator_range<param_iterator>;
346 using param_const_range = llvm::iterator_range<param_const_iterator>;
347
348 param_const_iterator param_begin() const {
349 return param_const_iterator(getParams());
350 }
351
352 param_const_iterator param_end() const {
353 return param_const_iterator(getParams() + NumParams);
354 }
355
356 param_iterator param_begin() { return param_iterator(getParams()); }
357 param_iterator param_end() { return param_iterator(getParams() + NumParams); }
358
359 // This method returns and of the parameters which are part of the selector
360 // name mangling requirements.
361 param_const_iterator sel_param_end() const {
362 return param_begin() + getSelector().getNumArgs();
363 }
364
365 // ArrayRef access to formal parameters. This should eventually
366 // replace the iterator interface above.
367 ArrayRef<ParmVarDecl*> parameters() const {
368 return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
369 NumParams);
370 }
371
372 /// Sets the method's parameters and selector source locations.
373 /// If the method is implicit (not coming from source) \p SelLocs is
374 /// ignored.
375 void setMethodParams(ASTContext &C,
376 ArrayRef<ParmVarDecl*> Params,
377 ArrayRef<SourceLocation> SelLocs = llvm::None);
378
379 // Iterator access to parameter types.
380 struct GetTypeFn {
381 QualType operator()(const ParmVarDecl *PD) const { return PD->getType(); }
382 };
383
384 using param_type_iterator =
385 llvm::mapped_iterator<param_const_iterator, GetTypeFn>;
386
387 param_type_iterator param_type_begin() const {
388 return llvm::map_iterator(param_begin(), GetTypeFn());
389 }
390
391 param_type_iterator param_type_end() const {
392 return llvm::map_iterator(param_end(), GetTypeFn());
393 }
394
395 /// createImplicitParams - Used to lazily create the self and cmd
396 /// implict parameters. This must be called prior to using getSelfDecl()
397 /// or getCmdDecl(). The call is ignored if the implicit parameters
398 /// have already been created.
399 void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
400
401 /// \return the type for \c self and set \arg selfIsPseudoStrong and
402 /// \arg selfIsConsumed accordingly.
403 QualType getSelfType(ASTContext &Context, const ObjCInterfaceDecl *OID,
404 bool &selfIsPseudoStrong, bool &selfIsConsumed);
405
406 ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
407 void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
408 ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
409 void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
410
411 /// Determines the family of this method.
412 ObjCMethodFamily getMethodFamily() const;
413
414 bool isInstanceMethod() const { return ObjCMethodDeclBits.IsInstance; }
415 void setInstanceMethod(bool isInst) {
416 ObjCMethodDeclBits.IsInstance = isInst;
417 }
418
419 bool isVariadic() const { return ObjCMethodDeclBits.IsVariadic; }
420 void setVariadic(bool isVar) { ObjCMethodDeclBits.IsVariadic = isVar; }
421
422 bool isClassMethod() const { return !isInstanceMethod(); }
423
424 bool isPropertyAccessor() const {
425 return ObjCMethodDeclBits.IsPropertyAccessor;
426 }
427
428 void setPropertyAccessor(bool isAccessor) {
429 ObjCMethodDeclBits.IsPropertyAccessor = isAccessor;
430 }
431
432 bool isDefined() const { return ObjCMethodDeclBits.IsDefined; }
433 void setDefined(bool isDefined) { ObjCMethodDeclBits.IsDefined = isDefined; }
434
435 /// Whether this method overrides any other in the class hierarchy.
436 ///
437 /// A method is said to override any method in the class's
438 /// base classes, its protocols, or its categories' protocols, that has
439 /// the same selector and is of the same kind (class or instance).
440 /// A method in an implementation is not considered as overriding the same
441 /// method in the interface or its categories.
442 bool isOverriding() const { return ObjCMethodDeclBits.IsOverriding; }
443 void setOverriding(bool IsOver) { ObjCMethodDeclBits.IsOverriding = IsOver; }
444
445 /// Return overridden methods for the given \p Method.
446 ///
447 /// An ObjC method is considered to override any method in the class's
448 /// base classes (and base's categories), its protocols, or its categories'
449 /// protocols, that has
450 /// the same selector and is of the same kind (class or instance).
451 /// A method in an implementation is not considered as overriding the same
452 /// method in the interface or its categories.
453 void getOverriddenMethods(
454 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
455
456 /// True if the method was a definition but its body was skipped.
457 bool hasSkippedBody() const { return ObjCMethodDeclBits.HasSkippedBody; }
458 void setHasSkippedBody(bool Skipped = true) {
459 ObjCMethodDeclBits.HasSkippedBody = Skipped;
460 }
461
462 /// Returns the property associated with this method's selector.
463 ///
464 /// Note that even if this particular method is not marked as a property
465 /// accessor, it is still possible for it to match a property declared in a
466 /// superclass. Pass \c false if you only want to check the current class.
467 const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
468
469 // Related to protocols declared in \@protocol
470 void setDeclImplementation(ImplementationControl ic) {
471 ObjCMethodDeclBits.DeclImplementation = ic;
472 }
473
474 ImplementationControl getImplementationControl() const {
475 return ImplementationControl(ObjCMethodDeclBits.DeclImplementation);
476 }
477
478 bool isOptional() const {
479 return getImplementationControl() == Optional;
480 }
481
482 /// Returns true if this specific method declaration is marked with the
483 /// designated initializer attribute.
484 bool isThisDeclarationADesignatedInitializer() const;
485
486 /// Returns true if the method selector resolves to a designated initializer
487 /// in the class's interface.
488 ///
489 /// \param InitMethod if non-null and the function returns true, it receives
490 /// the method declaration that was marked with the designated initializer
491 /// attribute.
492 bool isDesignatedInitializerForTheInterface(
493 const ObjCMethodDecl **InitMethod = nullptr) const;
494
495 /// Determine whether this method has a body.
496 bool hasBody() const override { return Body.isValid(); }
497
498 /// Retrieve the body of this method, if it has one.
499 Stmt *getBody() const override;
500
501 void setLazyBody(uint64_t Offset) { Body = Offset; }
502
503 CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
504 void setBody(Stmt *B) { Body = B; }
505
506 /// Returns whether this specific method is a definition.
507 bool isThisDeclarationADefinition() const { return hasBody(); }
508
509 /// Is this method defined in the NSObject base class?
510 bool definedInNSObject(const ASTContext &) const;
511
512 // Implement isa/cast/dyncast/etc.
513 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
514 static bool classofKind(Kind K) { return K == ObjCMethod; }
515
516 static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
517 return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
518 }
519
520 static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
521 return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
522 }
523};
524
525/// Describes the variance of a given generic parameter.
526enum class ObjCTypeParamVariance : uint8_t {
527 /// The parameter is invariant: must match exactly.
528 Invariant,
529
530 /// The parameter is covariant, e.g., X<T> is a subtype of X<U> when
531 /// the type parameter is covariant and T is a subtype of U.
532 Covariant,
533
534 /// The parameter is contravariant, e.g., X<T> is a subtype of X<U>
535 /// when the type parameter is covariant and U is a subtype of T.
536 Contravariant,
537};
538
539/// Represents the declaration of an Objective-C type parameter.
540///
541/// \code
542/// @interface NSDictionary<Key : id<NSCopying>, Value>
543/// @end
544/// \endcode
545///
546/// In the example above, both \c Key and \c Value are represented by
547/// \c ObjCTypeParamDecl. \c Key has an explicit bound of \c id<NSCopying>,
548/// while \c Value gets an implicit bound of \c id.
549///
550/// Objective-C type parameters are typedef-names in the grammar,
551class ObjCTypeParamDecl : public TypedefNameDecl {
552 /// Index of this type parameter in the type parameter list.
553 unsigned Index : 14;
554
555 /// The variance of the type parameter.
556 unsigned Variance : 2;
557
558 /// The location of the variance, if any.
559 SourceLocation VarianceLoc;
560
561 /// The location of the ':', which will be valid when the bound was
562 /// explicitly specified.
563 SourceLocation ColonLoc;
564
565 ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc,
566 ObjCTypeParamVariance variance, SourceLocation varianceLoc,
567 unsigned index,
568 SourceLocation nameLoc, IdentifierInfo *name,
569 SourceLocation colonLoc, TypeSourceInfo *boundInfo)
570 : TypedefNameDecl(ObjCTypeParam, ctx, dc, nameLoc, nameLoc, name,
571 boundInfo),
572 Index(index), Variance(static_cast<unsigned>(variance)),
573 VarianceLoc(varianceLoc), ColonLoc(colonLoc) {}
574
575 void anchor() override;
576
577public:
578 friend class ASTDeclReader;
579 friend class ASTDeclWriter;
580
581 static ObjCTypeParamDecl *Create(ASTContext &ctx, DeclContext *dc,
582 ObjCTypeParamVariance variance,
583 SourceLocation varianceLoc,
584 unsigned index,
585 SourceLocation nameLoc,
586 IdentifierInfo *name,
587 SourceLocation colonLoc,
588 TypeSourceInfo *boundInfo);
589 static ObjCTypeParamDecl *CreateDeserialized(ASTContext &ctx, unsigned ID);
590
591 SourceRange getSourceRange() const override LLVM_READONLY;
592
593 /// Determine the variance of this type parameter.
594 ObjCTypeParamVariance getVariance() const {
595 return static_cast<ObjCTypeParamVariance>(Variance);
596 }
597
598 /// Set the variance of this type parameter.
599 void setVariance(ObjCTypeParamVariance variance) {
600 Variance = static_cast<unsigned>(variance);
601 }
602
603 /// Retrieve the location of the variance keyword.
604 SourceLocation getVarianceLoc() const { return VarianceLoc; }
605
606 /// Retrieve the index into its type parameter list.
607 unsigned getIndex() const { return Index; }
608
609 /// Whether this type parameter has an explicitly-written type bound, e.g.,
610 /// "T : NSView".
611 bool hasExplicitBound() const { return ColonLoc.isValid(); }
612
613 /// Retrieve the location of the ':' separating the type parameter name
614 /// from the explicitly-specified bound.
615 SourceLocation getColonLoc() const { return ColonLoc; }
616
617 // Implement isa/cast/dyncast/etc.
618 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
619 static bool classofKind(Kind K) { return K == ObjCTypeParam; }
620};
621
622/// Stores a list of Objective-C type parameters for a parameterized class
623/// or a category/extension thereof.
624///
625/// \code
626/// @interface NSArray<T> // stores the <T>
627/// @end
628/// \endcode
629class ObjCTypeParamList final
630 : private llvm::TrailingObjects<ObjCTypeParamList, ObjCTypeParamDecl *> {
631 /// Stores the components of a SourceRange as a POD.
632 struct PODSourceRange {
633 unsigned Begin;
634 unsigned End;
635 };
636
637 union {
638 /// Location of the left and right angle brackets.
639 PODSourceRange Brackets;
640
641 // Used only for alignment.
642 ObjCTypeParamDecl *AlignmentHack;
643 };
644
645 /// The number of parameters in the list, which are tail-allocated.
646 unsigned NumParams;
647
648 ObjCTypeParamList(SourceLocation lAngleLoc,
649 ArrayRef<ObjCTypeParamDecl *> typeParams,
650 SourceLocation rAngleLoc);
651
652public:
653 friend TrailingObjects;
654
655 /// Create a new Objective-C type parameter list.
656 static ObjCTypeParamList *create(ASTContext &ctx,
657 SourceLocation lAngleLoc,
658 ArrayRef<ObjCTypeParamDecl *> typeParams,
659 SourceLocation rAngleLoc);
660
661 /// Iterate through the type parameters in the list.
662 using iterator = ObjCTypeParamDecl **;
663
664 iterator begin() { return getTrailingObjects<ObjCTypeParamDecl *>(); }
665
666 iterator end() { return begin() + size(); }
667
668 /// Determine the number of type parameters in this list.
669 unsigned size() const { return NumParams; }
670
671 // Iterate through the type parameters in the list.
672 using const_iterator = ObjCTypeParamDecl * const *;
673
674 const_iterator begin() const {
675 return getTrailingObjects<ObjCTypeParamDecl *>();
676 }
677
678 const_iterator end() const {
679 return begin() + size();
680 }
681
682 ObjCTypeParamDecl *front() const {
683 assert(size() > 0 && "empty Objective-C type parameter list");
684 return *begin();
685 }
686
687 ObjCTypeParamDecl *back() const {
688 assert(size() > 0 && "empty Objective-C type parameter list");
689 return *(end() - 1);
690 }
691
692 SourceLocation getLAngleLoc() const {
693 return SourceLocation::getFromRawEncoding(Brackets.Begin);
694 }
695
696 SourceLocation getRAngleLoc() const {
697 return SourceLocation::getFromRawEncoding(Brackets.End);
698 }
699
700 SourceRange getSourceRange() const {
701 return SourceRange(getLAngleLoc(), getRAngleLoc());
702 }
703
704 /// Gather the default set of type arguments to be substituted for
705 /// these type parameters when dealing with an unspecialized type.
706 void gatherDefaultTypeArgs(SmallVectorImpl<QualType> &typeArgs) const;
707};
708
709enum class ObjCPropertyQueryKind : uint8_t {
710 OBJC_PR_query_unknown = 0x00,
711 OBJC_PR_query_instance,
712 OBJC_PR_query_class
713};
714
715/// Represents one property declaration in an Objective-C interface.
716///
717/// For example:
718/// \code{.mm}
719/// \@property (assign, readwrite) int MyProperty;
720/// \endcode
721class ObjCPropertyDecl : public NamedDecl {
722 void anchor() override;
723
724public:
725 enum PropertyAttributeKind {
726 OBJC_PR_noattr = 0x00,
727 OBJC_PR_readonly = 0x01,
728 OBJC_PR_getter = 0x02,
729 OBJC_PR_assign = 0x04,
730 OBJC_PR_readwrite = 0x08,
731 OBJC_PR_retain = 0x10,
732 OBJC_PR_copy = 0x20,
733 OBJC_PR_nonatomic = 0x40,
734 OBJC_PR_setter = 0x80,
735 OBJC_PR_atomic = 0x100,
736 OBJC_PR_weak = 0x200,
737 OBJC_PR_strong = 0x400,
738 OBJC_PR_unsafe_unretained = 0x800,
739 /// Indicates that the nullability of the type was spelled with a
740 /// property attribute rather than a type qualifier.
741 OBJC_PR_nullability = 0x1000,
742 OBJC_PR_null_resettable = 0x2000,
743 OBJC_PR_class = 0x4000
744 // Adding a property should change NumPropertyAttrsBits
745 };
746
747 enum {
748 /// Number of bits fitting all the property attributes.
749 NumPropertyAttrsBits = 15
750 };
751
752 enum SetterKind { Assign, Retain, Copy, Weak };
753 enum PropertyControl { None, Required, Optional };
754
755private:
756 // location of \@property
757 SourceLocation AtLoc;
758
759 // location of '(' starting attribute list or null.
760 SourceLocation LParenLoc;
761
762 QualType DeclType;
763 TypeSourceInfo *DeclTypeSourceInfo;
764 unsigned PropertyAttributes : NumPropertyAttrsBits;
765 unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
766
767 // \@required/\@optional
768 unsigned PropertyImplementation : 2;
769
770 // getter name of NULL if no getter
771 Selector GetterName;
772
773 // setter name of NULL if no setter
774 Selector SetterName;
775
776 // location of the getter attribute's value
777 SourceLocation GetterNameLoc;
778
779 // location of the setter attribute's value
780 SourceLocation SetterNameLoc;
781
782 // Declaration of getter instance method
783 ObjCMethodDecl *GetterMethodDecl = nullptr;
784
785 // Declaration of setter instance method
786 ObjCMethodDecl *SetterMethodDecl = nullptr;
787
788 // Synthesize ivar for this property
789 ObjCIvarDecl *PropertyIvarDecl = nullptr;
790
791 ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
792 SourceLocation AtLocation, SourceLocation LParenLocation,
793 QualType T, TypeSourceInfo *TSI,
794 PropertyControl propControl)
795 : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
796 LParenLoc(LParenLocation), DeclType(T), DeclTypeSourceInfo(TSI),
797 PropertyAttributes(OBJC_PR_noattr),
798 PropertyAttributesAsWritten(OBJC_PR_noattr),
799 PropertyImplementation(propControl), GetterName(Selector()),
800 SetterName(Selector()) {}
801
802public:
803 static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
804 SourceLocation L,
805 IdentifierInfo *Id, SourceLocation AtLocation,
806 SourceLocation LParenLocation,
807 QualType T,
808 TypeSourceInfo *TSI,
809 PropertyControl propControl = None);
810
811 static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
812
813 SourceLocation getAtLoc() const { return AtLoc; }
814 void setAtLoc(SourceLocation L) { AtLoc = L; }
815
816 SourceLocation getLParenLoc() const { return LParenLoc; }
817 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
818
819 TypeSourceInfo *getTypeSourceInfo() const { return DeclTypeSourceInfo; }
820
821 QualType getType() const { return DeclType; }
822
823 void setType(QualType T, TypeSourceInfo *TSI) {
824 DeclType = T;
825 DeclTypeSourceInfo = TSI;
826 }
827
828 /// Retrieve the type when this property is used with a specific base object
829 /// type.
830 QualType getUsageType(QualType objectType) const;
831
832 PropertyAttributeKind getPropertyAttributes() const {
833 return PropertyAttributeKind(PropertyAttributes);
834 }
835
836 void setPropertyAttributes(PropertyAttributeKind PRVal) {
837 PropertyAttributes |= PRVal;
838 }
839
840 void overwritePropertyAttributes(unsigned PRVal) {
841 PropertyAttributes = PRVal;
842 }
843
844 PropertyAttributeKind getPropertyAttributesAsWritten() const {
845 return PropertyAttributeKind(PropertyAttributesAsWritten);
846 }
847
848 void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
849 PropertyAttributesAsWritten = PRVal;
850 }
851
852 // Helper methods for accessing attributes.
853
854 /// isReadOnly - Return true iff the property has a setter.
855 bool isReadOnly() const {
856 return (PropertyAttributes & OBJC_PR_readonly);
857 }
858
859 /// isAtomic - Return true if the property is atomic.
860 bool isAtomic() const {
861 return (PropertyAttributes & OBJC_PR_atomic);
862 }
863
864 /// isRetaining - Return true if the property retains its value.
865 bool isRetaining() const {
866 return (PropertyAttributes &
867 (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
868 }
869
870 bool isInstanceProperty() const { return !isClassProperty(); }
871 bool isClassProperty() const { return PropertyAttributes & OBJC_PR_class; }
872
873 ObjCPropertyQueryKind getQueryKind() const {
874 return isClassProperty() ? ObjCPropertyQueryKind::OBJC_PR_query_class :
875 ObjCPropertyQueryKind::OBJC_PR_query_instance;
876 }
877
878 static ObjCPropertyQueryKind getQueryKind(bool isClassProperty) {
879 return isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
880 ObjCPropertyQueryKind::OBJC_PR_query_instance;
881 }
882
883 /// getSetterKind - Return the method used for doing assignment in
884 /// the property setter. This is only valid if the property has been
885 /// defined to have a setter.
886 SetterKind getSetterKind() const {
887 if (PropertyAttributes & OBJC_PR_strong)
888 return getType()->isBlockPointerType() ? Copy : Retain;
889 if (PropertyAttributes & OBJC_PR_retain)
890 return Retain;
891 if (PropertyAttributes & OBJC_PR_copy)
892 return Copy;
893 if (PropertyAttributes & OBJC_PR_weak)
894 return Weak;
895 return Assign;
896 }
897
898 Selector getGetterName() const { return GetterName; }
899 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
900
901 void setGetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
902 GetterName = Sel;
903 GetterNameLoc = Loc;
904 }
905
906 Selector getSetterName() const { return SetterName; }
907 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
908
909 void setSetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
910 SetterName = Sel;
911 SetterNameLoc = Loc;
912 }
913
914 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
915 void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
916
917 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
918 void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
919
920 // Related to \@optional/\@required declared in \@protocol
921 void setPropertyImplementation(PropertyControl pc) {
922 PropertyImplementation = pc;
923 }
924
925 PropertyControl getPropertyImplementation() const {
926 return PropertyControl(PropertyImplementation);
927 }
928
929 bool isOptional() const {
930 return getPropertyImplementation() == PropertyControl::Optional;
931 }
932
933 void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
934 PropertyIvarDecl = Ivar;
935 }
936
937 ObjCIvarDecl *getPropertyIvarDecl() const {
938 return PropertyIvarDecl;
939 }
940
941 SourceRange getSourceRange() const override LLVM_READONLY {
942 return SourceRange(AtLoc, getLocation());
943 }
944
945 /// Get the default name of the synthesized ivar.
946 IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
947
948 /// Lookup a property by name in the specified DeclContext.
949 static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
950 const IdentifierInfo *propertyID,
951 ObjCPropertyQueryKind queryKind);
952
953 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
954 static bool classofKind(Kind K) { return K == ObjCProperty; }
955};
956
957/// ObjCContainerDecl - Represents a container for method declarations.
958/// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
959/// ObjCProtocolDecl, and ObjCImplDecl.
960///
961class ObjCContainerDecl : public NamedDecl, public DeclContext {
962 // This class stores some data in DeclContext::ObjCContainerDeclBits
963 // to save some space. Use the provided accessors to access it.
964
965 // These two locations in the range mark the end of the method container.
966 // The first points to the '@' token, and the second to the 'end' token.
967 SourceRange AtEnd;
968
969 void anchor() override;
970
971public:
972 ObjCContainerDecl(Kind DK, DeclContext *DC, IdentifierInfo *Id,
973 SourceLocation nameLoc, SourceLocation atStartLoc);
974
975 // Iterator access to instance/class properties.
976 using prop_iterator = specific_decl_iterator<ObjCPropertyDecl>;
977 using prop_range =
978 llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>;
979
980 prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
981
982 prop_iterator prop_begin() const {
983 return prop_iterator(decls_begin());
984 }
985
986 prop_iterator prop_end() const {
987 return prop_iterator(decls_end());
988 }
989
990 using instprop_iterator =
991 filtered_decl_iterator<ObjCPropertyDecl,
992 &ObjCPropertyDecl::isInstanceProperty>;
993 using instprop_range = llvm::iterator_range<instprop_iterator>;
994
995 instprop_range instance_properties() const {
996 return instprop_range(instprop_begin(), instprop_end());
997 }
998
999 instprop_iterator instprop_begin() const {
1000 return instprop_iterator(decls_begin());
1001 }
1002
1003 instprop_iterator instprop_end() const {
1004 return instprop_iterator(decls_end());
1005 }
1006
1007 using classprop_iterator =
1008 filtered_decl_iterator<ObjCPropertyDecl,
1009 &ObjCPropertyDecl::isClassProperty>;
1010 using classprop_range = llvm::iterator_range<classprop_iterator>;
1011
1012 classprop_range class_properties() const {
1013 return classprop_range(classprop_begin(), classprop_end());
1014 }
1015
1016 classprop_iterator classprop_begin() const {
1017 return classprop_iterator(decls_begin());
1018 }
1019
1020 classprop_iterator classprop_end() const {
1021 return classprop_iterator(decls_end());
1022 }
1023
1024 // Iterator access to instance/class methods.
1025 using method_iterator = specific_decl_iterator<ObjCMethodDecl>;
1026 using method_range =
1027 llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>;
1028
1029 method_range methods() const {
1030 return method_range(meth_begin(), meth_end());
1031 }
1032
1033 method_iterator meth_begin() const {
1034 return method_iterator(decls_begin());
1035 }
1036
1037 method_iterator meth_end() const {
1038 return method_iterator(decls_end());
1039 }
1040
1041 using instmeth_iterator =
1042 filtered_decl_iterator<ObjCMethodDecl,
1043 &ObjCMethodDecl::isInstanceMethod>;
1044 using instmeth_range = llvm::iterator_range<instmeth_iterator>;
1045
1046 instmeth_range instance_methods() const {
1047 return instmeth_range(instmeth_begin(), instmeth_end());
1048 }
1049
1050 instmeth_iterator instmeth_begin() const {
1051 return instmeth_iterator(decls_begin());
1052 }
1053
1054 instmeth_iterator instmeth_end() const {
1055 return instmeth_iterator(decls_end());
1056 }
1057
1058 using classmeth_iterator =
1059 filtered_decl_iterator<ObjCMethodDecl,
1060 &ObjCMethodDecl::isClassMethod>;
1061 using classmeth_range = llvm::iterator_range<classmeth_iterator>;
1062
1063 classmeth_range class_methods() const {
1064 return classmeth_range(classmeth_begin(), classmeth_end());
1065 }
1066
1067 classmeth_iterator classmeth_begin() const {
1068 return classmeth_iterator(decls_begin());
1069 }
1070
1071 classmeth_iterator classmeth_end() const {
1072 return classmeth_iterator(decls_end());
1073 }
1074
1075 // Get the local instance/class method declared in this interface.
1076 ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
1077 bool AllowHidden = false) const;
1078
1079 ObjCMethodDecl *getInstanceMethod(Selector Sel,
1080 bool AllowHidden = false) const {
1081 return getMethod(Sel, true/*isInstance*/, AllowHidden);
1082 }
1083
1084 ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
1085 return getMethod(Sel, false/*isInstance*/, AllowHidden);
1086 }
1087
1088 bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
1089 ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
1090
1091 ObjCPropertyDecl *
1092 FindPropertyDeclaration(const IdentifierInfo *PropertyId,
1093 ObjCPropertyQueryKind QueryKind) const;
1094
1095 using PropertyMap =
1096 llvm::DenseMap<std::pair<IdentifierInfo *, unsigned/*isClassProperty*/>,
1097 ObjCPropertyDecl *>;
1098 using ProtocolPropertySet = llvm::SmallDenseSet<const ObjCProtocolDecl *, 8>;
1099 using PropertyDeclOrder = llvm::SmallVector<ObjCPropertyDecl *, 8>;
1100
1101 /// This routine collects list of properties to be implemented in the class.
1102 /// This includes, class's and its conforming protocols' properties.
1103 /// Note, the superclass's properties are not included in the list.
1104 virtual void collectPropertiesToImplement(PropertyMap &PM,
1105 PropertyDeclOrder &PO) const {}
1106
1107 SourceLocation getAtStartLoc() const { return ObjCContainerDeclBits.AtStart; }
1108
1109 void setAtStartLoc(SourceLocation Loc) {
1110 ObjCContainerDeclBits.AtStart = Loc;
1111 }
1112
1113 // Marks the end of the container.
1114 SourceRange getAtEndRange() const { return AtEnd; }
1115
1116 void setAtEndRange(SourceRange atEnd) { AtEnd = atEnd; }
1117
1118 SourceRange getSourceRange() const override LLVM_READONLY {
1119 return SourceRange(getAtStartLoc(), getAtEndRange().getEnd());
1120 }
1121
1122 // Implement isa/cast/dyncast/etc.
1123 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1124
1125 static bool classofKind(Kind K) {
1126 return K >= firstObjCContainer &&
1127 K <= lastObjCContainer;
1128 }
1129
1130 static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
1131 return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
1132 }
1133
1134 static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
1135 return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
1136 }
1137};
1138
1139/// Represents an ObjC class declaration.
1140///
1141/// For example:
1142///
1143/// \code
1144/// // MostPrimitive declares no super class (not particularly useful).
1145/// \@interface MostPrimitive
1146/// // no instance variables or methods.
1147/// \@end
1148///
1149/// // NSResponder inherits from NSObject & implements NSCoding (a protocol).
1150/// \@interface NSResponder : NSObject \<NSCoding>
1151/// { // instance variables are represented by ObjCIvarDecl.
1152/// id nextResponder; // nextResponder instance variable.
1153/// }
1154/// - (NSResponder *)nextResponder; // return a pointer to NSResponder.
1155/// - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
1156/// \@end // to an NSEvent.
1157/// \endcode
1158///
1159/// Unlike C/C++, forward class declarations are accomplished with \@class.
1160/// Unlike C/C++, \@class allows for a list of classes to be forward declared.
1161/// Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
1162/// typically inherit from NSObject (an exception is NSProxy).
1163///
1164class ObjCInterfaceDecl : public ObjCContainerDecl
1165 , public Redeclarable<ObjCInterfaceDecl> {
1166 friend class ASTContext;
1167
1168 /// TypeForDecl - This indicates the Type object that represents this
1169 /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType
1170 mutable const Type *TypeForDecl = nullptr;
1171
1172 struct DefinitionData {
1173 /// The definition of this class, for quick access from any
1174 /// declaration.
1175 ObjCInterfaceDecl *Definition = nullptr;
1176
1177 /// When non-null, this is always an ObjCObjectType.
1178 TypeSourceInfo *SuperClassTInfo = nullptr;
1179
1180 /// Protocols referenced in the \@interface declaration
1181 ObjCProtocolList ReferencedProtocols;
1182
1183 /// Protocols reference in both the \@interface and class extensions.
1184 ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
1185
1186 /// List of categories and class extensions defined for this class.
1187 ///
1188 /// Categories are stored as a linked list in the AST, since the categories
1189 /// and class extensions come long after the initial interface declaration,
1190 /// and we avoid dynamically-resized arrays in the AST wherever possible.
1191 ObjCCategoryDecl *CategoryList = nullptr;
1192
1193 /// IvarList - List of all ivars defined by this class; including class
1194 /// extensions and implementation. This list is built lazily.
1195 ObjCIvarDecl *IvarList = nullptr;
1196
1197 /// Indicates that the contents of this Objective-C class will be
1198 /// completed by the external AST source when required.
1199 mutable unsigned ExternallyCompleted : 1;
1200
1201 /// Indicates that the ivar cache does not yet include ivars
1202 /// declared in the implementation.
1203 mutable unsigned IvarListMissingImplementation : 1;
1204
1205 /// Indicates that this interface decl contains at least one initializer
1206 /// marked with the 'objc_designated_initializer' attribute.
1207 unsigned HasDesignatedInitializers : 1;
1208
1209 enum InheritedDesignatedInitializersState {
1210 /// We didn't calculate whether the designated initializers should be
1211 /// inherited or not.
1212 IDI_Unknown = 0,
1213
1214 /// Designated initializers are inherited for the super class.
1215 IDI_Inherited = 1,
1216
1217 /// The class does not inherit designated initializers.
1218 IDI_NotInherited = 2
1219 };
1220
1221 /// One of the \c InheritedDesignatedInitializersState enumeratos.
1222 mutable unsigned InheritedDesignatedInitializers : 2;
1223
1224 /// The location of the last location in this declaration, before
1225 /// the properties/methods. For example, this will be the '>', '}', or
1226 /// identifier,
1227 SourceLocation EndLoc;
1228
1229 DefinitionData()
1230 : ExternallyCompleted(false), IvarListMissingImplementation(true),
1231 HasDesignatedInitializers(false),
1232 InheritedDesignatedInitializers(IDI_Unknown) {}
1233 };
1234
1235 /// The type parameters associated with this class, if any.
1236 ObjCTypeParamList *TypeParamList = nullptr;
1237
1238 /// Contains a pointer to the data associated with this class,
1239 /// which will be NULL if this class has not yet been defined.
1240 ///
1241 /// The bit indicates when we don't need to check for out-of-date
1242 /// declarations. It will be set unless modules are enabled.
1243 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1244
1245 ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
1246 IdentifierInfo *Id, ObjCTypeParamList *typeParamList,
1247 SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
1248 bool IsInternal);
1249
1250 void anchor() override;
1251
1252 void LoadExternalDefinition() const;
1253
1254 DefinitionData &data() const {
1255 assert(Data.getPointer() && "Declaration has no definition!");
1256 return *Data.getPointer();
1257 }
1258
1259 /// Allocate the definition data for this class.
1260 void allocateDefinitionData();
1261
1262 using redeclarable_base = Redeclarable<ObjCInterfaceDecl>;
1263
1264 ObjCInterfaceDecl *getNextRedeclarationImpl() override {
1265 return getNextRedeclaration();
1266 }
1267
1268 ObjCInterfaceDecl *getPreviousDeclImpl() override {
1269 return getPreviousDecl();
1270 }
1271
1272 ObjCInterfaceDecl *getMostRecentDeclImpl() override {
1273 return getMostRecentDecl();
1274 }
1275
1276public:
1277 static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
1278 SourceLocation atLoc,
1279 IdentifierInfo *Id,
1280 ObjCTypeParamList *typeParamList,
1281 ObjCInterfaceDecl *PrevDecl,
1282 SourceLocation ClassLoc = SourceLocation(),
1283 bool isInternal = false);
1284
1285 static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
1286
1287 /// Retrieve the type parameters of this class.
1288 ///
1289 /// This function looks for a type parameter list for the given
1290 /// class; if the class has been declared (with \c \@class) but not
1291 /// defined (with \c \@interface), it will search for a declaration that
1292 /// has type parameters, skipping any declarations that do not.
1293 ObjCTypeParamList *getTypeParamList() const;
1294
1295 /// Set the type parameters of this class.
1296 ///
1297 /// This function is used by the AST importer, which must import the type
1298 /// parameters after creating their DeclContext to avoid loops.
1299 void setTypeParamList(ObjCTypeParamList *TPL);
1300
1301 /// Retrieve the type parameters written on this particular declaration of
1302 /// the class.
1303 ObjCTypeParamList *getTypeParamListAsWritten() const {
1304 return TypeParamList;
1305 }
1306
1307 SourceRange getSourceRange() const override LLVM_READONLY {
1308 if (isThisDeclarationADefinition())
1309 return ObjCContainerDecl::getSourceRange();
1310
1311 return SourceRange(getAtStartLoc(), getLocation());
1312 }
1313
1314 /// Indicate that this Objective-C class is complete, but that
1315 /// the external AST source will be responsible for filling in its contents
1316 /// when a complete class is required.
1317 void setExternallyCompleted();
1318
1319 /// Indicate that this interface decl contains at least one initializer
1320 /// marked with the 'objc_designated_initializer' attribute.
1321 void setHasDesignatedInitializers();
1322
1323 /// Returns true if this interface decl contains at least one initializer
1324 /// marked with the 'objc_designated_initializer' attribute.
1325 bool hasDesignatedInitializers() const;
1326
1327 /// Returns true if this interface decl declares a designated initializer
1328 /// or it inherites one from its super class.
1329 bool declaresOrInheritsDesignatedInitializers() const {
1330 return hasDesignatedInitializers() || inheritsDesignatedInitializers();
1331 }
1332
1333 const ObjCProtocolList &getReferencedProtocols() const {
1334 assert(hasDefinition() && "Caller did not check for forward reference!");
1335 if (data().ExternallyCompleted)
1336 LoadExternalDefinition();
1337
1338 return data().ReferencedProtocols;
1339 }
1340
1341 ObjCImplementationDecl *getImplementation() const;
1342 void setImplementation(ObjCImplementationDecl *ImplD);
1343
1344 ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
1345
1346 // Get the local instance/class method declared in a category.
1347 ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
1348 ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
1349
1350 ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
1351 return isInstance ? getCategoryInstanceMethod(Sel)
1352 : getCategoryClassMethod(Sel);
1353 }
1354
1355 using protocol_iterator = ObjCProtocolList::iterator;
1356 using protocol_range = llvm::iterator_range<protocol_iterator>;
1357
1358 protocol_range protocols() const {
1359 return protocol_range(protocol_begin(), protocol_end());
1360 }
1361
1362 protocol_iterator protocol_begin() const {
1363 // FIXME: Should make sure no callers ever do this.
1364 if (!hasDefinition())
1365 return protocol_iterator();
1366
1367 if (data().ExternallyCompleted)
1368 LoadExternalDefinition();
1369
1370 return data().ReferencedProtocols.begin();
1371 }
1372
1373 protocol_iterator protocol_end() const {
1374 // FIXME: Should make sure no callers ever do this.
1375 if (!hasDefinition())
1376 return protocol_iterator();
1377
1378 if (data().ExternallyCompleted)
1379 LoadExternalDefinition();
1380
1381 return data().ReferencedProtocols.end();
1382 }
1383
1384 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
1385 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
1386
1387 protocol_loc_range protocol_locs() const {
1388 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1389 }
1390
1391 protocol_loc_iterator protocol_loc_begin() const {
1392 // FIXME: Should make sure no callers ever do this.
1393 if (!hasDefinition())
1394 return protocol_loc_iterator();
1395
1396 if (data().ExternallyCompleted)
1397 LoadExternalDefinition();
1398
1399 return data().ReferencedProtocols.loc_begin();
1400 }
1401
1402 protocol_loc_iterator protocol_loc_end() const {
1403 // FIXME: Should make sure no callers ever do this.
1404 if (!hasDefinition())
1405 return protocol_loc_iterator();
1406
1407 if (data().ExternallyCompleted)
1408 LoadExternalDefinition();
1409
1410 return data().ReferencedProtocols.loc_end();
1411 }
1412
1413 using all_protocol_iterator = ObjCList<ObjCProtocolDecl>::iterator;
1414 using all_protocol_range = llvm::iterator_range<all_protocol_iterator>;
1415
1416 all_protocol_range all_referenced_protocols() const {
1417 return all_protocol_range(all_referenced_protocol_begin(),
1418 all_referenced_protocol_end());
1419 }
1420
1421 all_protocol_iterator all_referenced_protocol_begin() const {
1422 // FIXME: Should make sure no callers ever do this.
1423 if (!hasDefinition())
1424 return all_protocol_iterator();
1425
1426 if (data().ExternallyCompleted)
1427 LoadExternalDefinition();
1428
1429 return data().AllReferencedProtocols.empty()
1430 ? protocol_begin()
1431 : data().AllReferencedProtocols.begin();
1432 }
1433
1434 all_protocol_iterator all_referenced_protocol_end() const {
1435 // FIXME: Should make sure no callers ever do this.
1436 if (!hasDefinition())
1437 return all_protocol_iterator();
1438
1439 if (data().ExternallyCompleted)
1440 LoadExternalDefinition();
1441
1442 return data().AllReferencedProtocols.empty()
1443 ? protocol_end()
1444 : data().AllReferencedProtocols.end();
1445 }
1446
1447 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
1448 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
1449
1450 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
1451
1452 ivar_iterator ivar_begin() const {
1453 if (const ObjCInterfaceDecl *Def = getDefinition())
1454 return ivar_iterator(Def->decls_begin());
1455
1456 // FIXME: Should make sure no callers ever do this.
1457 return ivar_iterator();
1458 }
1459
1460 ivar_iterator ivar_end() const {
1461 if (const ObjCInterfaceDecl *Def = getDefinition())
1462 return ivar_iterator(Def->decls_end());
1463
1464 // FIXME: Should make sure no callers ever do this.
1465 return ivar_iterator();
1466 }
1467
1468 unsigned ivar_size() const {
1469 return std::distance(ivar_begin(), ivar_end());
1470 }
1471
1472 bool ivar_empty() const { return ivar_begin() == ivar_end(); }
1473
1474 ObjCIvarDecl *all_declared_ivar_begin();
1475 const ObjCIvarDecl *all_declared_ivar_begin() const {
1476 // Even though this modifies IvarList, it's conceptually const:
1477 // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
1478 return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
1479 }
1480 void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
1481
1482 /// setProtocolList - Set the list of protocols that this interface
1483 /// implements.
1484 void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
1485 const SourceLocation *Locs, ASTContext &C) {
1486 data().ReferencedProtocols.set(List, Num, Locs, C);
1487 }
1488
1489 /// mergeClassExtensionProtocolList - Merge class extension's protocol list
1490 /// into the protocol list for this class.
1491 void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
1492 unsigned Num,
1493 ASTContext &C);
1494
1495 /// Produce a name to be used for class's metadata. It comes either via
1496 /// objc_runtime_name attribute or class name.
1497 StringRef getObjCRuntimeNameAsString() const;
1498
1499 /// Returns the designated initializers for the interface.
1500 ///
1501 /// If this declaration does not have methods marked as designated
1502 /// initializers then the interface inherits the designated initializers of
1503 /// its super class.
1504 void getDesignatedInitializers(
1505 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
1506
1507 /// Returns true if the given selector is a designated initializer for the
1508 /// interface.
1509 ///
1510 /// If this declaration does not have methods marked as designated
1511 /// initializers then the interface inherits the designated initializers of
1512 /// its super class.
1513 ///
1514 /// \param InitMethod if non-null and the function returns true, it receives
1515 /// the method that was marked as a designated initializer.
1516 bool
1517 isDesignatedInitializer(Selector Sel,
1518 const ObjCMethodDecl **InitMethod = nullptr) const;
1519
1520 /// Determine whether this particular declaration of this class is
1521 /// actually also a definition.
1522 bool isThisDeclarationADefinition() const {
1523 return getDefinition() == this;
1524 }
1525
1526 /// Determine whether this class has been defined.
1527 bool hasDefinition() const {
1528 // If the name of this class is out-of-date, bring it up-to-date, which
1529 // might bring in a definition.
1530 // Note: a null value indicates that we don't have a definition and that
1531 // modules are enabled.
1532 if (!Data.getOpaqueValue())
1533 getMostRecentDecl();
1534
1535 return Data.getPointer();
1536 }
1537
1538 /// Retrieve the definition of this class, or NULL if this class
1539 /// has been forward-declared (with \@class) but not yet defined (with
1540 /// \@interface).
1541 ObjCInterfaceDecl *getDefinition() {
1542 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1543 }
1544
1545 /// Retrieve the definition of this class, or NULL if this class
1546 /// has been forward-declared (with \@class) but not yet defined (with
1547 /// \@interface).
1548 const ObjCInterfaceDecl *getDefinition() const {
1549 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1550 }
1551
1552 /// Starts the definition of this Objective-C class, taking it from
1553 /// a forward declaration (\@class) to a definition (\@interface).
1554 void startDefinition();
1555
1556 /// Retrieve the superclass type.
1557 const ObjCObjectType *getSuperClassType() const {
1558 if (TypeSourceInfo *TInfo = getSuperClassTInfo())
1559 return TInfo->getType()->castAs<ObjCObjectType>();
1560
1561 return nullptr;
1562 }
1563
1564 // Retrieve the type source information for the superclass.
1565 TypeSourceInfo *getSuperClassTInfo() const {
1566 // FIXME: Should make sure no callers ever do this.
1567 if (!hasDefinition())
1568 return nullptr;
1569
1570 if (data().ExternallyCompleted)
1571 LoadExternalDefinition();
1572
1573 return data().SuperClassTInfo;
1574 }
1575
1576 // Retrieve the declaration for the superclass of this class, which
1577 // does not include any type arguments that apply to the superclass.
1578 ObjCInterfaceDecl *getSuperClass() const;
1579
1580 void setSuperClass(TypeSourceInfo *superClass) {
1581 data().SuperClassTInfo = superClass;
1582 }
1583
1584 /// Iterator that walks over the list of categories, filtering out
1585 /// those that do not meet specific criteria.
1586 ///
1587 /// This class template is used for the various permutations of category
1588 /// and extension iterators.
1589 template<bool (*Filter)(ObjCCategoryDecl *)>
1590 class filtered_category_iterator {
1591 ObjCCategoryDecl *Current = nullptr;
1592
1593 void findAcceptableCategory();
1594
1595 public:
1596 using value_type = ObjCCategoryDecl *;
1597 using reference = value_type;
1598 using pointer = value_type;
1599 using difference_type = std::ptrdiff_t;
1600 using iterator_category = std::input_iterator_tag;
1601
1602 filtered_category_iterator() = default;
1603 explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1604 : Current(Current) {
1605 findAcceptableCategory();
1606 }
1607
1608 reference operator*() const { return Current; }
1609 pointer operator->() const { return Current; }
1610
1611 filtered_category_iterator &operator++();
1612
1613 filtered_category_iterator operator++(int) {
1614 filtered_category_iterator Tmp = *this;
1615 ++(*this);
1616 return Tmp;
1617 }
1618
1619 friend bool operator==(filtered_category_iterator X,
1620 filtered_category_iterator Y) {
1621 return X.Current == Y.Current;
1622 }
1623
1624 friend bool operator!=(filtered_category_iterator X,
1625 filtered_category_iterator Y) {
1626 return X.Current != Y.Current;
1627 }
1628 };
1629
1630private:
1631 /// Test whether the given category is visible.
1632 ///
1633 /// Used in the \c visible_categories_iterator.
1634 static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1635
1636public:
1637 /// Iterator that walks over the list of categories and extensions
1638 /// that are visible, i.e., not hidden in a non-imported submodule.
1639 using visible_categories_iterator =
1640 filtered_category_iterator<isVisibleCategory>;
1641
1642 using visible_categories_range =
1643 llvm::iterator_range<visible_categories_iterator>;
1644
1645 visible_categories_range visible_categories() const {
1646 return visible_categories_range(visible_categories_begin(),
1647 visible_categories_end());
1648 }
1649
1650 /// Retrieve an iterator to the beginning of the visible-categories
1651 /// list.
1652 visible_categories_iterator visible_categories_begin() const {
1653 return visible_categories_iterator(getCategoryListRaw());
1654 }
1655
1656 /// Retrieve an iterator to the end of the visible-categories list.
1657 visible_categories_iterator visible_categories_end() const {
1658 return visible_categories_iterator();
1659 }
1660
1661 /// Determine whether the visible-categories list is empty.
1662 bool visible_categories_empty() const {
1663 return visible_categories_begin() == visible_categories_end();
1664 }
1665
1666private:
1667 /// Test whether the given category... is a category.
1668 ///
1669 /// Used in the \c known_categories_iterator.
1670 static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1671
1672public:
1673 /// Iterator that walks over all of the known categories and
1674 /// extensions, including those that are hidden.
1675 using known_categories_iterator = filtered_category_iterator<isKnownCategory>;
1676 using known_categories_range =
1677 llvm::iterator_range<known_categories_iterator>;
1678
1679 known_categories_range known_categories() const {
1680 return known_categories_range(known_categories_begin(),
1681 known_categories_end());
1682 }
1683
1684 /// Retrieve an iterator to the beginning of the known-categories
1685 /// list.
1686 known_categories_iterator known_categories_begin() const {
1687 return known_categories_iterator(getCategoryListRaw());
1688 }
1689
1690 /// Retrieve an iterator to the end of the known-categories list.
1691 known_categories_iterator known_categories_end() const {
1692 return known_categories_iterator();
1693 }
1694
1695 /// Determine whether the known-categories list is empty.
1696 bool known_categories_empty() const {
1697 return known_categories_begin() == known_categories_end();
1698 }
1699
1700private:
1701 /// Test whether the given category is a visible extension.
1702 ///
1703 /// Used in the \c visible_extensions_iterator.
1704 static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1705
1706public:
1707 /// Iterator that walks over all of the visible extensions, skipping
1708 /// any that are known but hidden.
1709 using visible_extensions_iterator =
1710 filtered_category_iterator<isVisibleExtension>;
1711
1712 using visible_extensions_range =
1713 llvm::iterator_range<visible_extensions_iterator>;
1714
1715 visible_extensions_range visible_extensions() const {
1716 return visible_extensions_range(visible_extensions_begin(),
1717 visible_extensions_end());
1718 }
1719
1720 /// Retrieve an iterator to the beginning of the visible-extensions
1721 /// list.
1722 visible_extensions_iterator visible_extensions_begin() const {
1723 return visible_extensions_iterator(getCategoryListRaw());
1724 }
1725
1726 /// Retrieve an iterator to the end of the visible-extensions list.
1727 visible_extensions_iterator visible_extensions_end() const {
1728 return visible_extensions_iterator();
1729 }
1730
1731 /// Determine whether the visible-extensions list is empty.
1732 bool visible_extensions_empty() const {
1733 return visible_extensions_begin() == visible_extensions_end();
1734 }
1735
1736private:
1737 /// Test whether the given category is an extension.
1738 ///
1739 /// Used in the \c known_extensions_iterator.
1740 static bool isKnownExtension(ObjCCategoryDecl *Cat);
1741
1742public:
1743 friend class ASTDeclReader;
1744 friend class ASTDeclWriter;
1745 friend class ASTReader;
1746
1747 /// Iterator that walks over all of the known extensions.
1748 using known_extensions_iterator =
1749 filtered_category_iterator<isKnownExtension>;
1750 using known_extensions_range =
1751 llvm::iterator_range<known_extensions_iterator>;
1752
1753 known_extensions_range known_extensions() const {
1754 return known_extensions_range(known_extensions_begin(),
1755 known_extensions_end());
1756 }
1757
1758 /// Retrieve an iterator to the beginning of the known-extensions
1759 /// list.
1760 known_extensions_iterator known_extensions_begin() const {
1761 return known_extensions_iterator(getCategoryListRaw());
1762 }
1763
1764 /// Retrieve an iterator to the end of the known-extensions list.
1765 known_extensions_iterator known_extensions_end() const {
1766 return known_extensions_iterator();
1767 }
1768
1769 /// Determine whether the known-extensions list is empty.
1770 bool known_extensions_empty() const {
1771 return known_extensions_begin() == known_extensions_end();
1772 }
1773
1774 /// Retrieve the raw pointer to the start of the category/extension
1775 /// list.
1776 ObjCCategoryDecl* getCategoryListRaw() const {
1777 // FIXME: Should make sure no callers ever do this.
1778 if (!hasDefinition())
1779 return nullptr;
1780
1781 if (data().ExternallyCompleted)
1782 LoadExternalDefinition();
1783
1784 return data().CategoryList;
1785 }
1786
1787 /// Set the raw pointer to the start of the category/extension
1788 /// list.
1789 void setCategoryListRaw(ObjCCategoryDecl *category) {
1790 data().CategoryList = category;
1791 }
1792
1793 ObjCPropertyDecl
1794 *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId,
1795 ObjCPropertyQueryKind QueryKind) const;
1796
1797 void collectPropertiesToImplement(PropertyMap &PM,
1798 PropertyDeclOrder &PO) const override;
1799
1800 /// isSuperClassOf - Return true if this class is the specified class or is a
1801 /// super class of the specified interface class.
1802 bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1803 // If RHS is derived from LHS it is OK; else it is not OK.
1804 while (I != nullptr) {
1805 if (declaresSameEntity(this, I))
1806 return true;
1807
1808 I = I->getSuperClass();
1809 }
1810 return false;
1811 }
1812
1813 /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1814 /// to be incompatible with __weak references. Returns true if it is.
1815 bool isArcWeakrefUnavailable() const;
1816
1817 /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1818 /// classes must not be auto-synthesized. Returns class decl. if it must not
1819 /// be; 0, otherwise.
1820 const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1821
1822 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1823 ObjCInterfaceDecl *&ClassDeclared);
1824 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1825 ObjCInterfaceDecl *ClassDeclared;
1826 return lookupInstanceVariable(IVarName, ClassDeclared);
1827 }
1828
1829 ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1830
1831 // Lookup a method. First, we search locally. If a method isn't
1832 // found, we search referenced protocols and class categories.
1833 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1834 bool shallowCategoryLookup = false,
1835 bool followSuper = true,
1836 const ObjCCategoryDecl *C = nullptr) const;
1837
1838 /// Lookup an instance method for a given selector.
1839 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1840 return lookupMethod(Sel, true/*isInstance*/);
1841 }
1842
1843 /// Lookup a class method for a given selector.
1844 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1845 return lookupMethod(Sel, false/*isInstance*/);
1846 }
1847
1848 ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1849
1850 /// Lookup a method in the classes implementation hierarchy.
1851 ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1852 bool Instance=true) const;
1853
1854 ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1855 return lookupPrivateMethod(Sel, false);
1856 }
1857
1858 /// Lookup a setter or getter in the class hierarchy,
1859 /// including in all categories except for category passed
1860 /// as argument.
1861 ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1862 const ObjCCategoryDecl *Cat,
1863 bool IsClassProperty) const {
1864 return lookupMethod(Sel, !IsClassProperty/*isInstance*/,
1865 false/*shallowCategoryLookup*/,
1866 true /* followsSuper */,
1867 Cat);
1868 }
1869
1870 SourceLocation getEndOfDefinitionLoc() const {
1871 if (!hasDefinition())
1872 return getLocation();
1873
1874 return data().EndLoc;
1875 }
1876
1877 void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1878
1879 /// Retrieve the starting location of the superclass.
1880 SourceLocation getSuperClassLoc() const;
1881
1882 /// isImplicitInterfaceDecl - check that this is an implicitly declared
1883 /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1884 /// declaration without an \@interface declaration.
1885 bool isImplicitInterfaceDecl() const {
1886 return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1887 }
1888
1889 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1890 /// has been implemented in IDecl class, its super class or categories (if
1891 /// lookupCategory is true).
1892 bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1893 bool lookupCategory,
1894 bool RHSIsQualifiedID = false);
1895
1896 using redecl_range = redeclarable_base::redecl_range;
1897 using redecl_iterator = redeclarable_base::redecl_iterator;
1898
1899 using redeclarable_base::redecls_begin;
1900 using redeclarable_base::redecls_end;
1901 using redeclarable_base::redecls;
1902 using redeclarable_base::getPreviousDecl;
1903 using redeclarable_base::getMostRecentDecl;
1904 using redeclarable_base::isFirstDecl;
1905
1906 /// Retrieves the canonical declaration of this Objective-C class.
1907 ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
1908 const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1909
1910 // Low-level accessor
1911 const Type *getTypeForDecl() const { return TypeForDecl; }
1912 void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1913
1914 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1915 static bool classofKind(Kind K) { return K == ObjCInterface; }
1916
1917private:
1918 const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1919 bool inheritsDesignatedInitializers() const;
1920};
1921
1922/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1923/// instance variables are identical to C. The only exception is Objective-C
1924/// supports C++ style access control. For example:
1925///
1926/// \@interface IvarExample : NSObject
1927/// {
1928/// id defaultToProtected;
1929/// \@public:
1930/// id canBePublic; // same as C++.
1931/// \@protected:
1932/// id canBeProtected; // same as C++.
1933/// \@package:
1934/// id canBePackage; // framework visibility (not available in C++).
1935/// }
1936///
1937class ObjCIvarDecl : public FieldDecl {
1938 void anchor() override;
1939
1940public:
1941 enum AccessControl {
1942 None, Private, Protected, Public, Package
1943 };
1944
1945private:
1946 ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1947 SourceLocation IdLoc, IdentifierInfo *Id,
1948 QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1949 bool synthesized)
1950 : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1951 /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1952 DeclAccess(ac), Synthesized(synthesized) {}
1953
1954public:
1955 static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1956 SourceLocation StartLoc, SourceLocation IdLoc,
1957 IdentifierInfo *Id, QualType T,
1958 TypeSourceInfo *TInfo,
1959 AccessControl ac, Expr *BW = nullptr,
1960 bool synthesized=false);
1961
1962 static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1963
1964 /// Return the class interface that this ivar is logically contained
1965 /// in; this is either the interface where the ivar was declared, or the
1966 /// interface the ivar is conceptually a part of in the case of synthesized
1967 /// ivars.
1968 const ObjCInterfaceDecl *getContainingInterface() const;
1969
1970 ObjCIvarDecl *getNextIvar() { return NextIvar; }
1971 const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1972 void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1973
1974 void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1975
1976 AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1977
1978 AccessControl getCanonicalAccessControl() const {
1979 return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1980 }
1981
1982 void setSynthesize(bool synth) { Synthesized = synth; }
1983 bool getSynthesize() const { return Synthesized; }
1984
1985 /// Retrieve the type of this instance variable when viewed as a member of a
1986 /// specific object type.
1987 QualType getUsageType(QualType objectType) const;
1988
1989 // Implement isa/cast/dyncast/etc.
1990 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1991 static bool classofKind(Kind K) { return K == ObjCIvar; }
1992
1993private:
1994 /// NextIvar - Next Ivar in the list of ivars declared in class; class's
1995 /// extensions and class's implementation
1996 ObjCIvarDecl *NextIvar = nullptr;
1997
1998 // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
1999 unsigned DeclAccess : 3;
2000 unsigned Synthesized : 1;
2001};
2002
2003/// Represents a field declaration created by an \@defs(...).
2004class ObjCAtDefsFieldDecl : public FieldDecl {
2005 ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
2006 SourceLocation IdLoc, IdentifierInfo *Id,
2007 QualType T, Expr *BW)
2008 : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
2009 /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
2010 BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
2011
2012 void anchor() override;
2013
2014public:
2015 static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
2016 SourceLocation StartLoc,
2017 SourceLocation IdLoc, IdentifierInfo *Id,
2018 QualType T, Expr *BW);
2019
2020 static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2021
2022 // Implement isa/cast/dyncast/etc.
2023 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2024 static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
2025};
2026
2027/// Represents an Objective-C protocol declaration.
2028///
2029/// Objective-C protocols declare a pure abstract type (i.e., no instance
2030/// variables are permitted). Protocols originally drew inspiration from
2031/// C++ pure virtual functions (a C++ feature with nice semantics and lousy
2032/// syntax:-). Here is an example:
2033///
2034/// \code
2035/// \@protocol NSDraggingInfo <refproto1, refproto2>
2036/// - (NSWindow *)draggingDestinationWindow;
2037/// - (NSImage *)draggedImage;
2038/// \@end
2039/// \endcode
2040///
2041/// This says that NSDraggingInfo requires two methods and requires everything
2042/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
2043/// well.
2044///
2045/// \code
2046/// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
2047/// \@end
2048/// \endcode
2049///
2050/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
2051/// protocols are in distinct namespaces. For example, Cocoa defines both
2052/// an NSObject protocol and class (which isn't allowed in Java). As a result,
2053/// protocols are referenced using angle brackets as follows:
2054///
2055/// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
2056class ObjCProtocolDecl : public ObjCContainerDecl,
2057 public Redeclarable<ObjCProtocolDecl> {
2058 struct DefinitionData {
2059 // The declaration that defines this protocol.
2060 ObjCProtocolDecl *Definition;
2061
2062 /// Referenced protocols
2063 ObjCProtocolList ReferencedProtocols;
2064 };
2065
2066 /// Contains a pointer to the data associated with this class,
2067 /// which will be NULL if this class has not yet been defined.
2068 ///
2069 /// The bit indicates when we don't need to check for out-of-date
2070 /// declarations. It will be set unless modules are enabled.
2071 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
2072
2073 ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
2074 SourceLocation nameLoc, SourceLocation atStartLoc,
2075 ObjCProtocolDecl *PrevDecl);
2076
2077 void anchor() override;
2078
2079 DefinitionData &data() const {
2080 assert(Data.getPointer() && "Objective-C protocol has no definition!");
2081 return *Data.getPointer();
2082 }
2083
2084 void allocateDefinitionData();
2085
2086 using redeclarable_base = Redeclarable<ObjCProtocolDecl>;
2087
2088 ObjCProtocolDecl *getNextRedeclarationImpl() override {
2089 return getNextRedeclaration();
2090 }
2091
2092 ObjCProtocolDecl *getPreviousDeclImpl() override {
2093 return getPreviousDecl();
2094 }
2095
2096 ObjCProtocolDecl *getMostRecentDeclImpl() override {
2097 return getMostRecentDecl();
2098 }
2099
2100public:
2101 friend class ASTDeclReader;
2102 friend class ASTDeclWriter;
2103 friend class ASTReader;
2104
2105 static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
2106 IdentifierInfo *Id,
2107 SourceLocation nameLoc,
2108 SourceLocation atStartLoc,
2109 ObjCProtocolDecl *PrevDecl);
2110
2111 static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2112
2113 const ObjCProtocolList &getReferencedProtocols() const {
2114 assert(hasDefinition() && "No definition available!");
2115 return data().ReferencedProtocols;
2116 }
2117
2118 using protocol_iterator = ObjCProtocolList::iterator;
2119 using protocol_range = llvm::iterator_range<protocol_iterator>;
2120
2121 protocol_range protocols() const {
2122 return protocol_range(protocol_begin(), protocol_end());
2123 }
2124
2125 protocol_iterator protocol_begin() const {
2126 if (!hasDefinition())
2127 return protocol_iterator();
2128
2129 return data().ReferencedProtocols.begin();
2130 }
2131
2132 protocol_iterator protocol_end() const {
2133 if (!hasDefinition())
2134 return protocol_iterator();
2135
2136 return data().ReferencedProtocols.end();
2137 }
2138
2139 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2140 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2141
2142 protocol_loc_range protocol_locs() const {
2143 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2144 }
2145
2146 protocol_loc_iterator protocol_loc_begin() const {
2147 if (!hasDefinition())
2148 return protocol_loc_iterator();
2149
2150 return data().ReferencedProtocols.loc_begin();
2151 }
2152
2153 protocol_loc_iterator protocol_loc_end() const {
2154 if (!hasDefinition())
2155 return protocol_loc_iterator();
2156
2157 return data().ReferencedProtocols.loc_end();
2158 }
2159
2160 unsigned protocol_size() const {
2161 if (!hasDefinition())
2162 return 0;
2163
2164 return data().ReferencedProtocols.size();
2165 }
2166
2167 /// setProtocolList - Set the list of protocols that this interface
2168 /// implements.
2169 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2170 const SourceLocation *Locs, ASTContext &C) {
2171 assert(hasDefinition() && "Protocol is not defined");
2172 data().ReferencedProtocols.set(List, Num, Locs, C);
2173 }
2174
2175 ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
2176
2177 // Lookup a method. First, we search locally. If a method isn't
2178 // found, we search referenced protocols and class categories.
2179 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
2180
2181 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
2182 return lookupMethod(Sel, true/*isInstance*/);
2183 }
2184
2185 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
2186 return lookupMethod(Sel, false/*isInstance*/);
2187 }
2188
2189 /// Determine whether this protocol has a definition.
2190 bool hasDefinition() const {
2191 // If the name of this protocol is out-of-date, bring it up-to-date, which
2192 // might bring in a definition.
2193 // Note: a null value indicates that we don't have a definition and that
2194 // modules are enabled.
2195 if (!Data.getOpaqueValue())
2196 getMostRecentDecl();
2197
2198 return Data.getPointer();
2199 }
2200
2201 /// Retrieve the definition of this protocol, if any.
2202 ObjCProtocolDecl *getDefinition() {
2203 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2204 }
2205
2206 /// Retrieve the definition of this protocol, if any.
2207 const ObjCProtocolDecl *getDefinition() const {
2208 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2209 }
2210
2211 /// Determine whether this particular declaration is also the
2212 /// definition.
2213 bool isThisDeclarationADefinition() const {
2214 return getDefinition() == this;
2215 }
2216
2217 /// Starts the definition of this Objective-C protocol.
2218 void startDefinition();
2219
2220 /// Produce a name to be used for protocol's metadata. It comes either via
2221 /// objc_runtime_name attribute or protocol name.
2222 StringRef getObjCRuntimeNameAsString() const;
2223
2224 SourceRange getSourceRange() const override LLVM_READONLY {
2225 if (isThisDeclarationADefinition())
2226 return ObjCContainerDecl::getSourceRange();
2227
2228 return SourceRange(getAtStartLoc(), getLocation());
2229 }
2230
2231 using redecl_range = redeclarable_base::redecl_range;
2232 using redecl_iterator = redeclarable_base::redecl_iterator;
2233
2234 using redeclarable_base::redecls_begin;
2235 using redeclarable_base::redecls_end;
2236 using redeclarable_base::redecls;
2237 using redeclarable_base::getPreviousDecl;
2238 using redeclarable_base::getMostRecentDecl;
2239 using redeclarable_base::isFirstDecl;
2240
2241 /// Retrieves the canonical declaration of this Objective-C protocol.
2242 ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
2243 const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
2244
2245 void collectPropertiesToImplement(PropertyMap &PM,
2246 PropertyDeclOrder &PO) const override;
2247
2248 void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
2249 ProtocolPropertySet &PS,
2250 PropertyDeclOrder &PO) const;
2251
2252 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2253 static bool classofKind(Kind K) { return K == ObjCProtocol; }
2254};
2255
2256/// ObjCCategoryDecl - Represents a category declaration. A category allows
2257/// you to add methods to an existing class (without subclassing or modifying
2258/// the original class interface or implementation:-). Categories don't allow
2259/// you to add instance data. The following example adds "myMethod" to all
2260/// NSView's within a process:
2261///
2262/// \@interface NSView (MyViewMethods)
2263/// - myMethod;
2264/// \@end
2265///
2266/// Categories also allow you to split the implementation of a class across
2267/// several files (a feature more naturally supported in C++).
2268///
2269/// Categories were originally inspired by dynamic languages such as Common
2270/// Lisp and Smalltalk. More traditional class-based languages (C++, Java)
2271/// don't support this level of dynamism, which is both powerful and dangerous.
2272class ObjCCategoryDecl : public ObjCContainerDecl {
2273 /// Interface belonging to this category
2274 ObjCInterfaceDecl *ClassInterface;
2275
2276 /// The type parameters associated with this category, if any.
2277 ObjCTypeParamList *TypeParamList = nullptr;
2278
2279 /// referenced protocols in this category.
2280 ObjCProtocolList ReferencedProtocols;
2281
2282 /// Next category belonging to this class.
2283 /// FIXME: this should not be a singly-linked list. Move storage elsewhere.
2284 ObjCCategoryDecl *NextClassCategory = nullptr;
2285
2286 /// The location of the category name in this declaration.
2287 SourceLocation CategoryNameLoc;
2288
2289 /// class extension may have private ivars.
2290 SourceLocation IvarLBraceLoc;
2291 SourceLocation IvarRBraceLoc;
2292
2293 ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2294 SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
2295 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2296 ObjCTypeParamList *typeParamList,
2297 SourceLocation IvarLBraceLoc = SourceLocation(),
2298 SourceLocation IvarRBraceLoc = SourceLocation());
2299
2300 void anchor() override;
2301
2302public:
2303 friend class ASTDeclReader;
2304 friend class ASTDeclWriter;
2305
2306 static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
2307 SourceLocation AtLoc,
2308 SourceLocation ClassNameLoc,
2309 SourceLocation CategoryNameLoc,
2310 IdentifierInfo *Id,
2311 ObjCInterfaceDecl *IDecl,
2312 ObjCTypeParamList *typeParamList,
2313 SourceLocation IvarLBraceLoc=SourceLocation(),
2314 SourceLocation IvarRBraceLoc=SourceLocation());
2315 static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2316
2317 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2318 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2319
2320 /// Retrieve the type parameter list associated with this category or
2321 /// extension.
2322 ObjCTypeParamList *getTypeParamList() const { return TypeParamList; }
2323
2324 /// Set the type parameters of this category.
2325 ///
2326 /// This function is used by the AST importer, which must import the type
2327 /// parameters after creating their DeclContext to avoid loops.
2328 void setTypeParamList(ObjCTypeParamList *TPL);
2329
2330
2331 ObjCCategoryImplDecl *getImplementation() const;
2332 void setImplementation(ObjCCategoryImplDecl *ImplD);
2333
2334 /// setProtocolList - Set the list of protocols that this interface
2335 /// implements.
2336 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2337 const SourceLocation *Locs, ASTContext &C) {
2338 ReferencedProtocols.set(List, Num, Locs, C);
2339 }
2340
2341 const ObjCProtocolList &getReferencedProtocols() const {
2342 return ReferencedProtocols;
2343 }
2344
2345 using protocol_iterator = ObjCProtocolList::iterator;
2346 using protocol_range = llvm::iterator_range<protocol_iterator>;
2347
2348 protocol_range protocols() const {
2349 return protocol_range(protocol_begin(), protocol_end());
2350 }
2351
2352 protocol_iterator protocol_begin() const {
2353 return ReferencedProtocols.begin();
2354 }
2355
2356 protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
2357 unsigned protocol_size() const { return ReferencedProtocols.size(); }
2358
2359 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2360 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2361
2362 protocol_loc_range protocol_locs() const {
2363 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2364 }
2365
2366 protocol_loc_iterator protocol_loc_begin() const {
2367 return ReferencedProtocols.loc_begin();
2368 }
2369
2370 protocol_loc_iterator protocol_loc_end() const {
2371 return ReferencedProtocols.loc_end();
2372 }
2373
2374 ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
2375
2376 /// Retrieve the pointer to the next stored category (or extension),
2377 /// which may be hidden.
2378 ObjCCategoryDecl *getNextClassCategoryRaw() const {
2379 return NextClassCategory;
2380 }
2381
2382 bool IsClassExtension() const { return getIdentifier() == nullptr; }
2383
2384 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2385 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2386
2387 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2388
2389 ivar_iterator ivar_begin() const {
2390 return ivar_iterator(decls_begin());
2391 }
2392
2393 ivar_iterator ivar_end() const {
2394 return ivar_iterator(decls_end());
2395 }
2396
2397 unsigned ivar_size() const {
2398 return std::distance(ivar_begin(), ivar_end());
2399 }
2400
2401 bool ivar_empty() const {
2402 return ivar_begin() == ivar_end();
2403 }
2404
2405 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2406 void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
2407
2408 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2409 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2410 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2411 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2412
2413 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2414 static bool classofKind(Kind K) { return K == ObjCCategory; }
2415};
2416
2417class ObjCImplDecl : public ObjCContainerDecl {
2418 /// Class interface for this class/category implementation
2419 ObjCInterfaceDecl *ClassInterface;
2420
2421 void anchor() override;
2422
2423protected:
2424 ObjCImplDecl(Kind DK, DeclContext *DC,
2425 ObjCInterfaceDecl *classInterface,
2426 IdentifierInfo *Id,
2427 SourceLocation nameLoc, SourceLocation atStartLoc)
2428 : ObjCContainerDecl(DK, DC, Id, nameLoc, atStartLoc),
2429 ClassInterface(classInterface) {}
2430
2431public:
2432 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2433 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2434 void setClassInterface(ObjCInterfaceDecl *IFace);
2435
2436 void addInstanceMethod(ObjCMethodDecl *method) {
2437 // FIXME: Context should be set correctly before we get here.
2438 method->setLexicalDeclContext(this);
2439 addDecl(method);
2440 }
2441
2442 void addClassMethod(ObjCMethodDecl *method) {
2443 // FIXME: Context should be set correctly before we get here.
2444 method->setLexicalDeclContext(this);
2445 addDecl(method);
2446 }
2447
2448 void addPropertyImplementation(ObjCPropertyImplDecl *property);
2449
2450 ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId,
2451 ObjCPropertyQueryKind queryKind) const;
2452 ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
2453
2454 // Iterator access to properties.
2455 using propimpl_iterator = specific_decl_iterator<ObjCPropertyImplDecl>;
2456 using propimpl_range =
2457 llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>;
2458
2459 propimpl_range property_impls() const {
2460 return propimpl_range(propimpl_begin(), propimpl_end());
2461 }
2462
2463 propimpl_iterator propimpl_begin() const {
2464 return propimpl_iterator(decls_begin());
2465 }
2466
2467 propimpl_iterator propimpl_end() const {
2468 return propimpl_iterator(decls_end());
2469 }
2470
2471 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2472
2473 static bool classofKind(Kind K) {
2474 return K >= firstObjCImpl && K <= lastObjCImpl;
2475 }
2476};
2477
2478/// ObjCCategoryImplDecl - An object of this class encapsulates a category
2479/// \@implementation declaration. If a category class has declaration of a
2480/// property, its implementation must be specified in the category's
2481/// \@implementation declaration. Example:
2482/// \@interface I \@end
2483/// \@interface I(CATEGORY)
2484/// \@property int p1, d1;
2485/// \@end
2486/// \@implementation I(CATEGORY)
2487/// \@dynamic p1,d1;
2488/// \@end
2489///
2490/// ObjCCategoryImplDecl
2491class ObjCCategoryImplDecl : public ObjCImplDecl {
2492 // Category name location
2493 SourceLocation CategoryNameLoc;
2494
2495 ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
2496 ObjCInterfaceDecl *classInterface,
2497 SourceLocation nameLoc, SourceLocation atStartLoc,
2498 SourceLocation CategoryNameLoc)
2499 : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, Id,
2500 nameLoc, atStartLoc),
2501 CategoryNameLoc(CategoryNameLoc) {}
2502
2503 void anchor() override;
2504
2505public:
2506 friend class ASTDeclReader;
2507 friend class ASTDeclWriter;
2508
2509 static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
2510 IdentifierInfo *Id,
2511 ObjCInterfaceDecl *classInterface,
2512 SourceLocation nameLoc,
2513 SourceLocation atStartLoc,
2514 SourceLocation CategoryNameLoc);
2515 static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2516
2517 ObjCCategoryDecl *getCategoryDecl() const;
2518
2519 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2520
2521 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2522 static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
2523};
2524
2525raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
2526
2527/// ObjCImplementationDecl - Represents a class definition - this is where
2528/// method definitions are specified. For example:
2529///
2530/// @code
2531/// \@implementation MyClass
2532/// - (void)myMethod { /* do something */ }
2533/// \@end
2534/// @endcode
2535///
2536/// In a non-fragile runtime, instance variables can appear in the class
2537/// interface, class extensions (nameless categories), and in the implementation
2538/// itself, as well as being synthesized as backing storage for properties.
2539///
2540/// In a fragile runtime, instance variables are specified in the class
2541/// interface, \em not in the implementation. Nevertheless (for legacy reasons),
2542/// we allow instance variables to be specified in the implementation. When
2543/// specified, they need to be \em identical to the interface.
2544class ObjCImplementationDecl : public ObjCImplDecl {
2545 /// Implementation Class's super class.
2546 ObjCInterfaceDecl *SuperClass;
2547 SourceLocation SuperLoc;
2548
2549 /// \@implementation may have private ivars.
2550 SourceLocation IvarLBraceLoc;
2551 SourceLocation IvarRBraceLoc;
2552
2553 /// Support for ivar initialization.
2554 /// The arguments used to initialize the ivars
2555 LazyCXXCtorInitializersPtr IvarInitializers;
2556 unsigned NumIvarInitializers = 0;
2557
2558 /// Do the ivars of this class require initialization other than
2559 /// zero-initialization?
2560 bool HasNonZeroConstructors : 1;
2561
2562 /// Do the ivars of this class require non-trivial destruction?
2563 bool HasDestructors : 1;
2564
2565 ObjCImplementationDecl(DeclContext *DC,
2566 ObjCInterfaceDecl *classInterface,
2567 ObjCInterfaceDecl *superDecl,
2568 SourceLocation nameLoc, SourceLocation atStartLoc,
2569 SourceLocation superLoc = SourceLocation(),
2570 SourceLocation IvarLBraceLoc=SourceLocation(),
2571 SourceLocation IvarRBraceLoc=SourceLocation())
2572 : ObjCImplDecl(ObjCImplementation, DC, classInterface,
2573 classInterface ? classInterface->getIdentifier()
2574 : nullptr,
2575 nameLoc, atStartLoc),
2576 SuperClass(superDecl), SuperLoc(superLoc),
2577 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc),
2578 HasNonZeroConstructors(false), HasDestructors(false) {}
2579
2580 void anchor() override;
2581
2582public:
2583 friend class ASTDeclReader;
2584 friend class ASTDeclWriter;
2585
2586 static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2587 ObjCInterfaceDecl *classInterface,
2588 ObjCInterfaceDecl *superDecl,
2589 SourceLocation nameLoc,
2590 SourceLocation atStartLoc,
2591 SourceLocation superLoc = SourceLocation(),
2592 SourceLocation IvarLBraceLoc=SourceLocation(),
2593 SourceLocation IvarRBraceLoc=SourceLocation());
2594
2595 static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2596
2597 /// init_iterator - Iterates through the ivar initializer list.
2598 using init_iterator = CXXCtorInitializer **;
2599
2600 /// init_const_iterator - Iterates through the ivar initializer list.
2601 using init_const_iterator = CXXCtorInitializer * const *;
2602
2603 using init_range = llvm::iterator_range<init_iterator>;
2604 using init_const_range = llvm::iterator_range<init_const_iterator>;
2605
2606 init_range inits() { return init_range(init_begin(), init_end()); }
2607
2608 init_const_range inits() const {
2609 return init_const_range(init_begin(), init_end());
2610 }
2611
2612 /// init_begin() - Retrieve an iterator to the first initializer.
2613 init_iterator init_begin() {
2614 const auto *ConstThis = this;
2615 return const_cast<init_iterator>(ConstThis->init_begin());
2616 }
2617
2618 /// begin() - Retrieve an iterator to the first initializer.
2619 init_const_iterator init_begin() const;
2620
2621 /// init_end() - Retrieve an iterator past the last initializer.
2622 init_iterator init_end() {
2623 return init_begin() + NumIvarInitializers;
2624 }
2625
2626 /// end() - Retrieve an iterator past the last initializer.
2627 init_const_iterator init_end() const {
2628 return init_begin() + NumIvarInitializers;
2629 }
2630
2631 /// getNumArgs - Number of ivars which must be initialized.
2632 unsigned getNumIvarInitializers() const {
2633 return NumIvarInitializers;
2634 }
2635
2636 void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2637 NumIvarInitializers = numNumIvarInitializers;
2638 }
2639
2640 void setIvarInitializers(ASTContext &C,
2641 CXXCtorInitializer ** initializers,
2642 unsigned numInitializers);
2643
2644 /// Do any of the ivars of this class (not counting its base classes)
2645 /// require construction other than zero-initialization?
2646 bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
2647 void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2648
2649 /// Do any of the ivars of this class (not counting its base classes)
2650 /// require non-trivial destruction?
2651 bool hasDestructors() const { return HasDestructors; }
2652 void setHasDestructors(bool val) { HasDestructors = val; }
2653
2654 /// getIdentifier - Get the identifier that names the class
2655 /// interface associated with this implementation.
2656 IdentifierInfo *getIdentifier() const {
2657 return getClassInterface()->getIdentifier();
2658 }
2659
2660 /// getName - Get the name of identifier for the class interface associated
2661 /// with this implementation as a StringRef.
2662 //
2663 // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2664 // meaning.
2665 StringRef getName() const {
2666 assert(getIdentifier() && "Name is not a simple identifier");
2667 return getIdentifier()->getName();
2668 }
2669
2670 /// Get the name of the class associated with this interface.
2671 //
2672 // FIXME: Move to StringRef API.
2673 std::string getNameAsString() const {
2674 return getName();
2675 }
2676
2677 /// Produce a name to be used for class's metadata. It comes either via
2678 /// class's objc_runtime_name attribute or class name.
2679 StringRef getObjCRuntimeNameAsString() const;
2680
2681 const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
2682 ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
2683 SourceLocation getSuperClassLoc() const { return SuperLoc; }
2684
2685 void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2686
2687 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2688 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2689 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2690 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2691
2692 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2693 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2694
2695 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2696
2697 ivar_iterator ivar_begin() const {
2698 return ivar_iterator(decls_begin());
2699 }
2700
2701 ivar_iterator ivar_end() const {
2702 return ivar_iterator(decls_end());
2703 }
2704
2705 unsigned ivar_size() const {
2706 return std::distance(ivar_begin(), ivar_end());
2707 }
2708
2709 bool ivar_empty() const {
2710 return ivar_begin() == ivar_end();
2711 }
2712
2713 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2714 static bool classofKind(Kind K) { return K == ObjCImplementation; }
2715};
2716
2717raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2718
2719/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2720/// declared as \@compatibility_alias alias class.
2721class ObjCCompatibleAliasDecl : public NamedDecl {
2722 /// Class that this is an alias of.
2723 ObjCInterfaceDecl *AliasedClass;
2724
2725 ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2726 ObjCInterfaceDecl* aliasedClass)
2727 : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2728
2729 void anchor() override;
2730
2731public:
2732 static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2733 SourceLocation L, IdentifierInfo *Id,
2734 ObjCInterfaceDecl* aliasedClass);
2735
2736 static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2737 unsigned ID);
2738
2739 const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
2740 ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
2741 void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2742
2743 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2744 static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2745};
2746
2747/// ObjCPropertyImplDecl - Represents implementation declaration of a property
2748/// in a class or category implementation block. For example:
2749/// \@synthesize prop1 = ivar1;
2750///
2751class ObjCPropertyImplDecl : public Decl {
2752public:
2753 enum Kind {
2754 Synthesize,
2755 Dynamic
2756 };
2757
2758private:
2759 SourceLocation AtLoc; // location of \@synthesize or \@dynamic
2760
2761 /// For \@synthesize, the location of the ivar, if it was written in
2762 /// the source code.
2763 ///
2764 /// \code
2765 /// \@synthesize int a = b
2766 /// \endcode
2767 SourceLocation IvarLoc;
2768
2769 /// Property declaration being implemented
2770 ObjCPropertyDecl *PropertyDecl;
2771
2772 /// Null for \@dynamic. Required for \@synthesize.
2773 ObjCIvarDecl *PropertyIvarDecl;
2774
2775 /// Null for \@dynamic. Non-null if property must be copy-constructed in
2776 /// getter.
2777 Expr *GetterCXXConstructor = nullptr;
2778
2779 /// Null for \@dynamic. Non-null if property has assignment operator to call
2780 /// in Setter synthesis.
2781 Expr *SetterCXXAssignment = nullptr;
2782
2783 ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2784 ObjCPropertyDecl *property,
2785 Kind PK,
2786 ObjCIvarDecl *ivarDecl,
2787 SourceLocation ivarLoc)
2788 : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2789 IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl) {
2790 assert(PK == Dynamic || PropertyIvarDecl);
2791 }
2792
2793public:
2794 friend class ASTDeclReader;
2795
2796 static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2797 SourceLocation atLoc, SourceLocation L,
2798 ObjCPropertyDecl *property,
2799 Kind PK,
2800 ObjCIvarDecl *ivarDecl,
2801 SourceLocation ivarLoc);
2802
2803 static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2804
2805 SourceRange getSourceRange() const override LLVM_READONLY;
2806
2807 SourceLocation getBeginLoc() const LLVM_READONLY { return AtLoc; }
2808 void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2809
2810 ObjCPropertyDecl *getPropertyDecl() const {
2811 return PropertyDecl;
2812 }
2813 void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2814
2815 Kind getPropertyImplementation() const {
2816 return PropertyIvarDecl ? Synthesize : Dynamic;
2817 }
2818
2819 ObjCIvarDecl *getPropertyIvarDecl() const {
2820 return PropertyIvarDecl;
2821 }
2822 SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2823
2824 void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2825 SourceLocation IvarLoc) {
2826 PropertyIvarDecl = Ivar;
2827 this->IvarLoc = IvarLoc;
2828 }
2829
2830 /// For \@synthesize, returns true if an ivar name was explicitly
2831 /// specified.
2832 ///
2833 /// \code
2834 /// \@synthesize int a = b; // true
2835 /// \@synthesize int a; // false
2836 /// \endcode
2837 bool isIvarNameSpecified() const {
2838 return IvarLoc.isValid() && IvarLoc != getLocation();
2839 }
2840
2841 Expr *getGetterCXXConstructor() const {
2842 return GetterCXXConstructor;
2843 }
2844
2845 void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2846 GetterCXXConstructor = getterCXXConstructor;
2847 }
2848
2849 Expr *getSetterCXXAssignment() const {
2850 return SetterCXXAssignment;
2851 }
2852
2853 void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2854 SetterCXXAssignment = setterCXXAssignment;
2855 }
2856
2857 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2858 static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2859};
2860
2861template<bool (*Filter)(ObjCCategoryDecl *)>
2862void
2863ObjCInterfaceDecl::filtered_category_iterator<Filter>::
2864findAcceptableCategory() {
2865 while (Current && !Filter(Current))
2866 Current = Current->getNextClassCategoryRaw();
2867}
2868
2869template<bool (*Filter)(ObjCCategoryDecl *)>
2870inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2871ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2872 Current = Current->getNextClassCategoryRaw();
2873 findAcceptableCategory();
2874 return *this;
2875}
2876
2877inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2878 return !Cat->isHidden();
2879}
2880
2881inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2882 return Cat->IsClassExtension() && !Cat->isHidden();
2883}
2884
2885inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2886 return Cat->IsClassExtension();
2887}
2888
2889} // namespace clang
2890
2891#endif // LLVM_CLANG_AST_DECLOBJC_H
2892