1use super::{AstPath, Box, Expr, ParameterList, StateMutability, Visibility};
2use solar_interface::{Ident, Span, Spanned, Symbol, kw};
3use std::{borrow::Cow, fmt};
4
5#[derive(Debug)]
9pub struct Type<'ast> {
10 pub span: Span,
11 pub kind: TypeKind<'ast>,
12}
13
14impl Type<'_> {
15 #[inline]
17 pub fn is_elementary(&self) -> bool {
18 self.kind.is_elementary()
19 }
20
21 #[inline]
23 pub fn is_custom(&self) -> bool {
24 self.kind.is_custom()
25 }
26
27 #[inline]
29 pub fn is_function(&self) -> bool {
30 matches!(self.kind, TypeKind::Function(_))
31 }
32}
33
34pub enum TypeKind<'ast> {
36 Elementary(ElementaryType),
38
39 Array(Box<'ast, TypeArray<'ast>>),
41 Function(Box<'ast, TypeFunction<'ast>>),
43 Mapping(Box<'ast, TypeMapping<'ast>>),
45
46 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 pub fn is_elementary(&self) -> bool {
67 matches!(self, Self::Elementary(_))
68 }
69
70 pub fn is_custom(&self) -> bool {
72 matches!(self, Self::Custom(_))
73 }
74}
75
76#[derive(Clone, Copy, PartialEq, Eq, Hash)]
80pub enum ElementaryType {
81 Address(bool),
84 Bool,
87 String,
90 Bytes,
93
94 Int(TypeSize),
99 UInt(TypeSize),
104 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 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 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 #[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 #[inline]
175 pub const fn is_reference_type(self) -> bool {
176 matches!(self, Self::String | Self::Bytes)
177 }
178
179 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 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#[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 pub const ZERO: Self = Self(0);
223
224 pub const MAX: u16 = 256;
226
227 #[inline]
229 const fn new(bits: u16) -> Option<Self> {
230 if bits > Self::MAX { None } else { Some(Self(bits)) }
231 }
232
233 #[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 #[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 #[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 #[inline]
263 pub fn try_new_literal_bits(bits: u16) -> Option<Self> {
264 if bits == 0 { None } else { Self::new(bits) }
265 }
266
267 #[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 #[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 #[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 #[inline]
295 pub const fn bytes_raw(self) -> u8 {
296 self.0.div_ceil(8) as u8
297 }
298
299 #[inline]
301 pub const fn bits(self) -> u16 {
302 if self.0 == 0 { Self::MAX } else { self.0 }
303 }
304
305 #[inline]
307 pub const fn bits_raw(self) -> u16 {
308 self.0
309 }
310
311 #[inline]
313 pub const fn int_keyword(self) -> Symbol {
314 kw::int(self.bytes_raw())
315 }
316
317 #[inline]
319 pub const fn uint_keyword(self) -> Symbol {
320 kw::uint(self.bytes_raw())
321 }
322
323 #[inline]
329 #[track_caller]
330 pub const fn bytes_keyword(self) -> Symbol {
331 kw::fixed_bytes(self.bytes_raw())
332 }
333}
334
335#[derive(Debug)]
337pub struct TypeArray<'ast> {
338 pub element: Type<'ast>,
339 pub size: Option<Box<'ast, Expr<'ast>>>,
340}
341
342#[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#[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}