leo_ast/common/
node_builder.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::NodeID;
18
19use std::cell::RefCell;
20
21/// A counter that produces sequentially increasing `NodeID`s.
22#[derive(Debug, Clone)]
23pub struct NodeBuilder {
24    /// The inner counter.
25    /// `RefCell` is used here to avoid `&mut` all over the compiler.
26    inner: RefCell<NodeBuilderInner>,
27}
28
29impl NodeBuilder {
30    /// Returns a new `NodeCounter` with the given `NodeID` as the starting value.
31    pub fn new(next: NodeID) -> Self {
32        Self { inner: RefCell::new(NodeBuilderInner::new(next)) }
33    }
34
35    /// Returns the next `NodeID` and increments the internal state.
36    pub fn next_id(&self) -> NodeID {
37        self.inner.borrow_mut().next_id()
38    }
39}
40
41impl Default for NodeBuilder {
42    fn default() -> Self {
43        Self::new(0)
44    }
45}
46
47/// Contains the actual data for `Handler`.
48/// Modeled this way to afford an API using interior mutability.
49#[derive(Debug, Clone)]
50pub struct NodeBuilderInner {
51    /// The next `NodeID`.
52    next: NodeID,
53}
54
55impl NodeBuilderInner {
56    /// Returns a new `NodeCounter` with the given `NodeID` as the starting value.
57    pub fn new(next: NodeID) -> Self {
58        Self { next }
59    }
60
61    /// Returns the next `NodeID` and increments the internal state.
62    pub fn next_id(&mut self) -> NodeID {
63        let next = self.next;
64        self.next += 1;
65        next
66    }
67}