leo_ast/statement/definition/
mod.rs

1// Copyright (C) 2019-2025 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::{Expression, Identifier, Node, NodeID, Statement, Type};
18
19use leo_span::Span;
20
21use itertools::Itertools as _;
22use serde::{Deserialize, Serialize};
23use std::fmt;
24
25/// A `let` or `const` declaration statement.
26#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
27pub struct DefinitionStatement {
28    /// The bindings / variable names to declare.
29    pub place: DefinitionPlace,
30    /// The types of the bindings, if specified, or inferred otherwise.
31    pub type_: Option<Type>,
32    /// An initializer value for the bindings.
33    pub value: Expression,
34    /// The span excluding the semicolon.
35    pub span: Span,
36    /// The ID of the node.
37    pub id: NodeID,
38}
39
40#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
41pub enum DefinitionPlace {
42    Single(Identifier),
43    Multiple(Vec<Identifier>),
44}
45
46impl fmt::Display for DefinitionPlace {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        match self {
49            DefinitionPlace::Single(id) => id.fmt(f),
50            DefinitionPlace::Multiple(ids) => write!(f, "({})", ids.iter().format(", ")),
51        }
52    }
53}
54
55impl fmt::Display for DefinitionStatement {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        match &self.type_ {
58            // For an Err type (as produced by many passes), don't write the type to reduce verbosity.
59            Some(Type::Err) | None => write!(f, "let {} = {}", self.place, self.value),
60            Some(ty) => write!(f, "let {}: {} = {}", self.place, ty, self.value),
61        }
62    }
63}
64
65impl From<DefinitionStatement> for Statement {
66    fn from(value: DefinitionStatement) -> Self {
67        Statement::Definition(value)
68    }
69}
70
71crate::simple_node_impl!(DefinitionStatement);