appstruct-codegen 0.1.0

Deterministic Rust, SQL, OpenAPI, TypeScript, and React generation for AppStruct
Documentation
//! Deterministic code generation from `AppStruct` IR.

mod artifact;
mod backend;
mod database;
mod module_artifact;
mod openapi;
mod typescript;
mod web;

pub use artifact::{Artifact, ArtifactKind, CodegenError};

use appstruct_ir::{AppIr, to_canonical_json, validate_app_ir};
use std::io::Write;
use std::process::{Command, Stdio};

/// Plan every M1 artifact in memory before any filesystem write.
///
/// # Errors
///
/// Returns an error if IR serialization or source generation fails.
pub fn plan(ir: &AppIr) -> Result<Vec<Artifact>, CodegenError> {
    validate_app_ir(ir)?;
    let canonical_ir = to_canonical_json(ir)?;
    let mut artifacts = vec![Artifact::text(
        "ir/app-ir.json",
        canonical_ir,
        ArtifactKind::CanonicalIr,
    )];
    artifacts.extend(database::plan(ir)?);
    artifacts.extend(backend::plan(ir)?);
    artifacts.extend(openapi::plan(ir)?);
    artifacts.extend(typescript::plan(ir));
    artifacts.extend(web::plan(ir));
    artifacts.extend(module_artifact::plan(ir)?);
    format_rust_artifacts(&mut artifacts)?;
    artifacts.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
    ensure_unique_paths(&artifacts)?;
    Ok(artifacts)
}

fn ensure_unique_paths(artifacts: &[Artifact]) -> Result<(), CodegenError> {
    for pair in artifacts.windows(2) {
        if pair[0].relative_path == pair[1].relative_path {
            return Err(CodegenError::new(format!(
                "multiple generators own `{}`",
                pair[0].relative_path.display()
            )));
        }
    }
    Ok(())
}

pub(crate) fn generated_header(comment: &str) -> String {
    format!("{comment} @generated by AppStruct. Do not edit manually.\n\n")
}

pub(crate) fn format_rust(source: &str) -> Result<String, CodegenError> {
    let syntax = syn::parse_file(source)
        .map_err(|error| CodegenError::new(format!("generated Rust did not parse: {error}")))?;
    Ok(format!(
        "{}{}",
        generated_header("//"),
        prettyplease::unparse(&syntax)
    ))
}

fn format_rust_artifacts(artifacts: &mut [Artifact]) -> Result<(), CodegenError> {
    let rust_indexes = artifacts
        .iter()
        .enumerate()
        .filter_map(|(index, artifact)| {
            (artifact.kind == ArtifactKind::RustSource).then_some(index)
        })
        .collect::<Vec<_>>();
    if rust_indexes.is_empty() {
        return Ok(());
    }
    let mut input = String::new();
    for index in &rust_indexes {
        let source = std::str::from_utf8(&artifacts[*index].content)
            .map_err(|error| CodegenError::new(format!("generated Rust is not UTF-8: {error}")))?;
        input.push_str(&start_marker(*index));
        input.push_str(source);
        if !source.ends_with('\n') {
            input.push('\n');
        }
        input.push_str(&end_marker(*index));
    }
    let output = run_rustfmt(&input)?;
    for index in rust_indexes {
        let start = start_marker(index);
        let end = end_marker(index);
        let (_, remainder) = output
            .split_once(&start)
            .ok_or_else(|| CodegenError::new("rustfmt removed an artifact start marker"))?;
        let (source, _) = remainder
            .split_once(&end)
            .ok_or_else(|| CodegenError::new("rustfmt removed an artifact end marker"))?;
        artifacts[index].content = format!("{}\n", source.trim_matches('\n')).into_bytes();
    }
    Ok(())
}

fn run_rustfmt(source: &str) -> Result<String, CodegenError> {
    let mut child = Command::new("rustfmt")
        .args(["--emit", "stdout", "--edition", "2024"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|error| CodegenError::new(format!("failed to start rustfmt: {error}")))?;
    child
        .stdin
        .take()
        .ok_or_else(|| CodegenError::new("rustfmt stdin was not available"))?
        .write_all(source.as_bytes())
        .map_err(|error| CodegenError::new(format!("failed to write to rustfmt: {error}")))?;
    let output = child
        .wait_with_output()
        .map_err(|error| CodegenError::new(format!("failed to wait for rustfmt: {error}")))?;
    if !output.status.success() {
        return Err(CodegenError::new(format!(
            "rustfmt failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    String::from_utf8(output.stdout)
        .map_err(|error| CodegenError::new(format!("rustfmt returned invalid UTF-8: {error}")))
}

fn start_marker(index: usize) -> String {
    format!("// __APPSTRUCT_ARTIFACT_{index}_START__\n")
}

fn end_marker(index: usize) -> String {
    format!("// __APPSTRUCT_ARTIFACT_{index}_END__\n")
}