Skip to main content

leo_ast/expressions/
literal.rs

1// Copyright (C) 2019-2026 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use crate::IntegerType;
18
19use super::*;
20
21/// A literal.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
23pub struct Literal {
24    pub span: Span,
25    pub id: NodeID,
26    pub variant: LiteralVariant,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
30pub enum LiteralVariant {
31    /// An address literal, e.g., `aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8s7pyjh9` or `hello.aleo`.
32    Address(String),
33    /// A boolean literal, either `true` or `false`.
34    Boolean(bool),
35    /// A field literal, e.g., `42field`.
36    /// A signed number followed by the keyword `field`.
37    Field(String),
38    /// A group literal, eg `42group`.
39    Group(String),
40    /// An integer literal, e.g., `42u32`.
41    Integer(IntegerType, String),
42    /// A literal `None` for optional types.
43    None,
44    /// A scalar literal, e.g. `1scalar`.
45    /// An unsigned number followed by the keyword `scalar`.
46    Scalar(String),
47    /// A signature literal, eg `sign195m229jvzr0wmnshj6f8gwplhkrkhjumgjmad553r997u7pjfgpfz4j2w0c9lp53mcqqdsmut2g3a2zuvgst85w38hv273mwjec3sqjsv9w6uglcy58gjh7x3l55z68zsf24kx7a73ctp8x8klhuw7l2p4s3aq8um5jp304js7qcnwdqj56q5r5088tyvxsgektun0rnmvtsuxpe6sj`.
48    Signature(String),
49    /// A string literal, e.g., `"foobar"`.
50    String(String),
51    /// An unsuffixed literal, e.g. `42` (without a type suffix)
52    Unsuffixed(String),
53}
54
55impl fmt::Display for LiteralVariant {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        match &self {
58            Self::Address(address) => write!(f, "{address}"),
59            Self::Boolean(boolean) => write!(f, "{boolean}"),
60            Self::Field(field) => write!(f, "{field}field"),
61            Self::Group(group) => write!(f, "{group}group"),
62            Self::Integer(type_, value) => write!(f, "{value}{type_}"),
63            Self::None => write!(f, "none"),
64            Self::Scalar(scalar) => write!(f, "{scalar}scalar"),
65            Self::Signature(signature) => write!(f, "{signature}"),
66            Self::String(string) => write!(f, "\"{string}\""),
67            Self::Unsuffixed(value) => write!(f, "{value}"),
68        }
69    }
70}
71
72impl fmt::Display for Literal {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        self.variant.fmt(f)
75    }
76}
77
78crate::simple_node_impl!(Literal);
79
80impl Literal {
81    pub fn address(s: String, span: Span, id: NodeID) -> Self {
82        Literal { variant: LiteralVariant::Address(s), span, id }
83    }
84
85    pub fn boolean(s: bool, span: Span, id: NodeID) -> Self {
86        Literal { variant: LiteralVariant::Boolean(s), span, id }
87    }
88
89    pub fn field(s: String, span: Span, id: NodeID) -> Self {
90        Literal { variant: LiteralVariant::Field(s), span, id }
91    }
92
93    pub fn group(s: String, span: Span, id: NodeID) -> Self {
94        Literal { variant: LiteralVariant::Group(s), span, id }
95    }
96
97    pub fn integer(integer_type: IntegerType, s: String, span: Span, id: NodeID) -> Self {
98        Literal { variant: LiteralVariant::Integer(integer_type, s), span, id }
99    }
100
101    pub fn none(span: Span, id: NodeID) -> Self {
102        Literal { variant: LiteralVariant::None, span, id }
103    }
104
105    pub fn scalar(s: String, span: Span, id: NodeID) -> Self {
106        Literal { variant: LiteralVariant::Scalar(s), span, id }
107    }
108
109    pub fn signature(s: String, span: Span, id: NodeID) -> Self {
110        Literal { variant: LiteralVariant::Signature(s), span, id }
111    }
112
113    pub fn string(s: String, span: Span, id: NodeID) -> Self {
114        Literal { variant: LiteralVariant::String(s), span, id }
115    }
116
117    pub fn unsuffixed(s: String, span: Span, id: NodeID) -> Self {
118        Literal { variant: LiteralVariant::Unsuffixed(s), span, id }
119    }
120
121    /// For an integer literal, parse it and cast it to a u32.
122    pub fn as_u32(&self) -> Option<u32> {
123        if let LiteralVariant::Integer(_, s) = &self.variant {
124            u32::from_str_by_radix(&s.replace("_", "")).ok()
125        } else {
126            None
127        }
128    }
129}
130
131impl From<Literal> for Expression {
132    fn from(value: Literal) -> Self {
133        Expression::Literal(value)
134    }
135}
136
137/// This trait allows to parse integer literals of any type generically.
138///
139/// The literal may optionally start with a `-` and/or `0x` or `0o` or 0b`.
140pub trait FromStrRadix: Sized {
141    fn from_str_by_radix(src: &str) -> Result<Self, std::num::ParseIntError>;
142}
143
144macro_rules! implement_from_str_radix {
145    ($($ty:ident)*) => {
146        $(
147            impl FromStrRadix for $ty {
148                fn from_str_by_radix(src: &str) -> Result<Self, std::num::ParseIntError> {
149                    if let Some(stripped) = src.strip_prefix("0x") {
150                        Self::from_str_radix(stripped, 16)
151                    } else if let Some(stripped) = src.strip_prefix("0o") {
152                        Self::from_str_radix(stripped, 8)
153                    } else if let Some(stripped) = src.strip_prefix("0b") {
154                        Self::from_str_radix(stripped, 2)
155                    } else if let Some(stripped) = src.strip_prefix("-0x") {
156                        // We have to remove the 0x prefix and put back in a - to use
157                        // std's parsing. Alternatively we could jump through
158                        // a few hoops to avoid allocating.
159                        let mut s = String::new();
160                        s.push('-');
161                        s.push_str(stripped);
162                        Self::from_str_radix(&s, 16)
163                    } else if let Some(stripped) = src.strip_prefix("-0o") {
164                        // Ditto.
165                        let mut s = String::new();
166                        s.push('-');
167                        s.push_str(stripped);
168                        Self::from_str_radix(&s, 8)
169                    } else if let Some(stripped) = src.strip_prefix("-0b") {
170                        // Ditto.
171                        let mut s = String::new();
172                        s.push('-');
173                        s.push_str(stripped);
174                        Self::from_str_radix(&s, 2)
175                    } else {
176                        Self::from_str_radix(src, 10)
177                    }
178                }
179            }
180        )*
181    };
182}
183
184implement_from_str_radix! { u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 }