Skip to main content

ydp_gen/
lib.rs

1//! 离线 CDP 协议编译器;输入经摘要验证后才进入统一生成管线。
2#![forbid(unsafe_code)]
3mod diff;
4mod input;
5/// 协议差异报告与离线比较入口。
6pub use diff::{ProtocolChange, ProtocolDiff, diff};
7mod layout;
8mod output;
9mod pdl;
10mod render;
11
12use serde::{Deserialize, Serialize};
13use std::{collections::BTreeMap, path::Path};
14
15/// 生成器错误,含稳定类别码、来源位置和中文修复提示;不依赖通信运行时。
16#[derive(Debug, thiserror::Error)]
17#[error("{code}: {location}: {message}")]
18pub struct GeneratorError {
19    /// 稳定诊断码,例如 Schema 或 Output。
20    pub code: &'static str,
21    /// 相对文件或符号路径,不包含输入正文。
22    pub location: String,
23    /// 中文原因和解决建议。
24    pub message: String,
25}
26fn error(
27    code: &'static str,
28    location: impl Into<String>,
29    message: impl Into<String>,
30) -> GeneratorError {
31    GeneratorError {
32        code,
33        location: location.into(),
34        message: message.into(),
35    }
36}
37/// 生成器各阶段的结构化结果,与 core 的通信错误独立。
38pub type Result<T> = std::result::Result<T, GeneratorError>;
39
40/// 经 SHA-256 校验的拥有型离线输入;内部保存源数据和配置,不持有打开的文件。
41#[derive(Debug, Clone)]
42pub struct SourceBundle {
43    manifest: input::Manifest,
44    sources: Vec<input::Source>,
45    docs: BTreeMap<String, input::Translation>,
46    overrides: Vec<(input::Override, Option<serde_json::Value>)>,
47}
48/// 纯编译阶段选项;始终保留协议原文,不要求中文翻译。
49#[derive(Debug, Clone, Default)]
50pub struct GenerateOptions {
51    /// 兼容旧调用的保留选项,目前不影响输出或发布资格;新调用使用默认值即可。
52    pub allow_incomplete_docs: bool,
53}
54/// 生成源码和 provenance 的拥有型集合;文件名均为受限相对路径。
55#[derive(Debug, Clone)]
56pub struct GeneratedOutput {
57    /// 应有文件全集,按相对路径稳定排序;内容为 UTF-8。
58    pub files: BTreeMap<String, String>,
59    /// 非致命中文诊断,稳定排序;不能用于绕过不支持的语义。
60    pub diagnostics: Vec<String>,
61    /// 是否满足生成器发布条件;协议原文完整保留,不以中文翻译数量判断。
62    pub release_ready: bool,
63}
64/// 只读比较的结果;不会修改被比较目录。
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct OutputDiff {
67    /// 缺失、内容不同或多余的相对文件路径,稳定排序。
68    pub changed: Vec<String>,
69}
70/// 源文件 provenance,不编造浏览器 revision。
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct SourceMetadata {
73    /// 相对 manifest 的源路径。
74    pub path: String,
75    /// 源文件原始字节的 SHA-256。
76    pub sha256: String,
77    /// 源文件声明的协议版本。
78    pub version: BTreeMap<String, String>,
79}
80/// 生成版本及源摘要;可序列化保存,运行时无需加载 schema。
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct GeneratedMetadata {
83    /// 与 core 共享的生成契约版本。
84    pub generated_contract_version: u32,
85    /// 生成器包版本。
86    pub generator_version: String,
87    /// 绑定包 Rust crate 名称。
88    pub binding_package: String,
89    /// 每个输入自己的源版本和摘要。
90    pub inputs: Vec<SourceMetadata>,
91    /// 规范化配置和说明目录的摘要。
92    pub configuration_sha256: String,
93}
94/// 读取 manifest 并校验所有输入摘要和根路径;不联网。路径、解析或摘要失败返回有来源的错误。
95///
96/// ```
97/// # use sha2::Digest;
98/// # let input = tempfile::tempdir()?;
99/// # let schema = br#"{"version":{"major":"1","minor":"0"},"domains":[{"domain":"Echo","commands":[{"name":"ping"}]}]}"#;
100/// # std::fs::write(input.path().join("schema.json"), schema)?;
101/// # let hash = format!("{:x}", sha2::Sha256::digest(schema));
102/// # let manifest = input.path().join("protocol.toml");
103/// # std::fs::write(&manifest, format!("format=1\ngenerated_crate=\"example_bindings\"\n[[inputs]]\npath=\"schema.json\"\nsha256=\"{hash}\"\n"))?;
104/// let bundle = ydp_gen::load_manifest(&manifest)?;
105/// # Ok::<(), Box<dyn std::error::Error>>(())
106/// ```
107pub fn load_manifest(path: &Path) -> Result<SourceBundle> {
108    input::load(path)
109}
110/// 将拥有型输入编译为确定性 Rust 源码;不写文件也不联网,未知语义或说明失配会失败。
111///
112/// ```
113/// # use sha2::Digest;
114/// # let input = tempfile::tempdir()?;
115/// # let schema = br#"{"version":{"major":"1","minor":"0"},"domains":[{"domain":"Echo","commands":[{"name":"ping"}]}]}"#;
116/// # std::fs::write(input.path().join("schema.json"), schema)?;
117/// # let hash = format!("{:x}", sha2::Sha256::digest(schema));
118/// # let manifest = input.path().join("protocol.toml");
119/// # std::fs::write(&manifest, format!("format=1\ngenerated_crate=\"example_bindings\"\n[[inputs]]\npath=\"schema.json\"\nsha256=\"{hash}\"\n"))?;
120/// let bundle = ydp_gen::load_manifest(&manifest)?;
121/// let output = ydp_gen::compile(&bundle, &ydp_gen::GenerateOptions::default())?;
122/// assert!(output.release_ready);
123/// # Ok::<(), Box<dyn std::error::Error>>(())
124/// ```
125pub fn compile(bundle: &SourceBundle, options: &GenerateOptions) -> Result<GeneratedOutput> {
126    render::compile(bundle, options)
127}
128/// 在同一文件系统暂存完整目录后发布;并发写入互斥,替换失败尝试恢复备份。拒绝额外人工文件。
129///
130/// ```
131/// # use sha2::Digest;
132/// # let input = tempfile::tempdir()?;
133/// # let schema = br#"{"version":{"major":"1","minor":"0"},"domains":[{"domain":"Echo","commands":[{"name":"ping"}]}]}"#;
134/// # std::fs::write(input.path().join("schema.json"), schema)?;
135/// # let hash = format!("{:x}", sha2::Sha256::digest(schema));
136/// # let manifest = input.path().join("protocol.toml");
137/// # std::fs::write(&manifest, format!("format=1\ngenerated_crate=\"example_bindings\"\n[[inputs]]\npath=\"schema.json\"\nsha256=\"{hash}\"\n"))?;
138/// let bundle = ydp_gen::load_manifest(&manifest)?;
139/// let output = ydp_gen::compile(&bundle, &Default::default())?;
140/// let directory = tempfile::tempdir()?;
141/// ydp_gen::write_output(&output, &directory.path().join("generated"))?;
142/// # Ok::<(), Box<dyn std::error::Error>>(())
143/// ```
144pub fn write_output(output: &GeneratedOutput, directory: &Path) -> Result<()> {
145    output::write(output, directory)
146}
147/// 比较应有文件集和字节,不创建或修改文件;拒绝调用方标记为不可发布的产物。
148///
149/// ```
150/// # use sha2::Digest;
151/// # let input = tempfile::tempdir()?;
152/// # let schema = br#"{"version":{"major":"1","minor":"0"},"domains":[{"domain":"Echo","commands":[{"name":"ping"}]}]}"#;
153/// # std::fs::write(input.path().join("schema.json"), schema)?;
154/// # let hash = format!("{:x}", sha2::Sha256::digest(schema));
155/// # let manifest = input.path().join("protocol.toml");
156/// # std::fs::write(&manifest, format!("format=1\ngenerated_crate=\"example_bindings\"\n[[inputs]]\npath=\"schema.json\"\nsha256=\"{hash}\"\n"))?;
157/// let bundle = ydp_gen::load_manifest(&manifest)?;
158/// let output = ydp_gen::compile(&bundle, &Default::default())?;
159/// let directory = input.path().join("generated");
160/// ydp_gen::write_output(&output, &directory)?;
161/// let diff = ydp_gen::check_output(&output, &directory)?;
162/// assert!(diff.changed.is_empty());
163/// # Ok::<(), Box<dyn std::error::Error>>(())
164/// ```
165pub fn check_output(output: &GeneratedOutput, directory: &Path) -> Result<OutputDiff> {
166    output::check(output, directory)
167}