Skip to main content

solar_ast/ast/
ty.rs

1use super::{AstPath, Box, Expr, ParameterList, StateMutability, Visibility};
2use solar_interface::{Ident, Span, Spanned, Symbol, kw};
3use std::{borrow::Cow, fmt};
4
5/// A type name.
6///
7/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.typeName>
8#[derive(Debug)]
9pub struct Type<'ast> {
10    pub span: Span,
11    pub kind: TypeKind<'ast>,
12}
13
14impl Type<'_> {
15    /// Returns `true` if the type is an elementary type.
16    #[inline]
17    pub fn is_elementary(&self) -> bool {
18        self.kind.is_elementary()
19    }
20
21    /// Returns `true` if the type is a custom type.
22    #[inline]
23    pub fn is_custom(&self) -> bool {
24        self.kind.is_custom()
25    }
26
27    /// Returns `true` if the type is a function.
28    #[inline]
29    pub fn is_function(&self) -> bool {
30        matches!(self.kind, TypeKind::Function(_))
31    }
32}
33
34/// The kind of a type.
35pub enum TypeKind<'ast> {
36    /// An elementary/primitive type.
37    Elementary(ElementaryType),
38
39    /// `$element[$($size)?]`
40    Array(Box<'ast, TypeArray<'ast>>),
41    /// `function($($parameters),*) $($attributes)* $(returns ($($returns),+))?`
42    Function(Box<'ast, TypeFunction<'ast>>),
43    /// `mapping($key $($key_name)? => $value $($value_name)?)`
44    Mapping(Box<'ast, TypeMapping<'ast>>),
45
46    /// A custom type.
47    Custom(AstPath<'ast>),
48}
49
50impl fmt::Debug for TypeKind<'_> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Elementary(ty) => ty.fmt(f),
54            Self::Array(ty) => ty.fmt(f),
55            Self::Function(ty) => ty.fmt(f),
56            Self::Mapping(ty) => ty.fmt(f),
57            Self::Custom(path) => write!(f, "Custom({path:?})"),
58        }
59    }
60}
61
62impl TypeKind<'_> {
63    /// Returns `true` if the type is an elementary type.
64    ///
65    /// Note that this does not include `Custom` types.
66    pub fn is_elementary(&self) -> bool {
67        matches!(self, Self::Elementary(_))
68    }
69
70    /// Returns `true` if the type is a custom type.
71    pub fn is_custom(&self) -> bool {
72        matches!(self, Self::Custom(_))
73    }
74}
75
76/// Elementary/primitive type.
77///
78/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.elementaryTypeName>
79#[derive(Clone, Copy, PartialEq, Eq, Hash)]
80pub enum ElementaryType {
81    /// Ethereum address, 20-byte fixed-size byte array.
82    /// `address $(payable)?`
83    Address(/* payable: */ bool),
84    /// Boolean.
85    /// `bool`
86    Bool,
87    /// UTF-8 string.
88    /// `string`
89    String,
90    /// Dynamic byte array.
91    /// `bytes`
92    Bytes,
93
94    /// Signed integer. The number is the number of bytes, **not bits**.
95    /// `0 => int`
96    /// `size @ 1..=32 => int{size*8}`
97    /// `33.. => unreachable!()`
98    Int(TypeSize),
99    /// Unsigned integer. The number is the number of bytes, **not bits**.
100    /// `0 => uint`
101    /// `size @ 1..=32 => uint{size*8}`
102    /// `33.. => unreachable!()`
103    UInt(TypeSize),
104    /// Fixed-size byte array.
105    /// `size @ 1..=32 => bytes{size}`
106    /// `0 | 33.. => unreachable!()`
107    FixedBytes(TypeSize),
108}
109
110impl fmt::Debug for ElementaryType {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::Address(false) => f.write_str("Address"),
114            Self::Address(true) => f.write_str("AddressPayable"),
115            Self::Bool => f.write_str("Bool"),
116            Self::String => f.write_str("String"),
117            Self::Bytes => f.write_str("Bytes"),
118            Self::Int(size) => write!(f, "Int({})", size.bits_raw()),
119            Self::UInt(size) => write!(f, "UInt({})", size.bits_raw()),
120            Self::FixedBytes(size) => write!(f, "FixedBytes({})", size.bytes_raw()),
121        }
122    }
123}
124
125impl fmt::Display for ElementaryType {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        self.write_abi_str(f)?;
128        if let Self::Address(true) = self {
129            f.write_str(" payable")?;
130        }
131        Ok(())
132    }
133}
134
135impl ElementaryType {
136    /// Returns the Solidity ABI representation of the type as a string.
137    pub fn to_abi_str(self) -> Cow<'static, str> {
138        match self {
139            Self::Address(_) => "address".into(),
140            Self::Bool => "bool".into(),
141            Self::String => "string".into(),
142            Self::Bytes => "bytes".into(),
143            Self::Int(size) => format!("int{}", size.bits()).into(),
144            Self::UInt(size) => format!("uint{}", size.bits()).into(),
145            Self::FixedBytes(size) => format!("bytes{}", size.bytes()).into(),
146        }
147    }
148
149    /// Writes the Solidity ABI representation of the type to a formatter.
150    pub fn write_abi_str<W: fmt::Write + ?Sized>(self, f: &mut W) -> fmt::Result {
151        f.write_str(match self {
152            Self::Address(_) => "address",
153            Self::Bool => "bool",
154            Self::String => "string",
155            Self::Bytes => "bytes",
156            Self::Int(size) => return write!(f, "int{}", size.bits()),
157            Self::UInt(size) => return write!(f, "uint{}", size.bits()),
158            Self::FixedBytes(size) => return write!(f, "bytes{}", size.bytes()),
159        })
160    }
161
162    /// Returns `true` if the type is a value type.
163    ///
164    /// Reference: <https://docs.soliditylang.org/en/latest/types.html#value-types>
165    #[inline]
166    pub const fn is_value_type(self) -> bool {
167        matches!(
168            self,
169            Self::Address(_) | Self::Bool | Self::Int(..) | Self::UInt(..) | Self::FixedBytes(..)
170        )
171    }
172
173    /// Returns `true` if the type is a reference type.
174    #[inline]
175    pub const fn is_reference_type(self) -> bool {
176        matches!(self, Self::String | Self::Bytes)
177    }
178
179    /// Returns `true` if the name is a `fixedMxN` or `ufixedMxN` type name, where `M` is a
180    /// multiple of 8 in `8..=256` and `N` is in `0..=80`.
181    ///
182    /// Returns `false` for any other name, including `fixed` and `ufixed`. Like solc, these names
183    /// are keywords, but fixed-point types are not supported.
184    pub fn is_fixed_mxn(name: Symbol) -> bool {
185        if name.is_preinterned() {
186            return false;
187        }
188        let s = name.as_str();
189        let s = s.strip_prefix('u').unwrap_or(s);
190        let Some((m, n)) = s.strip_prefix("fixed").and_then(|s| s.split_once('x')) else {
191            return false;
192        };
193        // Reject leading zeros such as `fixed08x8`.
194        // Reference: <https://github.com/argotorg/solidity/blob/f401782df49be312ea4ef52a2d467cf5183b5906/liblangutil/Token.cpp#L197-L199>
195        let size = |s: &str| {
196            if s.len() > 1 && s.starts_with('0') { None } else { s.parse::<u16>().ok() }
197        };
198        size(m).and_then(TypeSize::try_new_int_bits).is_some_and(|m| m.bits_raw() != 0)
199            && size(n).is_some_and(|n| n <= 80)
200    }
201}
202
203/// Bit size of a fixed-bytes or integer type. Valid values: 0..=256.
204#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
205pub struct TypeSize(u16);
206
207impl Default for TypeSize {
208    #[inline]
209    fn default() -> Self {
210        Self::ZERO
211    }
212}
213
214impl fmt::Debug for TypeSize {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        write!(f, "TypeSize({})", self.0)
217    }
218}
219
220impl TypeSize {
221    /// The value zero. Note that this is not a valid size for a fixed-bytes type.
222    pub const ZERO: Self = Self(0);
223
224    /// The maximum bit value of a `TypeSize`.
225    pub const MAX: u16 = 256;
226
227    /// Creates a new `TypeSize` from a `u16` number of **bits**.
228    #[inline]
229    const fn new(bits: u16) -> Option<Self> {
230        if bits > Self::MAX { None } else { Some(Self(bits)) }
231    }
232
233    /// Creates a new `TypeSize` for an integer type from **bits**.
234    ///
235    /// Panics if `bits` is not a multiple of 8 or greater than 256.
236    #[inline]
237    #[track_caller]
238    pub const fn new_int_bits(bits: u16) -> Self {
239        Self::try_new_int_bits(bits).expect("invalid integer size")
240    }
241
242    /// Creates a new `TypeSize` for an integer type from **bits**.
243    ///
244    /// Returns None if `bits` is not a multiple of 8 or greater than 256.
245    #[inline]
246    pub const fn try_new_int_bits(bits: u16) -> Option<Self> {
247        if bits.is_multiple_of(8) { Self::new(bits) } else { None }
248    }
249
250    /// Creates a new `TypeSize` for an integer literal from **bits**.
251    ///
252    /// Panics if `bits` is zero or greater than 256.
253    #[inline]
254    #[track_caller]
255    pub fn new_literal_bits(bits: u16) -> Self {
256        Self::try_new_literal_bits(bits).unwrap_or_else(|| panic!("invalid literal size: {bits}"))
257    }
258
259    /// Creates a new `TypeSize` for an integer literal from **bits**.
260    ///
261    /// Returns None if `bits` is zero or greater than 256.
262    #[inline]
263    pub fn try_new_literal_bits(bits: u16) -> Option<Self> {
264        if bits == 0 { None } else { Self::new(bits) }
265    }
266
267    /// Creates a new `TypeSize` for a fixed-bytes type from **bytes**.
268    ///
269    /// Panics if `bytes` is not in the range 1..=32.
270    #[inline]
271    #[track_caller]
272    pub const fn new_fb_bytes(bytes: u8) -> Self {
273        Self::try_new_fb_bytes(bytes).expect("invalid fixed-bytes size")
274    }
275
276    /// Creates a new `TypeSize` for a fixed-bytes type from **bytes**.
277    ///
278    /// Returns None if `bytes` is not in the range 1..=32.
279    #[inline]
280    pub const fn try_new_fb_bytes(bytes: u8) -> Option<Self> {
281        if bytes == 0 {
282            return None;
283        }
284        Self::new(bytes as u16 * 8)
285    }
286
287    /// Returns the number of **bytes**, with `0` defaulting to 32.
288    #[inline]
289    pub const fn bytes(self) -> u8 {
290        if self.0 == 0 { (Self::MAX / 8) as u8 } else { self.0.div_ceil(8) as u8 }
291    }
292
293    /// Returns the number of **bytes**.
294    #[inline]
295    pub const fn bytes_raw(self) -> u8 {
296        self.0.div_ceil(8) as u8
297    }
298
299    /// Returns the number of **bits**, with `0` defaulting to `MAX`.
300    #[inline]
301    pub const fn bits(self) -> u16 {
302        if self.0 == 0 { Self::MAX } else { self.0 }
303    }
304
305    /// Returns the number of **bits**.
306    #[inline]
307    pub const fn bits_raw(self) -> u16 {
308        self.0
309    }
310
311    /// Returns the `int` symbol for the type name.
312    #[inline]
313    pub const fn int_keyword(self) -> Symbol {
314        kw::int(self.bytes_raw())
315    }
316
317    /// Returns the `uint` symbol for the type name.
318    #[inline]
319    pub const fn uint_keyword(self) -> Symbol {
320        kw::uint(self.bytes_raw())
321    }
322
323    /// Returns the `bytesN` symbol for the type name.
324    ///
325    /// # Panics
326    ///
327    /// Panics if `self` is 0.
328    #[inline]
329    #[track_caller]
330    pub const fn bytes_keyword(self) -> Symbol {
331        kw::fixed_bytes(self.bytes_raw())
332    }
333}
334
335/// An array type.
336#[derive(Debug)]
337pub struct TypeArray<'ast> {
338    pub element: Type<'ast>,
339    pub size: Option<Box<'ast, Expr<'ast>>>,
340}
341
342/// A function type name.
343///
344/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.functionTypeName>
345#[derive(Debug)]
346pub struct TypeFunction<'ast> {
347    pub parameters: ParameterList<'ast>,
348    pub visibility: Option<Spanned<Visibility>>,
349    pub state_mutability: Option<Spanned<StateMutability>>,
350    pub returns: Option<ParameterList<'ast>>,
351}
352
353impl<'ast> TypeFunction<'ast> {
354    pub fn visibility(&self) -> Option<Visibility> {
355        self.visibility.map(Spanned::into_inner)
356    }
357
358    pub fn state_mutability(&self) -> StateMutability {
359        self.state_mutability.map(Spanned::into_inner).unwrap_or(StateMutability::NonPayable)
360    }
361
362    pub fn returns(&self) -> &[crate::VariableDefinition<'ast>] {
363        self.returns.as_ref().map(|pl| &pl.vars[..]).unwrap_or(&[])
364    }
365}
366
367/// A mapping type.
368///
369/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.mappingType>
370#[derive(Debug)]
371pub struct TypeMapping<'ast> {
372    pub key: Type<'ast>,
373    pub key_name: Option<Ident>,
374    pub value: Type<'ast>,
375    pub value_name: Option<Ident>,
376}