leo_input/expressions/
expression.rs

1// Copyright (C) 2019-2021 Aleo Systems 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::{ast::Rule, expressions::*, values::Value};
18
19use pest::Span;
20use pest_ast::FromPest;
21use std::fmt;
22
23#[derive(Clone, Debug, FromPest, PartialEq)]
24#[pest_ast(rule(Rule::expression))]
25pub enum Expression<'ast> {
26    ArrayInitializer(ArrayInitializerExpression<'ast>),
27    ArrayInline(ArrayInlineExpression<'ast>),
28    StringExpression(StringExpression<'ast>),
29    Tuple(TupleExpression<'ast>),
30    Value(Value<'ast>),
31}
32
33impl<'ast> Expression<'ast> {
34    pub fn span(&self) -> &Span {
35        match self {
36            Expression::ArrayInitializer(expression) => &expression.span,
37            Expression::ArrayInline(expression) => &expression.span,
38            Expression::StringExpression(string) => &string.span,
39            Expression::Tuple(tuple) => &tuple.span,
40            Expression::Value(value) => value.span(),
41        }
42    }
43}
44
45impl<'ast> fmt::Display for Expression<'ast> {
46    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47        match *self {
48            Expression::ArrayInitializer(ref expression) => {
49                write!(f, "array [{} ; {}]", expression.expression, expression.dimensions)
50            }
51            Expression::ArrayInline(ref array) => {
52                let values = array
53                    .expressions
54                    .iter()
55                    .map(|x| x.to_string())
56                    .collect::<Vec<_>>()
57                    .join(", ");
58
59                write!(f, "array [{}]", values)
60            }
61            Expression::StringExpression(ref string) => write!(f, "{}", string),
62            Expression::Tuple(ref tuple) => {
63                let values = tuple
64                    .expressions
65                    .iter()
66                    .map(|x| x.to_string())
67                    .collect::<Vec<_>>()
68                    .join(", ");
69
70                write!(f, "({})", values)
71            }
72            Expression::Value(ref expression) => write!(f, "{}", expression),
73        }
74    }
75}