1use alloy_primitives::{Address, U256};
2use solar_interface::{ByteSymbol, Span, Symbol, diagnostics::ErrorGuaranteed, kw};
3use std::fmt;
4
5#[derive(Clone, Copy, Debug)]
13pub struct Lit<'ast> {
14 pub span: Span,
16 pub symbol: Symbol,
22 pub kind: LitKind<'ast>,
25}
26
27impl fmt::Display for Lit<'_> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 let Self { ref kind, symbol, span: _ } = *self;
30 match kind {
31 LitKind::Str(s, ..) => write!(f, "{}\"{symbol}\"", s.prefix()),
32 LitKind::Number(_)
33 | LitKind::BigNumber(_)
34 | LitKind::Rational(..)
35 | LitKind::Err(_)
36 | LitKind::Address(_)
37 | LitKind::Bool(_) => write!(f, "{symbol}"),
38 }
39 }
40}
41
42impl Lit<'_> {
43 pub fn first_span(&self) -> Span {
45 if let LitKind::Str(kind, _, extra) = &self.kind
46 && !extra.is_empty()
47 {
48 let str_len = kind.prefix().len() + 1 + self.symbol.as_str().len() + 1;
49 return self.span.with_hi(self.span.lo() + str_len as u32);
50 }
51 self.span
52 }
53
54 pub fn literals(&self) -> impl Iterator<Item = (Span, Symbol)> + '_ {
56 let extra = if let LitKind::Str(_, _, extra) = self.kind { extra } else { &[] };
57 std::iter::once((self.first_span(), self.symbol)).chain(extra.iter().copied())
58 }
59
60 pub fn copy_without_data<'a>(&self) -> Lit<'a> {
62 if let LitKind::Str(str_kind, byte_symbol, items) = self.kind
63 && !items.is_empty()
64 {
65 return Lit {
66 span: self.span,
67 symbol: self.symbol,
68 kind: LitKind::Str(str_kind, byte_symbol, &[]),
69 };
70 }
71
72 unsafe { std::mem::transmute::<Lit<'_>, Lit<'a>>(*self) }
74 }
75}
76
77#[derive(Clone, Copy)]
79pub enum LitKind<'ast> {
80 Str(StrKind, ByteSymbol, &'ast [(Span, Symbol)]),
100 Number(U256),
102 BigNumber(LitUint),
104 Rational(LitUint, LitUint),
110 Address(Address),
112 Bool(bool),
114 Err(ErrorGuaranteed),
116}
117
118impl fmt::Debug for LitKind<'_> {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 match self {
121 Self::Str(kind, value, extra) => {
122 write!(f, "{kind:?}(")?;
123 let value = value.as_byte_str();
124 if let Ok(utf8) = std::str::from_utf8(value) {
125 write!(f, "{utf8:?}")?;
126 } else {
127 f.write_str(&alloy_primitives::hex::encode_prefixed(value))?;
128 }
129 if !extra.is_empty() {
130 write!(f, ", {extra:?}")?;
131 }
132 f.write_str(")")
133 }
134 Self::Number(value) => write!(f, "Number({value:?})"),
135 Self::BigNumber(value) => write!(f, "BigNumber({value:?})"),
136 Self::Rational(numer, denom) => write!(f, "Rational({numer:?} / {denom:?})"),
137 Self::Address(value) => write!(f, "Address({value:?})"),
138 Self::Bool(value) => write!(f, "Bool({value:?})"),
139 Self::Err(_) => write!(f, "Err"),
140 }
141 }
142}
143
144impl LitKind<'_> {
145 pub fn is_number(&self) -> bool {
147 matches!(self, Self::Number(_) | Self::BigNumber(_) | Self::Rational(..))
148 }
149
150 pub fn description(&self) -> &'static str {
152 match self {
153 Self::Str(kind, ..) => kind.description(),
154 Self::Number(_) | Self::BigNumber(_) => "number",
155 Self::Rational(..) => "rational",
156 Self::Address(_) => "address",
157 Self::Bool(_) => "boolean",
158 Self::Err(_) => "<error>",
159 }
160 }
161}
162
163#[derive(Clone, Copy, PartialEq, Eq, Hash)]
168pub struct LitUint(ByteSymbol);
169
170impl fmt::Debug for LitUint {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.write_str(&alloy_primitives::hex::encode_prefixed(self.to_be_bytes()))
173 }
174}
175
176impl LitUint {
177 pub fn from_be_bytes(bytes: &[u8]) -> Self {
179 debug_assert!(bytes.first() != Some(&0), "leading zeros: {bytes:?}");
180 Self(ByteSymbol::intern(bytes))
181 }
182
183 pub fn to_be_bytes(&self) -> &[u8] {
185 self.0.as_byte_str()
186 }
187
188 pub fn bit_len(&self) -> usize {
190 let bytes = self.to_be_bytes();
191 bytes.len() * 8 - bytes.first().map_or(0, |b| b.leading_zeros() as usize)
192 }
193}
194
195#[derive(Clone, Debug)]
197pub struct StrLit {
198 pub span: Span,
200 pub value: Symbol,
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
206pub enum StrKind {
207 Str,
209 Unicode,
211 Hex,
213}
214
215impl StrKind {
216 pub fn description(self) -> &'static str {
218 match self {
219 Self::Str => "string",
220 Self::Unicode => "unicode string",
221 Self::Hex => "hex string",
222 }
223 }
224
225 #[doc(alias = "to_str")]
227 pub fn prefix(self) -> &'static str {
228 match self {
229 Self::Str => "",
230 Self::Unicode => "unicode",
231 Self::Hex => "hex",
232 }
233 }
234
235 #[doc(alias = "to_symbol")]
237 pub fn prefix_symbol(self) -> Symbol {
238 match self {
239 Self::Str => kw::Empty,
240 Self::Unicode => kw::Unicode,
241 Self::Hex => kw::Hex,
242 }
243 }
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
248pub enum SubDenomination {
249 Ether(EtherSubDenomination),
251 Time(TimeSubDenomination),
253}
254
255impl fmt::Display for SubDenomination {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 match self {
258 Self::Ether(sub_denomination) => sub_denomination.fmt(f),
259 Self::Time(sub_denomination) => sub_denomination.fmt(f),
260 }
261 }
262}
263
264impl SubDenomination {
265 pub const fn to_str(self) -> &'static str {
267 match self {
268 Self::Ether(sub_denomination) => sub_denomination.to_str(),
269 Self::Time(sub_denomination) => sub_denomination.to_str(),
270 }
271 }
272
273 pub const fn to_symbol(self) -> Symbol {
275 match self {
276 Self::Ether(sub_denomination) => sub_denomination.to_symbol(),
277 Self::Time(sub_denomination) => sub_denomination.to_symbol(),
278 }
279 }
280
281 pub const fn value(self) -> u64 {
283 match self {
284 Self::Ether(sub_denomination) => sub_denomination.wei(),
285 Self::Time(sub_denomination) => sub_denomination.seconds(),
286 }
287 }
288}
289
290#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
292pub enum EtherSubDenomination {
293 Wei,
295 Gwei,
297 Ether,
299}
300
301impl fmt::Display for EtherSubDenomination {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 f.write_str(self.to_str())
304 }
305}
306
307impl EtherSubDenomination {
308 pub const fn to_str(self) -> &'static str {
310 match self {
311 Self::Wei => "wei",
312 Self::Gwei => "gwei",
313 Self::Ether => "ether",
314 }
315 }
316
317 pub const fn to_symbol(self) -> Symbol {
319 match self {
320 Self::Wei => kw::Wei,
321 Self::Gwei => kw::Gwei,
322 Self::Ether => kw::Ether,
323 }
324 }
325
326 pub const fn wei(self) -> u64 {
328 match self {
330 Self::Wei => 1,
331 Self::Gwei => 1_000_000_000,
332 Self::Ether => 1_000_000_000_000_000_000,
333 }
334 }
335}
336
337#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
339pub enum TimeSubDenomination {
340 Seconds,
342 Minutes,
344 Hours,
346 Days,
348 Weeks,
350 Years,
352}
353
354impl fmt::Display for TimeSubDenomination {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.write_str(self.to_str())
357 }
358}
359
360impl TimeSubDenomination {
361 pub const fn to_str(self) -> &'static str {
363 match self {
364 Self::Seconds => "seconds",
365 Self::Minutes => "minutes",
366 Self::Hours => "hours",
367 Self::Days => "days",
368 Self::Weeks => "weeks",
369 Self::Years => "years",
370 }
371 }
372
373 pub const fn to_symbol(self) -> Symbol {
375 match self {
376 Self::Seconds => kw::Seconds,
377 Self::Minutes => kw::Minutes,
378 Self::Hours => kw::Hours,
379 Self::Days => kw::Days,
380 Self::Weeks => kw::Weeks,
381 Self::Years => kw::Years,
382 }
383 }
384
385 pub const fn seconds(self) -> u64 {
387 match self {
389 Self::Seconds => 1,
390 Self::Minutes => 60,
391 Self::Hours => 3_600,
392 Self::Days => 86_400,
393 Self::Weeks => 604_800,
394 Self::Years => 31_536_000,
395 }
396 }
397}
398
399#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
401pub enum Base {
402 Binary = 2,
404 Octal = 8,
406 Decimal = 10,
408 Hexadecimal = 16,
410}
411
412impl fmt::Display for Base {
413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414 self.to_str().fmt(f)
415 }
416}
417
418impl Base {
419 pub fn to_str(self) -> &'static str {
421 match self {
422 Self::Binary => "binary",
423 Self::Octal => "octal",
424 Self::Decimal => "decimal",
425 Self::Hexadecimal => "hexadecimal",
426 }
427 }
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433 use solar_interface::{BytePos, enter};
434
435 fn bs(s: &[u8]) -> ByteSymbol {
436 ByteSymbol::intern(s)
437 }
438
439 #[test]
440 fn literal_fmt() {
441 enter(|| {
442 let lit = LitKind::Str(StrKind::Str, bs(b"hello world"), &[]);
443 assert_eq!(lit.description(), "string");
444 assert_eq!(format!("{lit:?}"), "Str(\"hello world\")");
445
446 let lit = LitKind::Str(StrKind::Str, bs(b"hello\0world"), &[]);
447 assert_eq!(lit.description(), "string");
448 assert_eq!(format!("{lit:?}"), "Str(\"hello\\0world\")");
449
450 let lit = LitKind::Str(StrKind::Str, bs(&[255u8][..]), &[]);
451 assert_eq!(lit.description(), "string");
452 assert_eq!(format!("{lit:?}"), "Str(0xff)");
453
454 let extra = [(Span::new(BytePos(69), BytePos(420)), Symbol::intern("world"))];
455 let lit = LitKind::Str(StrKind::Str, bs(b"hello world"), &extra);
456 assert_eq!(lit.description(), "string");
457 assert_eq!(format!("{lit:?}"), "Str(\"hello world\", [(Span(69..420), \"world\")])");
458 })
459 }
460}