Skip to main content

cairo_lang_lowering/objects/
blocks.rs

1use std::ops::{Index, IndexMut};
2
3use cairo_lang_diagnostics::{DiagnosticAdded, Maybe};
4use cairo_lang_utils::require;
5
6use crate::analysis::StatementLocation;
7use crate::{Block, Statement};
8
9#[derive(Copy, Clone, PartialEq, Eq, Hash, salsa::SalsaValue)]
10pub struct BlockId(pub usize);
11impl BlockId {
12    pub fn root() -> Self {
13        Self(0)
14    }
15
16    pub fn is_root(&self) -> bool {
17        self.0 == 0
18    }
19
20    pub fn next_block_id(&self) -> BlockId {
21        BlockId(self.0 + 1)
22    }
23}
24impl core::fmt::Debug for BlockId {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        write!(f, "blk{}", self.0)
27    }
28}
29
30/// A convenient wrapper around a vector of blocks.
31/// This is used instead of id_arena, since the latter is harder to clone and modify.
32#[derive(Clone, Debug, Default, PartialEq, Eq)]
33pub struct BlocksBuilder<'db>(pub Vec<Block<'db>>);
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct Blocks<'db>(Vec<Block<'db>>);
36
37// SAFETY: The blocks hold owned lowered-IR objects composed of interned ids and owned data, all
38// of which are safe to retain across revisions; the contained `id_arena` ids are foreign types,
39// so this cannot be derived.
40unsafe impl<'db> salsa::SalsaValue for Blocks<'db> {}
41
42impl<'db> BlocksBuilder<'db> {
43    pub fn new() -> Self {
44        Self(vec![])
45    }
46    /// Creates a new builder with pre-allocated capacity for `n` blocks.
47    pub fn with_capacity(n: usize) -> Self {
48        Self(Vec::with_capacity(n))
49    }
50    pub fn alloc(&mut self, block: Block<'db>) -> BlockId {
51        let id = BlockId(self.0.len());
52        self.0.push(block);
53        id
54    }
55    /// Allocate a new block ID. The block itself should be populated later.
56    pub fn alloc_empty(&mut self) -> BlockId {
57        let id = BlockId(self.0.len());
58        self.0.push(Block::default());
59        id
60    }
61    /// Sets an already-allocated block.
62    pub fn set_block(&mut self, id: BlockId, block: Block<'db>) {
63        self.0[id.0] = block;
64    }
65
66    /// Returns a mutable reference to an already-allocated block.
67    pub fn get_mut_block<'m>(&'m mut self, id: BlockId) -> &'m mut Block<'db> {
68        &mut self.0[id.0]
69    }
70
71    pub fn len(&self) -> usize {
72        self.0.len()
73    }
74
75    pub fn is_empty(&self) -> bool {
76        self.0.is_empty()
77    }
78
79    pub fn build(self) -> Option<Blocks<'db>> {
80        require(!self.is_empty())?;
81        Some(Blocks(self.0))
82    }
83}
84impl<'db> Blocks<'db> {
85    pub fn new_errored(_diag_added: DiagnosticAdded) -> Self {
86        Self(vec![])
87    }
88
89    pub fn get(&self) -> &[Block<'db>] {
90        &self.0
91    }
92
93    pub fn len(&self) -> usize {
94        self.0.len()
95    }
96
97    pub fn is_empty(&self) -> bool {
98        self.0.is_empty()
99    }
100
101    pub fn iter(
102        &self,
103    ) -> impl DoubleEndedIterator<Item = (BlockId, &Block<'db>)> + ExactSizeIterator {
104        self.0.iter().enumerate().map(|(i, b)| (BlockId(i), b))
105    }
106
107    // Note: It is safe to create DiagnosticAdded here, since BlocksBuilder::build() guarantees to
108    // build a non empty Blocks. The only way to create an empty Blocks is using
109    // `new_errored(DiagnosticAdded)`.
110    pub fn root_block(&self) -> Maybe<&Block<'db>> {
111        if self.is_empty() { Err(DiagnosticAdded) } else { Ok(&self.0[0]) }
112    }
113
114    pub fn has_root(&self) -> Maybe<()> {
115        if self.is_empty() { Err(DiagnosticAdded) } else { Ok(()) }
116    }
117
118    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Block<'db>> {
119        self.0.iter_mut()
120    }
121
122    pub fn push(&mut self, block: Block<'db>) -> BlockId {
123        let id = BlockId(self.0.len());
124        self.0.push(block);
125        id
126    }
127
128    pub fn reset_block(&mut self, block_id: BlockId, block: Block<'db>) {
129        self.0[block_id.0] = block;
130    }
131}
132impl<'db> IntoIterator for Blocks<'db> {
133    type Item = Block<'db>;
134    type IntoIter = std::vec::IntoIter<Block<'db>>;
135
136    fn into_iter(self) -> Self::IntoIter {
137        self.0.into_iter()
138    }
139}
140impl<'db> Index<BlockId> for Blocks<'db> {
141    type Output = Block<'db>;
142
143    fn index(&self, index: BlockId) -> &Self::Output {
144        &self.0[index.0]
145    }
146}
147impl<'db> IndexMut<BlockId> for Blocks<'db> {
148    fn index_mut(&mut self, index: BlockId) -> &mut Self::Output {
149        &mut self.0[index.0]
150    }
151}
152impl<'db> Index<StatementLocation> for Blocks<'db> {
153    type Output = Statement<'db>;
154
155    fn index(&self, index: StatementLocation) -> &Self::Output {
156        &self[index.0].statements[index.1]
157    }
158}