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

source code of clang/include/clang/AST/DeclObjC.h