Skip to main content

appstruct_codegen/
lib.rs

1//! Deterministic code generation from `AppStruct` IR.
2
3mod artifact;
4mod backend;
5mod database;
6mod module_artifact;
7mod openapi;
8mod typescript;
9mod web;
10
11pub use artifact::{Artifact, ArtifactKind, CodegenError};
12
13use appstruct_ir::{AppIr, to_canonical_json, validate_app_ir};
14use std::io::Write;
15use std::process::{Command, Stdio};
16
17/// Plan every M1 artifact in memory before any filesystem write.
18///
19/// # Errors
20///
21/// Returns an error if IR serialization or source generation fails.
22pub fn plan(ir: &AppIr) -> Result<Vec<Artifact>, CodegenError> {
23    validate_app_ir(ir)?;
24    let canonical_ir = to_canonical_json(ir)?;
25    let mut artifacts = vec![Artifact::text(
26        "ir/app-ir.json",
27        canonical_ir,
28        ArtifactKind::CanonicalIr,
29    )];
30    artifacts.extend(database::plan(ir)?);
31    artifacts.extend(backend::plan(ir)?);
32    artifacts.extend(openapi::plan(ir)?);
33    artifacts.extend(typescript::plan(ir));
34    artifacts.extend(web::plan(ir));
35    artifacts.extend(module_artifact::plan(ir)?);
36    format_rust_artifacts(&mut artifacts)?;
37    artifacts.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
38    ensure_unique_paths(&artifacts)?;
39    Ok(artifacts)
40}
41
42fn ensure_unique_paths(artifacts: &[Artifact]) -> Result<(), CodegenError> {
43    for pair in artifacts.windows(2) {
44        if pair[0].relative_path == pair[1].relative_path {
45            return Err(CodegenError::new(format!(
46                "multiple generators own `{}`",
47                pair[0].relative_path.display()
48            )));
49        }
50    }
51    Ok(())
52}
53
54pub(crate) fn generated_header(comment: &str) -> String {
55    format!("{comment} @generated by AppStruct. Do not edit manually.\n\n")
56}
57
58pub(crate) fn format_rust(source: &str) -> Result<String, CodegenError> {
59    let syntax = syn::parse_file(source)
60        .map_err(|error| CodegenError::new(format!("generated Rust did not parse: {error}")))?;
61    Ok(format!(
62        "{}{}",
63        generated_header("//"),
64        prettyplease::unparse(&syntax)
65    ))
66}
67
68fn format_rust_artifacts(artifacts: &mut [Artifact]) -> Result<(), CodegenError> {
69    let rust_indexes = artifacts
70        .iter()
71        .enumerate()
72        .filter_map(|(index, artifact)| {
73            (artifact.kind == ArtifactKind::RustSource).then_some(index)
74        })
75        .collect::<Vec<_>>();
76    if rust_indexes.is_empty() {
77        return Ok(());
78    }
79    let mut input = String::new();
80    for index in &rust_indexes {
81        let source = std::str::from_utf8(&artifacts[*index].content)
82            .map_err(|error| CodegenError::new(format!("generated Rust is not UTF-8: {error}")))?;
83        input.push_str(&start_marker(*index));
84        input.push_str(source);
85        if !source.ends_with('\n') {
86            input.push('\n');
87        }
88        input.push_str(&end_marker(*index));
89    }
90    let output = run_rustfmt(&input)?;
91    for index in rust_indexes {
92        let start = start_marker(index);
93        let end = end_marker(index);
94        let (_, remainder) = output
95            .split_once(&start)
96            .ok_or_else(|| CodegenError::new("rustfmt removed an artifact start marker"))?;
97        let (source, _) = remainder
98            .split_once(&end)
99            .ok_or_else(|| CodegenError::new("rustfmt removed an artifact end marker"))?;
100        artifacts[index].content = format!("{}\n", source.trim_matches('\n')).into_bytes();
101    }
102    Ok(())
103}
104
105fn run_rustfmt(source: &str) -> Result<String, CodegenError> {
106    let mut child = Command::new("rustfmt")
107        .args(["--emit", "stdout", "--edition", "2024"])
108        .stdin(Stdio::piped())
109        .stdout(Stdio::piped())
110        .stderr(Stdio::piped())
111        .spawn()
112        .map_err(|error| CodegenError::new(format!("failed to start rustfmt: {error}")))?;
113    child
114        .stdin
115        .take()
116        .ok_or_else(|| CodegenError::new("rustfmt stdin was not available"))?
117        .write_all(source.as_bytes())
118        .map_err(|error| CodegenError::new(format!("failed to write to rustfmt: {error}")))?;
119    let output = child
120        .wait_with_output()
121        .map_err(|error| CodegenError::new(format!("failed to wait for rustfmt: {error}")))?;
122    if !output.status.success() {
123        return Err(CodegenError::new(format!(
124            "rustfmt failed: {}",
125            String::from_utf8_lossy(&output.stderr).trim()
126        )));
127    }
128    String::from_utf8(output.stdout)
129        .map_err(|error| CodegenError::new(format!("rustfmt returned invalid UTF-8: {error}")))
130}
131
132fn start_marker(index: usize) -> String {
133    format!("// __APPSTRUCT_ARTIFACT_{index}_START__\n")
134}
135
136fn end_marker(index: usize) -> String {
137    format!("// __APPSTRUCT_ARTIFACT_{index}_END__\n")
138}