python_assembler/builder/
mod.rs

1use crate::{
2    instructions::PythonInstruction,
3    program::{PycHeader, PythonCodeObject, PythonObject, PythonProgram},
4};
5
6/// PycProgram 的构建器
7#[derive(Debug)]
8pub struct PythonBuilder {
9    instructions: Vec<PythonInstruction>,
10    constants: Vec<PythonObject>,
11    names: Vec<String>,
12}
13
14impl PythonBuilder {
15    pub fn new() -> Self {
16        Self { instructions: Vec::new(), constants: Vec::new(), names: Vec::new() }
17    }
18
19    /// 添加打印字符串指令:print("...")
20    pub fn print_str(mut self, s: &str) -> Self {
21        let const_value = PythonObject::Str(s.to_string());
22        let const_index = self.constants.len() as u8;
23        self.constants.push(const_value);
24
25        let print_name = "print".to_string();
26        let print_index = if let Some(idx) = self.names.iter().position(|n| n == &print_name) {
27            idx as u8
28        }
29        else {
30            self.names.push(print_name);
31            (self.names.len() - 1) as u8
32        };
33        self
34    }
35
36    pub fn build(self, header: PycHeader) -> PythonProgram {
37        PythonProgram {
38            header,
39            code_object: PythonCodeObject {
40                source_name: "<string>".to_string(),
41                first_line: 1,
42                last_line: 1,
43                num_params: 0,
44                is_vararg: 0,
45                max_stack_size: 0,
46                nested_functions: vec![],
47                upvalues: vec![],
48                local_vars: vec![],
49                line_info: vec![],
50                co_argcount: 0,
51                co_nlocal: 0,
52                co_stacks: 0,
53                num_upval: 0,
54                co_code: vec![],
55                co_consts: self.constants,
56                upvalue_n: 0,
57            },
58        }
59    }
60}