Skip to main content

python_assembler/formats/pyc/
mod.rs

1//! # pyc 模块
2//!
3//! 本模块提供了对 Python 字节码文件(`.pyc` 文件)的读取、解析和写入功能。
4//! 它包含了以下主要组件:
5//!
6//! - `reader`: 负责从字节流中读取和解析 `.pyc` 文件的内容。
7//! - `writer`: 负责将 PythonProgram 序列化为 `.pyc` 文件的字节流。
8//!
9//! ## 设计目标
10//!
11//! - **高效性**:通过优化的数据结构和算法,确保读取和写入操作的高效性。
12//! - **准确性**:严格遵循 `.pyc` 文件格式规范,确保生成和解析的文件符合标准。
13//! - **易用性**:提供简洁明了的 API,使得用户可以轻松地进行 `.pyc` 文件的操作。
14//! - **可扩展性**:模块化的设计使得功能可以根据需要进行扩展和定制。
15
16/// Marshal 序列化模块
17pub mod marshal;
18pub mod reader;
19/// 写入器模块,负责将 PythonProgram 写入到 .pyc 文件
20pub mod writer;
21
22use crate::program::PythonVersion;
23use gaia_types::{GaiaDiagnostics, GaiaError};
24use std::{fs::File, io::BufReader, path::Path};
25
26/// 配置结构体,用于指定读取 .pyc 文件时的参数
27#[derive(Debug, Clone, Copy)]
28pub struct PycReadConfig {
29    /// 指定 Python 版本,如果为 Unknown,则从文件头部推断
30    pub version: PythonVersion,
31}
32
33impl Default for PycReadConfig {
34    fn default() -> Self {
35        Self { version: PythonVersion::Unknown }
36    }
37}
38
39/// 配置结构体,用于指定写入 .pyc 文件时的参数
40#[derive(Debug, Clone, Copy)]
41pub struct PycWriteConfig {
42    /// 指定 Python 版本
43    pub version: PythonVersion,
44}
45
46impl Default for PycWriteConfig {
47    fn default() -> Self {
48        Self { version: PythonVersion::Python3_9 }
49    }
50}
51
52/// 从指定路径读取 .pyc 文件并解析为 PythonProgram
53pub fn pyc_read_path<P: AsRef<Path>>(path: P, config: &PycReadConfig) -> GaiaDiagnostics<crate::program::PythonProgram> {
54    let file = match File::open(path) {
55        Ok(f) => f,
56        Err(e) => return GaiaDiagnostics { result: Err(GaiaError::from(e)), diagnostics: Vec::new() },
57    };
58
59    let buf_reader = BufReader::new(file);
60    let reader = config.as_reader(buf_reader);
61    reader.finish()
62}