cairo_lang_lowering/objects/
blocks.rs1use std::ops::{Index, IndexMut};
2
3use cairo_lang_diagnostics::{DiagnosticAdded, Maybe};
4use cairo_lang_utils::require;
5
6use crate::Block;
7
8#[derive(Copy, Clone, PartialEq, Eq, Hash, salsa::Update)]
9pub struct BlockId(pub usize);
10impl BlockId {
11 pub fn root() -> Self {
12 Self(0)
13 }
14
15 pub fn is_root(&self) -> bool {
16 self.0 == 0
17 }
18
19 pub fn next_block_id(&self) -> BlockId {
20 BlockId(self.0 + 1)
21 }
22}
23impl core::fmt::Debug for BlockId {
24 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
25 write!(f, "blk{}", self.0)
26 }
27}
28
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
32pub struct BlocksBuilder<'db>(pub Vec<Block<'db>>);
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Blocks<'db>(Vec<Block<'db>>);
35
36impl<'db> BlocksBuilder<'db> {
37 pub fn new() -> Self {
38 Self(vec![])
39 }
40 pub fn alloc(&mut self, block: Block<'db>) -> BlockId {
41 let id = BlockId(self.0.len());
42 self.0.push(block);
43 id
44 }
45 pub fn alloc_empty(&mut self) -> BlockId {
47 let id = BlockId(self.0.len());
48 self.0.push(Block::default());
49 id
50 }
51 pub fn set_block(&mut self, id: BlockId, block: Block<'db>) {
53 self.0[id.0] = block;
54 }
55
56 pub fn get_mut_block<'m>(&'m mut self, id: BlockId) -> &'m mut Block<'db> {
58 &mut self.0[id.0]
59 }
60
61 pub fn len(&self) -> usize {
62 self.0.len()
63 }
64
65 pub fn is_empty(&self) -> bool {
66 self.0.is_empty()
67 }
68
69 pub fn build(self) -> Option<Blocks<'db>> {
70 require(!self.is_empty())?;
71 Some(Blocks(self.0))
72 }
73}
74impl<'db> Blocks<'db> {
75 pub fn new_errored(_diag_added: DiagnosticAdded) -> Self {
76 Self(vec![])
77 }
78
79 pub fn get(&self) -> &Vec<Block<'db>> {
80 &self.0
81 }
82
83 pub fn len(&self) -> usize {
84 self.0.len()
85 }
86
87 pub fn is_empty(&self) -> bool {
88 self.0.is_empty()
89 }
90
91 pub fn iter(
92 &self,
93 ) -> impl DoubleEndedIterator<Item = (BlockId, &Block<'db>)> + ExactSizeIterator {
94 self.0.iter().enumerate().map(|(i, b)| (BlockId(i), b))
95 }
96
97 pub fn root_block(&self) -> Maybe<&Block<'db>> {
101 if self.is_empty() { Err(DiagnosticAdded) } else { Ok(&self.0[0]) }
102 }
103
104 pub fn has_root(&self) -> Maybe<()> {
105 if self.is_empty() { Err(DiagnosticAdded) } else { Ok(()) }
106 }
107
108 pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Block<'db>> {
109 self.0.iter_mut()
110 }
111
112 pub fn push(&mut self, block: Block<'db>) -> BlockId {
113 let id = BlockId(self.0.len());
114 self.0.push(block);
115 id
116 }
117
118 pub fn reset_block(&mut self, block_id: BlockId, block: Block<'db>) {
119 self.0[block_id.0] = block;
120 }
121}
122impl<'db> Index<BlockId> for Blocks<'db> {
123 type Output = Block<'db>;
124
125 fn index(&self, index: BlockId) -> &Self::Output {
126 &self.0[index.0]
127 }
128}
129impl<'db> IndexMut<BlockId> for Blocks<'db> {
130 fn index_mut(&mut self, index: BlockId) -> &mut Self::Output {
131 &mut self.0[index.0]
132 }
133}