appstruct-codegen 0.2.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 formatting;
mod module_artifact;
mod openapi;
mod typescript;
mod web;

pub use artifact::{Artifact, ArtifactKind, CodegenError};
pub use web::symbols::{RequiredSymbols, check_user_symbols, required_symbols};

use appstruct_ir::{AppIr, to_canonical_json, validate_app_ir};
use quote::ToTokens;
use std::path::Path;
use std::time::{Duration, Instant};

#[derive(Clone, Copy, Debug, Default)]
pub struct PlanOptions<'path> {
    rustfmt_cache: Option<&'path Path>,
}

impl<'path> PlanOptions<'path> {
    #[must_use]
    pub fn with_rustfmt_cache(mut self, directory: &'path Path) -> Self {
        self.rustfmt_cache = Some(directory);
        self
    }
}

#[derive(Clone, Debug, Default)]
pub struct PlannerTimings {
    pub database: Duration,
    pub backend: Duration,
    pub openapi: Duration,
    pub typescript: Duration,
    pub web: Duration,
    pub modules: Duration,
}

#[derive(Clone, Debug, Default)]
pub struct RustfmtTimings {
    pub total: Duration,
    pub process: Duration,
    pub memory_hits: usize,
    pub persistent_hits: usize,
    pub misses: usize,
}

#[derive(Clone, Debug, Default)]
pub struct PlanTimings {
    pub total: Duration,
    pub validation: Duration,
    pub canonical_ir: Duration,
    pub planners: PlannerTimings,
    pub rustfmt: RustfmtTimings,
}

#[derive(Clone, Debug)]
pub struct PlanOutput {
    pub artifacts: Vec<Artifact>,
    pub timings: PlanTimings,
}

/// 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> {
    plan_with_options(ir, PlanOptions::default()).map(|output| output.artifacts)
}

/// Plan every artifact and optionally reuse content-addressed Rust formatting results.
///
/// # Errors
///
/// Returns an error if IR serialization, source generation, or Rust formatting fails.
pub fn plan_with_options(ir: &AppIr, options: PlanOptions<'_>) -> Result<PlanOutput, CodegenError> {
    let total_started = Instant::now();
    let started = Instant::now();
    validate_app_ir(ir)?;
    let validation = started.elapsed();
    let started = Instant::now();
    let canonical_ir = to_canonical_json(ir)?;
    let canonical_ir_elapsed = started.elapsed();
    let mut artifacts = vec![Artifact::text(
        "ir/app-ir.json",
        canonical_ir,
        ArtifactKind::CanonicalIr,
    )];
    let planned = std::thread::scope(|scope| {
        let database = scope.spawn(|| timed(|| database::plan(ir)));
        let backend = scope.spawn(|| timed(|| backend::plan(ir)));
        let openapi = scope.spawn(|| timed(|| openapi::plan(ir)));
        let typescript = scope.spawn(|| timed(|| typescript::plan(ir)));
        let web = scope.spawn(|| timed(|| web::plan(ir)));
        let modules = scope.spawn(|| timed(|| module_artifact::plan(ir)));
        let (database_elapsed, database) = join_planner(database, "database")?;
        let (backend_elapsed, backend) = join_planner(backend, "backend")?;
        let (openapi_elapsed, openapi) = join_planner(openapi, "OpenAPI")?;
        let (typescript_elapsed, typescript) = join_planner(typescript, "TypeScript")?;
        let (web_elapsed, web) = join_planner(web, "Web")?;
        let (modules_elapsed, modules) = join_planner(modules, "module")?;
        Ok::<_, CodegenError>((
            [database?, backend?, openapi?, typescript, web, modules?],
            PlannerTimings {
                database: database_elapsed,
                backend: backend_elapsed,
                openapi: openapi_elapsed,
                typescript: typescript_elapsed,
                web: web_elapsed,
                modules: modules_elapsed,
            },
        ))
    })?;
    artifacts.extend(planned.0.into_iter().flatten());
    let rustfmt = formatting::format_rust_artifacts(&mut artifacts, options.rustfmt_cache)?;
    artifacts.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
    ensure_unique_paths(&artifacts)?;
    Ok(PlanOutput {
        artifacts,
        timings: PlanTimings {
            total: total_started.elapsed(),
            validation,
            canonical_ir: canonical_ir_elapsed,
            planners: planned.1,
            rustfmt,
        },
    })
}

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("//"),
        syntax.into_token_stream()
    ))
}

fn join_planner<T>(
    handle: std::thread::ScopedJoinHandle<'_, T>,
    name: &str,
) -> Result<T, CodegenError> {
    handle
        .join()
        .map_err(|_| CodegenError::new(format!("{name} generation worker panicked")))
}

fn timed<T>(operation: impl FnOnce() -> T) -> (Duration, T) {
    let started = Instant::now();
    let result = operation();
    (started.elapsed(), result)
}