python_assembler/program/
mod.rs1use crate::instructions::PythonInstruction;
2use serde::{Deserialize, Serialize};
3use std::fmt::Debug;
4
5#[derive(Clone, Debug, PartialEq, Eq, Copy)]
6pub enum PythonVersion {
7 Unknown,
8 Python3_7,
9 Python3_8,
10 Python3_9,
11 Python3_10,
12 Python3_11,
13 Python3_12,
14}
15
16impl PythonVersion {
17 pub fn to_byte(&self) -> u8 {
18 match self {
19 PythonVersion::Python3_7 => 0x51,
20 PythonVersion::Python3_8 => 0x52,
21 PythonVersion::Python3_9 => 0x53,
22 PythonVersion::Python3_10 => 0x54,
23 _ => 0x00, }
25 }
26
27 pub fn from_byte(byte: u8) -> Self {
28 match byte {
29 0x51 => PythonVersion::Python3_7,
30 0x52 => PythonVersion::Python3_8,
31 0x53 => PythonVersion::Python3_9,
32 0x54 => PythonVersion::Python3_10,
33 _ => PythonVersion::Unknown,
34 }
35 }
36
37 pub fn from_magic(magic: [u8; 4]) -> Self {
40 match magic {
41 [203, 13, 13, 10] => PythonVersion::Python3_12,
43 _ => PythonVersion::Unknown,
45 }
46 }
47}
48
49#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub struct PycHeader {
51 pub magic: [u8; 4],
52 pub flags: u32,
53 pub timestamp: u32,
54 pub size: u32,
55}
56
57impl Default for PycHeader {
58 fn default() -> Self {
59 Self { magic: [0; 4], flags: 0, timestamp: 0, size: 0 }
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct Upvalue {
66 pub in_stack: u8, pub idx: u8, pub name: String, }
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct LocalVar {
74 pub name: String,
75 pub start_pc: u32,
76 pub end_pc: u32,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub enum PythonObject {
81 Str(String),
82 Int(i32),
83 Code(PythonCodeObject),
84 None,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
88pub struct PythonCodeObject {
89 pub source_name: String,
90 pub first_line: u32,
91 pub last_line: u32,
92 pub num_params: u8,
93 pub is_vararg: u8,
94 pub max_stack_size: u8,
95 pub nested_functions: Vec<PythonCodeObject>,
96 pub upvalues: Vec<Upvalue>,
97 pub local_vars: Vec<LocalVar>,
98 pub line_info: Vec<u8>,
99 pub co_argcount: u8,
100 pub co_nlocal: u8,
101 pub co_stacks: u8,
102 pub num_upval: u8,
103 pub co_code: Vec<PythonInstruction>,
104 pub co_consts: Vec<PythonObject>,
105 pub upvalue_n: u8,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
110pub struct PythonProgram {
111 pub header: PycHeader,
112 pub code_object: PythonCodeObject,
113}