Skip to main content

python_assembler/formats/pyc/
mod.rs

1#![doc = include_str!("readme.md")]
2
3/// Marshal 序列化模块
4pub mod marshal;
5pub mod reader;
6/// 写入器模块,负责将 PythonProgram 写入到 .pyc 文件
7pub mod writer;
8
9use crate::program::PythonVersion;
10use gaia_types::{GaiaDiagnostics, GaiaError};
11use std::{fs::File, io::BufReader, path::Path};
12
13/// 配置结构体,用于指定读取 .pyc 文件时的参数
14#[derive(Debug, Clone, Copy)]
15pub struct PycReadConfig {
16    /// 指定 Python 版本,如果为 Unknown,则从文件头部推断
17    pub version: PythonVersion,
18}
19
20impl Default for PycReadConfig {
21    fn default() -> Self {
22        Self { version: PythonVersion::Unknown }
23    }
24}
25
26/// 配置结构体,用于指定写入 .pyc 文件时的参数
27#[derive(Debug, Clone, Copy)]
28pub struct PycWriteConfig {
29    /// 指定 Python 版本
30    pub version: PythonVersion,
31}
32
33impl Default for PycWriteConfig {
34    fn default() -> Self {
35        Self { version: PythonVersion::Python3_9 }
36    }
37}
38
39/// 从指定路径读取 .pyc 文件并解析为 PythonProgram
40pub fn pyc_read_path<P: AsRef<Path>>(path: P, config: &PycReadConfig) -> GaiaDiagnostics<crate::program::PythonProgram> {
41    let file = match File::open(path) {
42        Ok(f) => f,
43        Err(e) => return GaiaDiagnostics { result: Err(GaiaError::from(e)), diagnostics: Vec::new() },
44    };
45
46    let buf_reader = BufReader::new(file);
47    let reader = config.as_reader(buf_reader);
48    reader.finish()
49}