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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use crate::{
    ast,
    ir::{
        function::{
            ir_generator::{rvalue_from_ast, IRGeneratingContext},
            IsIRStatement,
        },
        quantity::{self, local, Quantity},
        RegisterName,
    },
    utility::{data_type, data_type::Type, parsing},
};
use itertools::Itertools;
use nom::{
    bytes::complete::tag,
    character::complete::space0,
    combinator::{map, opt},
    multi::separated_list0,
    sequence::{delimited, tuple},
    IResult,
};
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
/// [`Call`] instruction.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct Call {
    /// Where to store the result of the call.
    pub to: Option<RegisterName>,
    /// Name of the function to call.
    pub name: String,
    /// Result type.
    pub data_type: Type,
    /// Arguments to pass to the function.
    pub params: Vec<Quantity>,
}

impl IsIRStatement for Call {
    fn on_register_change(&mut self, from: &RegisterName, to: Quantity) {
        if let Some(result_to) = &self.to
            && result_to == from
        {
            self.to = Some(to.clone().unwrap_local());
        }
        for param in self.params.iter_mut() {
            if let Quantity::RegisterName(param_val) = param {
                if param_val == from {
                    *param = to.clone();
                }
            }
        }
    }

    fn generate_register(&self) -> Option<(RegisterName, Type)> {
        self.to.clone().map(|it| (it, self.data_type.clone()))
    }

    fn use_register(&self) -> Vec<RegisterName> {
        self.params
            .iter()
            .filter_map(|it| {
                if let Quantity::RegisterName(register) = it {
                    Some(register.clone())
                } else {
                    None
                }
            })
            .collect()
    }
}

impl Display for Call {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(to_register) = &self.to {
            write!(f, "{to_register} = ")?;
        }
        write!(f, "call {} {}(", self.data_type, self.name)?;
        write!(
            f,
            "{}",
            self.params
                .iter()
                .map(|it| format!("{it}"))
                .collect::<Vec<_>>()
                .join(",")
        )?;
        write!(f, ")")
    }
}

/// Parse a [`Call`] instruction.
pub fn parse(code: &str) -> IResult<&str, Call> {
    map(
        tuple((
            opt(map(tuple((local::parse, space0, tag("="), space0)), |x| {
                x.0
            })),
            tag("call"),
            space0,
            data_type::parse,
            space0,
            parsing::ident,
            delimited(
                tag("("),
                separated_list0(tuple((space0, tag(","), space0)), quantity::parse),
                tag(")"),
            ),
        )),
        |(result, _, _, data_type, _, name, params)| Call {
            to: result,
            data_type,
            name,
            params,
        },
    )(code)
}

/// Generate a [`Call`] from an [`ast::expression::FunctionCall`],
/// and append it to the current basic block.
/// Return a [`RegisterName`] which contains the result.
pub fn from_ast(
    ast: &ast::expression::FunctionCall,
    ctx: &mut IRGeneratingContext,
) -> RegisterName {
    let ast::expression::FunctionCall { name, arguments } = ast;
    let function_info = ctx
        .parent_context
        .function_definitions
        .get(name)
        .unwrap()
        .clone();
    let result_register = ctx.next_register_with_type(&function_info.return_type);
    let params = arguments
        .iter()
        .map(|it| rvalue_from_ast(it, ctx))
        .collect_vec();
    ctx.current_basic_block.append_statement(Call {
        to: Some(result_register.clone()),
        name: name.clone(),
        data_type: function_info.return_type.clone(),
        params,
    });
    result_register
}
#[cfg(test)]
mod tests {
    #![allow(clippy::borrow_interior_mutable_const)]
    use crate::{
        ast::expression::IntegerLiteral,
        ir::{function::parameter::Parameter, FunctionHeader},
    };

    use super::*;

    #[test]
    fn test_parse() {
        let result = parse("call i32 foo()").unwrap().1;
        assert_eq!(
            result,
            Call {
                to: None,
                data_type: data_type::I32.clone(),
                name: "foo".to_string(),
                params: vec![]
            }
        );
        let result = parse("%1 = call i32 foo(%0)").unwrap().1;
        assert_eq!(
            result,
            Call {
                to: Some(RegisterName("1".to_string())),
                data_type: data_type::I32.clone(),
                name: "foo".to_string(),
                params: vec![RegisterName("0".to_string()).into()]
            }
        );
    }

    #[test]
    fn test_from_ast() {
        let ast = ast::expression::FunctionCall {
            name: "f".to_string(),
            arguments: vec![IntegerLiteral(1i64).into()],
        };
        let mut parent_ctx = crate::ir::IRGeneratingContext::new();
        parent_ctx.function_definitions.insert(
            "f".to_string(),
            FunctionHeader {
                name: "f".to_string(),
                parameters: vec![Parameter {
                    name: RegisterName("a".to_string()),
                    data_type: data_type::I32.clone(),
                }],
                return_type: data_type::I32.clone(),
            },
        );
        let mut ctx = super::IRGeneratingContext::new(&mut parent_ctx);
        let result = from_ast(&ast, &mut ctx);
        assert_eq!(result, RegisterName("0".to_string()));
        let call_statement = ctx.current_basic_block.content.pop().unwrap();
        assert_eq!(
            call_statement,
            Call {
                to: Some(RegisterName("0".to_string())),
                data_type: data_type::I32.clone(),
                name: "f".to_string(),
                params: vec![1.into()]
            }
            .into()
        );
    }
}