1use crate::{Identifier, IntegerType, Intrinsic, Location, Mode, Node, NodeBuilder, NodeID, Path, Type};
18use leo_span::{Span, Symbol};
19
20use serde::{Deserialize, Serialize};
21use std::fmt;
22
23mod array_access;
24pub use array_access::*;
25
26mod async_;
27pub use async_::*;
28
29mod array;
30pub use array::*;
31
32mod binary;
33pub use binary::*;
34
35mod call;
36pub use call::*;
37
38mod cast;
39pub use cast::*;
40
41mod composite_init;
42pub use composite_init::*;
43
44mod dynamic_call;
45pub use dynamic_call::*;
46
47mod err;
48pub use err::*;
49
50mod member_access;
51pub use member_access::*;
52
53mod intrinsic;
54pub use intrinsic::*;
55
56mod repeat;
57pub use repeat::*;
58
59mod ternary;
60pub use ternary::*;
61
62mod tuple;
63pub use tuple::*;
64
65mod tuple_access;
66pub use tuple_access::*;
67
68mod unary;
69pub use unary::*;
70
71mod unit;
72pub use unit::*;
73
74mod literal;
75pub use literal::*;
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub enum Expression {
80 ArrayAccess(Box<ArrayAccess>),
82 Async(AsyncExpression),
84 Array(ArrayExpression),
86 Binary(Box<BinaryExpression>),
88 Intrinsic(Box<IntrinsicExpression>),
90 Call(Box<CallExpression>),
92 DynamicCall(Box<DynamicCallExpression>),
94 Cast(Box<CastExpression>),
96 Composite(CompositeExpression),
100 Err(ErrExpression),
101 Path(Path),
103 Literal(Literal),
105 MemberAccess(Box<MemberAccess>),
107 Repeat(Box<RepeatExpression>),
109 Ternary(Box<TernaryExpression>),
111 Tuple(TupleExpression),
113 TupleAccess(Box<TupleAccess>),
115 Unary(Box<UnaryExpression>),
117 Unit(UnitExpression),
119}
120
121impl Default for Expression {
122 fn default() -> Self {
123 Expression::Err(Default::default())
124 }
125}
126
127impl Node for Expression {
128 fn span(&self) -> Span {
129 use Expression::*;
130 match self {
131 ArrayAccess(n) => n.span(),
132 Array(n) => n.span(),
133 Async(n) => n.span(),
134 Binary(n) => n.span(),
135 Call(n) => n.span(),
136 DynamicCall(n) => n.span(),
137 Cast(n) => n.span(),
138 Composite(n) => n.span(),
139 Err(n) => n.span(),
140 Intrinsic(n) => n.span(),
141 Path(n) => n.span(),
142 Literal(n) => n.span(),
143 MemberAccess(n) => n.span(),
144 Repeat(n) => n.span(),
145 Ternary(n) => n.span(),
146 Tuple(n) => n.span(),
147 TupleAccess(n) => n.span(),
148 Unary(n) => n.span(),
149 Unit(n) => n.span(),
150 }
151 }
152
153 fn set_span(&mut self, span: Span) {
154 use Expression::*;
155 match self {
156 ArrayAccess(n) => n.set_span(span),
157 Array(n) => n.set_span(span),
158 Async(n) => n.set_span(span),
159 Binary(n) => n.set_span(span),
160 Call(n) => n.set_span(span),
161 DynamicCall(n) => n.set_span(span),
162 Cast(n) => n.set_span(span),
163 Composite(n) => n.set_span(span),
164 Err(n) => n.set_span(span),
165 Intrinsic(n) => n.set_span(span),
166 Path(n) => n.set_span(span),
167 Literal(n) => n.set_span(span),
168 MemberAccess(n) => n.set_span(span),
169 Repeat(n) => n.set_span(span),
170 Ternary(n) => n.set_span(span),
171 Tuple(n) => n.set_span(span),
172 TupleAccess(n) => n.set_span(span),
173 Unary(n) => n.set_span(span),
174 Unit(n) => n.set_span(span),
175 }
176 }
177
178 fn id(&self) -> NodeID {
179 use Expression::*;
180 match self {
181 Array(n) => n.id(),
182 ArrayAccess(n) => n.id(),
183 Async(n) => n.id(),
184 Binary(n) => n.id(),
185 Call(n) => n.id(),
186 DynamicCall(n) => n.id(),
187 Cast(n) => n.id(),
188 Composite(n) => n.id(),
189 Path(n) => n.id(),
190 Literal(n) => n.id(),
191 MemberAccess(n) => n.id(),
192 Repeat(n) => n.id(),
193 Err(n) => n.id(),
194 Intrinsic(n) => n.id(),
195 Ternary(n) => n.id(),
196 Tuple(n) => n.id(),
197 TupleAccess(n) => n.id(),
198 Unary(n) => n.id(),
199 Unit(n) => n.id(),
200 }
201 }
202
203 fn set_id(&mut self, id: NodeID) {
204 use Expression::*;
205 match self {
206 Array(n) => n.set_id(id),
207 ArrayAccess(n) => n.set_id(id),
208 Async(n) => n.set_id(id),
209 Binary(n) => n.set_id(id),
210 Call(n) => n.set_id(id),
211 DynamicCall(n) => n.set_id(id),
212 Cast(n) => n.set_id(id),
213 Composite(n) => n.set_id(id),
214 Path(n) => n.set_id(id),
215 Literal(n) => n.set_id(id),
216 MemberAccess(n) => n.set_id(id),
217 Repeat(n) => n.set_id(id),
218 Err(n) => n.set_id(id),
219 Intrinsic(n) => n.set_id(id),
220 Ternary(n) => n.set_id(id),
221 Tuple(n) => n.set_id(id),
222 TupleAccess(n) => n.set_id(id),
223 Unary(n) => n.set_id(id),
224 Unit(n) => n.set_id(id),
225 }
226 }
227}
228
229impl fmt::Display for Expression {
230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231 use Expression::*;
232 match &self {
233 Array(n) => n.fmt(f),
234 ArrayAccess(n) => n.fmt(f),
235 Async(n) => n.fmt(f),
236 Binary(n) => n.fmt(f),
237 Call(n) => n.fmt(f),
238 DynamicCall(n) => n.fmt(f),
239 Cast(n) => n.fmt(f),
240 Composite(n) => n.fmt(f),
241 Err(n) => n.fmt(f),
242 Intrinsic(n) => n.fmt(f),
243 Path(n) => n.fmt(f),
244 Literal(n) => n.fmt(f),
245 MemberAccess(n) => n.fmt(f),
246 Repeat(n) => n.fmt(f),
247 Ternary(n) => n.fmt(f),
248 Tuple(n) => n.fmt(f),
249 TupleAccess(n) => n.fmt(f),
250 Unary(n) => n.fmt(f),
251 Unit(n) => n.fmt(f),
252 }
253 }
254}
255
256#[derive(Clone, Copy, Eq, PartialEq)]
257pub(crate) enum Associativity {
258 Left,
259 Right,
260 None,
261}
262
263impl Expression {
264 pub(crate) fn precedence(&self) -> u32 {
265 use Expression::*;
266 match self {
267 Binary(e) => e.precedence(),
268 Cast(_) => 12,
269 Ternary(_) => 0,
270 Array(_) | ArrayAccess(_) | Async(_) | Call(_) | DynamicCall(_) | Composite(_) | Err(_) | Intrinsic(_)
271 | Path(_) | Literal(_) | MemberAccess(_) | Repeat(_) | Tuple(_) | TupleAccess(_) | Unary(_) | Unit(_) => 20,
272 }
273 }
274
275 pub(crate) fn associativity(&self) -> Associativity {
276 if let Expression::Binary(bin) = self { bin.associativity() } else { Associativity::None }
277 }
278
279 pub fn as_u32(&self) -> Option<u32> {
282 if let Expression::Literal(literal) = &self {
283 if let LiteralVariant::Integer(int_type, s, ..) = &literal.variant {
284 use crate::IntegerType::*;
285 let s = s.replace("_", "");
286
287 return match int_type {
288 U8 => u8::from_str_by_radix(&s).map(|v| v as u32).ok(),
289 U16 => u16::from_str_by_radix(&s).map(|v| v as u32).ok(),
290 U32 => u32::from_str_by_radix(&s).ok(),
291 U64 => u64::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
292 U128 => u128::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
293 I8 => i8::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
294 I16 => i16::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
295 I32 => i32::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
296 I64 => i64::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
297 I128 => i128::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
298 };
299 } else if let LiteralVariant::Unsuffixed(s) = &literal.variant {
300 let s = s.replace("_", "");
302 return u32::from_str_by_radix(&s).ok();
303 }
304 }
305 None
306 }
307
308 pub fn is_none_expr(&self) -> bool {
309 matches!(self, Expression::Literal(Literal { variant: LiteralVariant::None, .. }))
310 }
311
312 pub fn is_pure(&self, get_type: &impl Fn(NodeID) -> Type) -> bool {
314 match self {
315 Expression::Intrinsic(intr) => {
317 if let Some(intrinsic) = Intrinsic::from_symbol(intr.name, &intr.type_parameters) {
318 intrinsic.is_pure()
319 } else {
320 false
321 }
322 }
323
324 Expression::Call(..)
327 | Expression::DynamicCall(..)
328 | Expression::Err(..)
329 | Expression::Async(..)
330 | Expression::Cast(..) => false,
331
332 Expression::Binary(expr) => {
333 use BinaryOperation::*;
334 match expr.op {
335 Div | Mod | Rem | Shl | Shr => false,
337 Add | Mul | Pow => !matches!(get_type(expr.id()), Type::Integer(..)),
339 _ => expr.left.is_pure(get_type) && expr.right.is_pure(get_type),
340 }
341 }
342 Expression::Unary(expr) => {
343 use UnaryOperation::*;
344 match expr.op {
345 Abs | Inverse | SquareRoot => false,
347 Negate => !matches!(get_type(expr.id()), Type::Integer(..)),
349 _ => expr.receiver.is_pure(get_type),
350 }
351 }
352
353 Expression::Literal(..) | Expression::Path(..) | Expression::Unit(..) => true,
355
356 Expression::ArrayAccess(expr) => expr.array.is_pure(get_type) && expr.index.is_pure(get_type),
358 Expression::MemberAccess(expr) => expr.inner.is_pure(get_type),
359 Expression::Repeat(expr) => expr.expr.is_pure(get_type) && expr.count.is_pure(get_type),
360 Expression::TupleAccess(expr) => expr.tuple.is_pure(get_type),
361 Expression::Array(expr) => expr.elements.iter().all(|e| e.is_pure(get_type)),
362 Expression::Composite(expr) => {
363 expr.const_arguments.iter().all(|e| e.is_pure(get_type))
364 && expr.members.iter().all(|init| init.expression.as_ref().is_none_or(|e| e.is_pure(get_type)))
365 }
366 Expression::Ternary(expr) => {
367 expr.condition.is_pure(get_type) && expr.if_true.is_pure(get_type) && expr.if_false.is_pure(get_type)
368 }
369 Expression::Tuple(expr) => expr.elements.iter().all(|e| e.is_pure(get_type)),
370 }
371 }
372
373 #[allow(clippy::type_complexity)]
390 pub fn zero(
391 ty: &Type,
392 span: Span,
393 node_builder: &NodeBuilder,
394 composite_lookup: &dyn Fn(&Location) -> Vec<(Symbol, Type)>,
395 ) -> Option<Self> {
396 let id = node_builder.next_id();
397
398 match ty {
399 Type::Integer(IntegerType::I8) => Some(Literal::integer(IntegerType::I8, "0".to_string(), span, id).into()),
401 Type::Integer(IntegerType::I16) => {
402 Some(Literal::integer(IntegerType::I16, "0".to_string(), span, id).into())
403 }
404 Type::Integer(IntegerType::I32) => {
405 Some(Literal::integer(IntegerType::I32, "0".to_string(), span, id).into())
406 }
407 Type::Integer(IntegerType::I64) => {
408 Some(Literal::integer(IntegerType::I64, "0".to_string(), span, id).into())
409 }
410 Type::Integer(IntegerType::I128) => {
411 Some(Literal::integer(IntegerType::I128, "0".to_string(), span, id).into())
412 }
413 Type::Integer(IntegerType::U8) => Some(Literal::integer(IntegerType::U8, "0".to_string(), span, id).into()),
414 Type::Integer(IntegerType::U16) => {
415 Some(Literal::integer(IntegerType::U16, "0".to_string(), span, id).into())
416 }
417 Type::Integer(IntegerType::U32) => {
418 Some(Literal::integer(IntegerType::U32, "0".to_string(), span, id).into())
419 }
420 Type::Integer(IntegerType::U64) => {
421 Some(Literal::integer(IntegerType::U64, "0".to_string(), span, id).into())
422 }
423 Type::Integer(IntegerType::U128) => {
424 Some(Literal::integer(IntegerType::U128, "0".to_string(), span, id).into())
425 }
426
427 Type::Boolean => Some(Literal::boolean(false, span, id).into()),
429
430 Type::Address => Some(
434 Literal::address(
435 "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc".to_string(),
436 span,
437 id,
438 )
439 .into(),
440 ),
441
442 Type::Field => Some(Literal::field("0".to_string(), span, id).into()),
444 Type::Group => Some(Literal::group("0".to_string(), span, id).into()),
445 Type::Scalar => Some(Literal::scalar("0".to_string(), span, id).into()),
446
447 Type::Signature => Some(
451 Literal::signature(
452 "sign195m229jvzr0wmnshj6f8gwplhkrkhjumgjmad553r997u7pjfgpfz4j2w0c9lp53mcqqdsmut2g3a2zuvgst85w38hv273mwjec3sqjsv9w6uglcy58gjh7x3l55z68zsf24kx7a73ctp8x8klhuw7l2p4s3aq8um5jp304js7qcnwdqj56q5r5088tyvxsgektun0rnmvtsuxpe6sj".to_string(),
453 span,
454 id,
455 )
456 .into(),
457 ),
458
459 Type::Composite(composite_type) => {
461 let path = &composite_type.path;
462 let members = composite_lookup(path.expect_global_location());
463
464 let composite_members = members
465 .into_iter()
466 .map(|(symbol, member_type)| {
467 let member_id = node_builder.next_id();
468 let zero_expr = Self::zero(&member_type, span, node_builder, composite_lookup)?;
469
470 Some(CompositeFieldInitializer {
471 span,
472 id: member_id,
473 identifier: Identifier::new(symbol, node_builder.next_id()),
474 expression: Some(zero_expr),
475 })
476 })
477 .collect::<Option<Vec<_>>>()?;
478
479 Some(Expression::Composite(CompositeExpression {
480 span,
481 id,
482 path: path.clone(),
483 const_arguments: composite_type.const_arguments.clone(),
484 members: composite_members,
485 }))
486 }
487
488 Type::Array(array_type) => {
490 let element_ty = &array_type.element_type;
491
492 let element_expr = Self::zero(element_ty, span, node_builder, composite_lookup)?;
493
494 Some(Expression::Repeat(
495 RepeatExpression { span, id, expr: element_expr, count: *array_type.length.clone() }.into(),
496 ))
497 }
498
499 _ => None,
501 }
502 }
503}