leo_passes/common/assigner/
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 leo_ast::{DefinitionPlace, DefinitionStatement, Expression, Identifier, NodeID, Statement};
18use leo_span::Symbol;
19
20use std::{cell::RefCell, fmt::Display};
21
22/// A struct used to create assignment statements.
23#[derive(Debug, Default, Clone)]
24pub struct Assigner {
25    /// The inner counter.
26    /// `RefCell` is used here to avoid `&mut` all over the compiler.
27    inner: RefCell<AssignerInner>,
28}
29
30impl Assigner {
31    /// Return a new unique `Symbol` from a `&str`.
32    pub fn unique_symbol(&self, arg: impl Display, separator: impl Display) -> Symbol {
33        self.inner.borrow_mut().unique_symbol(arg, separator)
34    }
35
36    /// Constructs the definition statement `let place = expr;`.
37    /// This function should be the only place where `DefinitionStatement`s are constructed.
38    pub fn simple_definition(&self, identifier: Identifier, value: Expression, id: NodeID) -> Statement {
39        self.inner.borrow_mut().simple_definition(identifier, value, id)
40    }
41}
42
43/// Contains the actual data for `Assigner`.
44/// Modeled this way to afford an API using interior mutability.
45#[derive(Debug, Default, Clone)]
46pub struct AssignerInner {
47    /// A strictly increasing counter, used to ensure that new variable names are unique.
48    pub(crate) counter: usize,
49}
50
51impl AssignerInner {
52    /// Return a new unique `Symbol` from a `&str`.
53    fn unique_symbol(&mut self, arg: impl Display, separator: impl Display) -> Symbol {
54        self.counter += 1;
55        Symbol::intern(&format!("{}{}{}", arg, separator, self.counter - 1))
56    }
57
58    /// Constructs the definition statement `let place = expr;`.
59    /// This function should be the only place where `DefinitionStatement`s are constructed.
60    fn simple_definition(&mut self, identifier: Identifier, value: Expression, id: NodeID) -> Statement {
61        DefinitionStatement {
62            place: DefinitionPlace::Single(identifier),
63            type_: None,
64            value,
65            span: Default::default(),
66            id,
67        }
68        .into()
69    }
70}