Skip to main content

solar_ast/ast/
lit.rs

1use alloy_primitives::{Address, U256};
2use solar_interface::{ByteSymbol, Span, Symbol, diagnostics::ErrorGuaranteed, kw};
3use std::fmt;
4
5/// A literal: `hex"1234"`, `5.6 ether`.
6///
7/// Note that multiple string literals of the same kind are concatenated together to form a single
8/// `Lit` (see [`LitKind::Str`]), thus the `span` will be the span of the entire literal, and
9/// the `symbol` will be the concatenated string.
10///
11/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.literal>
12#[derive(Clone, Copy, Debug)]
13pub struct Lit<'ast> {
14    /// The concatenated span of the literal.
15    pub span: Span,
16    /// The original contents of the literal as written in the source code, excluding any quotes.
17    ///
18    /// If this is a concatenated string literal, this will contain only the **first string
19    /// literal's contents**. For all the other string literals, see the `extra` field in
20    /// [`LitKind::Str`].
21    pub symbol: Symbol,
22    /// The "semantic" representation of the literal lowered from the original tokens.
23    /// Strings are unescaped and concatenated, hexadecimal forms are eliminated, etc.
24    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    /// Returns the span of the first string literal in this literal.
44    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    /// Returns an iterator over all the literals that were concatenated to form this literal.
55    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    /// Returns a copy of this literal with any allocated data discarded.
61    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        // SAFETY: We just handled the case with data, this is a POD copy.
73        unsafe { std::mem::transmute::<Lit<'_>, Lit<'a>>(*self) }
74    }
75}
76
77/// A kind of literal.
78#[derive(Clone, Copy)]
79pub enum LitKind<'ast> {
80    /// A string, unicode string, or hex string literal. Contains the kind and the unescaped
81    /// contents of the string.
82    ///
83    /// Note that even if this is a string or unicode string literal, invalid UTF-8 sequences
84    /// are allowed, and as such this cannot be a `str` or `Symbol`.
85    ///
86    /// The `[(Span, Symbol)]` contains the extra string literals of the same kind that were
87    /// concatenated together to form this literal.
88    /// For example, `"foo" "bar"` would be parsed as:
89    /// ```ignore (illustrative-debug-format)
90    /// # #![rustfmt::skip]
91    /// Lit {
92    ///     span: 0..11,
93    ///     symbol: "foo",
94    ///     kind: Str("foobar", [(6..11, "bar")]),
95    /// }
96    /// ```
97    ///
98    /// This list is only present in the AST, and is discarded after.
99    Str(StrKind, ByteSymbol, &'ast [(Span, Symbol)]),
100    /// A decimal or hexadecimal number literal that fits in 256 bits.
101    Number(U256),
102    /// A number literal wider than 256 bits, such as `1e100`.
103    BigNumber(LitUint),
104    /// A fractional number literal, such as `0.5`, as its numerator and denominator in lowest
105    /// terms.
106    ///
107    /// Number literals whose values are integers are [`Number`](Self::Number)s or
108    /// [`BigNumber`](Self::BigNumber)s, so `1.2e3` is `Number(1200)`.
109    Rational(LitUint, LitUint),
110    /// An address literal. This is a special case of a 40 digit hexadecimal number literal.
111    Address(Address),
112    /// A boolean literal.
113    Bool(bool),
114    /// An error occurred while parsing the literal, which has been emitted.
115    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    /// Returns `true` if this is a number literal, whatever its value.
146    pub fn is_number(&self) -> bool {
147        matches!(self, Self::Number(_) | Self::BigNumber(_) | Self::Rational(..))
148    }
149
150    /// Returns the description of this literal kind.
151    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/// An unsigned integer of a number literal, interned as its big-endian bytes.
164///
165/// Number literals that fit in 256 bits are stored inline as [`U256`]s instead. Interning keeps
166/// literals small and `Copy`.
167#[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    /// Interns an integer from its big-endian bytes, without leading zeros.
178    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    /// Returns the integer's big-endian bytes, without leading zeros.
184    pub fn to_be_bytes(&self) -> &[u8] {
185        self.0.as_byte_str()
186    }
187
188    /// Returns the number of bits needed to represent the integer.
189    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/// A single UTF-8 string literal. Only used in import paths and statements, not expressions.
196#[derive(Clone, Debug)]
197pub struct StrLit {
198    /// The span of the literal.
199    pub span: Span,
200    /// The contents of the string. Not unescaped.
201    pub value: Symbol,
202}
203
204/// A string literal kind.
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
206pub enum StrKind {
207    /// A regular string literal.
208    Str,
209    /// A unicode string literal.
210    Unicode,
211    /// A hex string literal.
212    Hex,
213}
214
215impl StrKind {
216    /// Returns the description of this string kind.
217    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    /// Returns the prefix as a string. Empty if `Str`.
226    #[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    /// Returns the prefix as a symbol. Empty if `Str`.
236    #[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/// A number sub-denomination.
247#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
248pub enum SubDenomination {
249    /// An ether sub-denomination.
250    Ether(EtherSubDenomination),
251    /// A time sub-denomination.
252    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    /// Returns the name of this sub-denomination as a string.
266    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    /// Returns the symbol of this sub-denomination.
274    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    /// Returns the value of this sub-denomination.
282    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/// An ether [`SubDenomination`].
291#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
292pub enum EtherSubDenomination {
293    /// `wei`
294    Wei,
295    /// `gwei`
296    Gwei,
297    /// `ether`
298    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    /// Returns the name of this sub-denomination as a string.
309    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    /// Returns the symbol of this sub-denomination.
318    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    /// Returns the number of wei in this sub-denomination.
327    pub const fn wei(self) -> u64 {
328        // https://github.com/argotorg/solidity/blob/2a2a9d37ee69ca77ef530fe18524a3dc8b053104/libsolidity/ast/Types.cpp#L973
329        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/// A time [`SubDenomination`].
338#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
339pub enum TimeSubDenomination {
340    /// `seconds`
341    Seconds,
342    /// `minutes`
343    Minutes,
344    /// `hours`
345    Hours,
346    /// `days`
347    Days,
348    /// `weeks`
349    Weeks,
350    /// `years`
351    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    /// Returns the name of this sub-denomination as a string.
362    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    /// Returns the symbol of this sub-denomination.
374    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    /// Returns the number of seconds in this sub-denomination.
386    pub const fn seconds(self) -> u64 {
387        // https://github.com/argotorg/solidity/blob/2a2a9d37ee69ca77ef530fe18524a3dc8b053104/libsolidity/ast/Types.cpp#L973
388        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/// Base of numeric literal encoding according to its prefix.
400#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
401pub enum Base {
402    /// Literal starts with "0b".
403    Binary = 2,
404    /// Literal starts with "0o".
405    Octal = 8,
406    /// Literal doesn't contain a prefix.
407    Decimal = 10,
408    /// Literal starts with "0x".
409    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    /// Returns the name of the base as a string.
420    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}