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    /// An identifier literal such as `'foo'`
45    Identifier(String),
46    /// A scalar literal, e.g. `1scalar`.
47    /// An unsigned number followed by the keyword `scalar`.
48    Scalar(String),
49    /// A signature literal, eg `sign195m229jvzr0wmnshj6f8gwplhkrkhjumgjmad553r997u7pjfgpfz4j2w0c9lp53mcqqdsmut2g3a2zuvgst85w38hv273mwjec3sqjsv9w6uglcy58gjh7x3l55z68zsf24kx7a73ctp8x8klhuw7l2p4s3aq8um5jp304js7qcnwdqj56q5r5088tyvxsgektun0rnmvtsuxpe6sj`.
50    Signature(String),
51    /// A string literal, e.g., `"foobar"`.
52    String(String),
53    /// An unsuffixed literal, e.g. `42` (without a type suffix)
54    Unsuffixed(String),
55}
56
57impl fmt::Display for LiteralVariant {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        match &self {
60            Self::Address(address) => write!(f, "{address}"),
61            Self::Boolean(boolean) => write!(f, "{boolean}"),
62            Self::Field(field) => write!(f, "{field}field"),
63            Self::Group(group) => write!(f, "{group}group"),
64            Self::Integer(type_, value) => write!(f, "{value}{type_}"),
65            Self::None => write!(f, "none"),
66            Self::Identifier(string) => write!(f, "'{string}'"),
67            Self::Scalar(scalar) => write!(f, "{scalar}scalar"),
68            Self::Signature(signature) => write!(f, "{signature}"),
69            Self::String(string) => write!(f, "\"{string}\""),
70            Self::Unsuffixed(value) => write!(f, "{value}"),
71        }
72    }
73}
74
75impl fmt::Display for Literal {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        self.variant.fmt(f)
78    }
79}
80
81crate::simple_node_impl!(Literal);
82
83impl Literal {
84    pub fn address(s: String, span: Span, id: NodeID) -> Self {
85        Literal { variant: LiteralVariant::Address(s), span, id }
86    }
87
88    pub fn boolean(s: bool, span: Span, id: NodeID) -> Self {
89        Literal { variant: LiteralVariant::Boolean(s), span, id }
90    }
91
92    pub fn field(s: String, span: Span, id: NodeID) -> Self {
93        Literal { variant: LiteralVariant::Field(s), span, id }
94    }
95
96    pub fn group(s: String, span: Span, id: NodeID) -> Self {
97        Literal { variant: LiteralVariant::Group(s), span, id }
98    }
99
100    pub fn integer(integer_type: IntegerType, s: String, span: Span, id: NodeID) -> Self {
101        Literal { variant: LiteralVariant::Integer(integer_type, s), span, id }
102    }
103
104    pub fn none(span: Span, id: NodeID) -> Self {
105        Literal { variant: LiteralVariant::None, span, id }
106    }
107
108    pub fn identifier(s: String, span: Span, id: NodeID) -> Self {
109        Literal { variant: LiteralVariant::Identifier(s), span, id }
110    }
111
112    pub fn scalar(s: String, span: Span, id: NodeID) -> Self {
113        Literal { variant: LiteralVariant::Scalar(s), span, id }
114    }
115
116    pub fn signature(s: String, span: Span, id: NodeID) -> Self {
117        Literal { variant: LiteralVariant::Signature(s), span, id }
118    }
119
120    pub fn string(s: String, span: Span, id: NodeID) -> Self {
121        Literal { variant: LiteralVariant::String(s), span, id }
122    }
123
124    pub fn unsuffixed(s: String, span: Span, id: NodeID) -> Self {
125        Literal { variant: LiteralVariant::Unsuffixed(s), span, id }
126    }
127
128    /// For an integer literal, parse it and cast it to a u32.
129    pub fn as_u32(&self) -> Option<u32> {
130        if let LiteralVariant::Integer(_, s) = &self.variant {
131            u32::from_str_by_radix(&s.replace("_", "")).ok()
132        } else {
133            None
134        }
135    }
136}
137
138impl From<Literal> for Expression {
139    fn from(value: Literal) -> Self {
140        Expression::Literal(value)
141    }
142}
143
144/// This trait allows to parse integer literals of any type generically.
145///
146/// The literal may optionally start with a `-` and/or `0x` or `0o` or 0b`.
147pub trait FromStrRadix: Sized {
148    fn from_str_by_radix(src: &str) -> Result<Self, std::num::ParseIntError>;
149}
150
151macro_rules! implement_from_str_radix {
152    ($($ty:ident)*) => {
153        $(
154            impl FromStrRadix for $ty {
155                fn from_str_by_radix(src: &str) -> Result<Self, std::num::ParseIntError> {
156                    if let Some(stripped) = src.strip_prefix("0x") {
157                        Self::from_str_radix(stripped, 16)
158                    } else if let Some(stripped) = src.strip_prefix("0o") {
159                        Self::from_str_radix(stripped, 8)
160                    } else if let Some(stripped) = src.strip_prefix("0b") {
161                        Self::from_str_radix(stripped, 2)
162                    } else if let Some(stripped) = src.strip_prefix("-0x") {
163                        // We have to remove the 0x prefix and put back in a - to use
164                        // std's parsing. Alternatively we could jump through
165                        // a few hoops to avoid allocating.
166                        let mut s = String::new();
167                        s.push('-');
168                        s.push_str(stripped);
169                        Self::from_str_radix(&s, 16)
170                    } else if let Some(stripped) = src.strip_prefix("-0o") {
171                        // Ditto.
172                        let mut s = String::new();
173                        s.push('-');
174                        s.push_str(stripped);
175                        Self::from_str_radix(&s, 8)
176                    } else if let Some(stripped) = src.strip_prefix("-0b") {
177                        // Ditto.
178                        let mut s = String::new();
179                        s.push('-');
180                        s.push_str(stripped);
181                        Self::from_str_radix(&s, 2)
182                    } else {
183                        Self::from_str_radix(src, 10)
184                    }
185                }
186            }
187        )*
188    };
189}
190
191implement_from_str_radix! { u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 }