Skip to main content

appstruct_codegen/
lib.rs

1//! Deterministic code generation from `AppStruct` IR.
2
3mod artifact;
4mod backend;
5mod database;
6mod formatting;
7mod module_artifact;
8mod openapi;
9mod typescript;
10mod web;
11
12pub use artifact::{Artifact, ArtifactKind, CodegenError};
13pub use web::symbols::{RequiredSymbols, check_user_symbols, required_symbols};
14
15use appstruct_ir::{AppIr, to_canonical_json, validate_app_ir};
16use quote::ToTokens;
17use std::path::Path;
18use std::time::{Duration, Instant};
19
20#[derive(Clone, Copy, Debug, Default)]
21pub struct PlanOptions<'path> {
22    rustfmt_cache: Option<&'path Path>,
23}
24
25impl<'path> PlanOptions<'path> {
26    #[must_use]
27    pub fn with_rustfmt_cache(mut self, directory: &'path Path) -> Self {
28        self.rustfmt_cache = Some(directory);
29        self
30    }
31}
32
33#[derive(Clone, Debug, Default)]
34pub struct PlannerTimings {
35    pub database: Duration,
36    pub backend: Duration,
37    pub openapi: Duration,
38    pub typescript: Duration,
39    pub web: Duration,
40    pub modules: Duration,
41}
42
43#[derive(Clone, Debug, Default)]
44pub struct RustfmtTimings {
45    pub total: Duration,
46    pub process: Duration,
47    pub memory_hits: usize,
48    pub persistent_hits: usize,
49    pub misses: usize,
50}
51
52#[derive(Clone, Debug, Default)]
53pub struct PlanTimings {
54    pub total: Duration,
55    pub validation: Duration,
56    pub canonical_ir: Duration,
57    pub planners: PlannerTimings,
58    pub rustfmt: RustfmtTimings,
59}
60
61#[derive(Clone, Debug)]
62pub struct PlanOutput {
63    pub artifacts: Vec<Artifact>,
64    pub timings: PlanTimings,
65}
66
67/// Plan every M1 artifact in memory before any filesystem write.
68///
69/// # Errors
70///
71/// Returns an error if IR serialization or source generation fails.
72pub fn plan(ir: &AppIr) -> Result<Vec<Artifact>, CodegenError> {
73    plan_with_options(ir, PlanOptions::default()).map(|output| output.artifacts)
74}
75
76/// Plan every artifact and optionally reuse content-addressed Rust formatting results.
77///
78/// # Errors
79///
80/// Returns an error if IR serialization, source generation, or Rust formatting fails.
81pub fn plan_with_options(ir: &AppIr, options: PlanOptions<'_>) -> Result<PlanOutput, CodegenError> {
82    let total_started = Instant::now();
83    let started = Instant::now();
84    validate_app_ir(ir)?;
85    let validation = started.elapsed();
86    let started = Instant::now();
87    let canonical_ir = to_canonical_json(ir)?;
88    let canonical_ir_elapsed = started.elapsed();
89    let mut artifacts = vec![Artifact::text(
90        "ir/app-ir.json",
91        canonical_ir,
92        ArtifactKind::CanonicalIr,
93    )];
94    let planned = std::thread::scope(|scope| {
95        let database = scope.spawn(|| timed(|| database::plan(ir)));
96        let backend = scope.spawn(|| timed(|| backend::plan(ir)));
97        let openapi = scope.spawn(|| timed(|| openapi::plan(ir)));
98        let typescript = scope.spawn(|| timed(|| typescript::plan(ir)));
99        let web = scope.spawn(|| timed(|| web::plan(ir)));
100        let modules = scope.spawn(|| timed(|| module_artifact::plan(ir)));
101        let (database_elapsed, database) = join_planner(database, "database")?;
102        let (backend_elapsed, backend) = join_planner(backend, "backend")?;
103        let (openapi_elapsed, openapi) = join_planner(openapi, "OpenAPI")?;
104        let (typescript_elapsed, typescript) = join_planner(typescript, "TypeScript")?;
105        let (web_elapsed, web) = join_planner(web, "Web")?;
106        let (modules_elapsed, modules) = join_planner(modules, "module")?;
107        Ok::<_, CodegenError>((
108            [database?, backend?, openapi?, typescript, web, modules?],
109            PlannerTimings {
110                database: database_elapsed,
111                backend: backend_elapsed,
112                openapi: openapi_elapsed,
113                typescript: typescript_elapsed,
114                web: web_elapsed,
115                modules: modules_elapsed,
116            },
117        ))
118    })?;
119    artifacts.extend(planned.0.into_iter().flatten());
120    let rustfmt = formatting::format_rust_artifacts(&mut artifacts, options.rustfmt_cache)?;
121    artifacts.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
122    ensure_unique_paths(&artifacts)?;
123    Ok(PlanOutput {
124        artifacts,
125        timings: PlanTimings {
126            total: total_started.elapsed(),
127            validation,
128            canonical_ir: canonical_ir_elapsed,
129            planners: planned.1,
130            rustfmt,
131        },
132    })
133}
134
135fn ensure_unique_paths(artifacts: &[Artifact]) -> Result<(), CodegenError> {
136    for pair in artifacts.windows(2) {
137        if pair[0].relative_path == pair[1].relative_path {
138            return Err(CodegenError::new(format!(
139                "multiple generators own `{}`",
140                pair[0].relative_path.display()
141            )));
142        }
143    }
144    Ok(())
145}
146
147pub(crate) fn generated_header(comment: &str) -> String {
148    format!("{comment} @generated by AppStruct. Do not edit manually.\n\n")
149}
150
151pub(crate) fn format_rust(source: &str) -> Result<String, CodegenError> {
152    let syntax = syn::parse_file(source)
153        .map_err(|error| CodegenError::new(format!("generated Rust did not parse: {error}")))?;
154    Ok(format!(
155        "{}{}",
156        generated_header("//"),
157        syntax.into_token_stream()
158    ))
159}
160
161fn join_planner<T>(
162    handle: std::thread::ScopedJoinHandle<'_, T>,
163    name: &str,
164) -> Result<T, CodegenError> {
165    handle
166        .join()
167        .map_err(|_| CodegenError::new(format!("{name} generation worker panicked")))
168}
169
170fn timed<T>(operation: impl FnOnce() -> T) -> (Duration, T) {
171    let started = Instant::now();
172    let result = operation();
173    (started.elapsed(), result)
174}