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::Update)]
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
37impl<'db> BlocksBuilder<'db> {
38    pub fn new() -> Self {
39        Self(vec![])
40    }
41    /// Creates a new builder with pre-allocated capacity for `n` blocks.
42    pub fn with_capacity(n: usize) -> Self {
43        Self(Vec::with_capacity(n))
44    }
45    pub fn alloc(&mut self, block: Block<'db>) -> BlockId {
46        let id = BlockId(self.0.len());
47        self.0.push(block);
48        id
49    }
50    /// Allocate a new block ID. The block itself should be populated later.
51    pub fn alloc_empty(&mut self) -> BlockId {
52        let id = BlockId(self.0.len());
53        self.0.push(Block::default());
54        id
55    }
56    /// Sets an already-allocated block.
57    pub fn set_block(&mut self, id: BlockId, block: Block<'db>) {
58        self.0[id.0] = block;
59    }
60
61    /// Returns a mutable reference to an already-allocated block.
62    pub fn get_mut_block<'m>(&'m mut self, id: BlockId) -> &'m mut Block<'db> {
63        &mut self.0[id.0]
64    }
65
66    pub fn len(&self) -> usize {
67        self.0.len()
68    }
69
70    pub fn is_empty(&self) -> bool {
71        self.0.is_empty()
72    }
73
74    pub fn build(self) -> Option<Blocks<'db>> {
75        require(!self.is_empty())?;
76        Some(Blocks(self.0))
77    }
78}
79impl<'db> Blocks<'db> {
80    pub fn new_errored(_diag_added: DiagnosticAdded) -> Self {
81        Self(vec![])
82    }
83
84    pub fn get(&self) -> &[Block<'db>] {
85        &self.0
86    }
87
88    pub fn len(&self) -> usize {
89        self.0.len()
90    }
91
92    pub fn is_empty(&self) -> bool {
93        self.0.is_empty()
94    }
95
96    pub fn iter(
97        &self,
98    ) -> impl DoubleEndedIterator<Item = (BlockId, &Block<'db>)> + ExactSizeIterator {
99        self.0.iter().enumerate().map(|(i, b)| (BlockId(i), b))
100    }
101
102    // Note: It is safe to create DiagnosticAdded here, since BlocksBuilder::build() guarantees to
103    // build a non empty Blocks. The only way to create an empty Blocks is using
104    // `new_errored(DiagnosticAdded)`.
105    pub fn root_block(&self) -> Maybe<&Block<'db>> {
106        if self.is_empty() { Err(DiagnosticAdded) } else { Ok(&self.0[0]) }
107    }
108
109    pub fn has_root(&self) -> Maybe<()> {
110        if self.is_empty() { Err(DiagnosticAdded) } else { Ok(()) }
111    }
112
113    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Block<'db>> {
114        self.0.iter_mut()
115    }
116
117    pub fn push(&mut self, block: Block<'db>) -> BlockId {
118        let id = BlockId(self.0.len());
119        self.0.push(block);
120        id
121    }
122
123    pub fn reset_block(&mut self, block_id: BlockId, block: Block<'db>) {
124        self.0[block_id.0] = block;
125    }
126}
127impl<'db> IntoIterator for Blocks<'db> {
128    type Item = Block<'db>;
129    type IntoIter = std::vec::IntoIter<Block<'db>>;
130
131    fn into_iter(self) -> Self::IntoIter {
132        self.0.into_iter()
133    }
134}
135impl<'db> Index<BlockId> for Blocks<'db> {
136    type Output = Block<'db>;
137
138    fn index(&self, index: BlockId) -> &Self::Output {
139        &self.0[index.0]
140    }
141}
142impl<'db> IndexMut<BlockId> for Blocks<'db> {
143    fn index_mut(&mut self, index: BlockId) -> &mut Self::Output {
144        &mut self.0[index.0]
145    }
146}
147impl<'db> Index<StatementLocation> for Blocks<'db> {
148    type Output = Statement<'db>;
149
150    fn index(&self, index: StatementLocation) -> &Self::Output {
151        &self[index.0].statements[index.1]
152    }
153}