1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::fmt::Display;

use crate::ir::{self, function::basic_block::BasicBlock};

use super::IsAction;

#[derive(Debug, Clone)]
pub enum InsertPosition {
    Back,
    Index(usize),
}

impl Display for InsertPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InsertPosition::Back => write!(f, "back of function"),
            InsertPosition::Index(index) => write!(f, "{index}"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct InsertBasicBlock {
    pub position: InsertPosition,
    pub name: String,
    pub content: Vec<ir::statement::IRStatement>,
}

impl IsAction for InsertBasicBlock {
    fn perform_on_function(self, ir: &mut crate::ir::FunctionDefinition) {
        let mut block = BasicBlock::new(self.name);
        block.content = self.content;
        match self.position {
            InsertPosition::Back => {
                ir.content.push(block);
            }
            InsertPosition::Index(index) => {
                ir.content.insert(index, block);
            }
        }
    }
}

impl Display for InsertBasicBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "insert `{}` at {}", self.name, self.position)
    }
}

impl InsertBasicBlock {
    pub fn at_index(index: impl Into<usize>, name: String) -> Self {
        Self {
            position: InsertPosition::Index(index.into()),
            name,
            content: Vec::new(),
        }
    }
    pub fn back_of(name: String) -> Self {
        Self {
            position: InsertPosition::Back,
            name,
            content: Vec::new(),
        }
    }
    pub fn set_content(mut self, content: Vec<ir::statement::IRStatement>) -> Self {
        self.content = content;
        self
    }
}