Skip to main content

appstruct_compiler/
lib.rs

1//! `AppStruct` configuration loading, validation, and normalization.
2
3mod access;
4mod audit;
5mod auth;
6mod extension;
7mod field;
8mod field_options;
9mod file;
10mod jobs;
11mod lint;
12mod loading;
13mod lower;
14mod mail;
15mod module;
16mod naming;
17mod preset;
18mod surface;
19mod tenant;
20mod validation;
21mod yaml;
22
23pub use loading::discover_project;
24pub use preset::{
25    CURRENT_PROJECT_LAYOUT_VERSION, PresetInfo, ProjectLayout, preset_info, project_layout,
26    project_lock,
27};
28
29/// Draft 2020-12 schema for root and domain App Spec YAML documents.
30pub const APP_SPEC_SCHEMA: &str = include_str!("../schema/appstruct.schema.json");
31
32#[derive(Clone, Debug)]
33pub struct CompileReport {
34    pub ir: AppIr,
35    pub diagnostics: Vec<Diagnostic>,
36}
37
38use appstruct_ir::{AppIr, Diagnostic, SourceSpan};
39use std::collections::BTreeMap;
40use std::fs;
41use std::path::{Path, PathBuf};
42
43/// Compile a project root into normalized, deterministically ordered IR.
44///
45/// # Errors
46///
47/// Returns all diagnostics found during path resolution and semantic validation. YAML shape errors
48/// are reported per source before semantic validation starts.
49pub fn compile_project(project_root: &Path) -> Result<AppIr, Vec<Diagnostic>> {
50    compile_project_report(project_root).map(|report| report.ir)
51}
52
53/// Compile a project and retain non-fatal diagnostics for CLI and CI policy.
54///
55/// # Errors
56///
57/// Returns all fatal diagnostics found during loading and semantic validation.
58pub fn compile_project_report(project_root: &Path) -> Result<CompileReport, Vec<Diagnostic>> {
59    let root = canonical_project_root(project_root)?;
60    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
61    let surface_root = surface::decode_root(&root_node)?;
62    let mut diagnostics = validation::validate_root(&surface_root);
63    diagnostics.extend(preset::validate_lock(&root, &surface_root));
64    let (local_modules, module_diagnostics) =
65        module::load_local_modules(&root, &surface_root.module_manifests);
66    if module_diagnostics.is_empty() {
67        diagnostics.extend(preset::validate_local_module_lock(&root, &local_modules));
68    }
69    diagnostics.extend(module_diagnostics);
70    let mut canonical_includes = BTreeMap::<PathBuf, SourceSpan>::new();
71    let mut application = surface::SurfaceDomain::default();
72
73    for include in &surface_root.includes {
74        let include_path = match loading::resolve_include(&root, include) {
75            Ok(path) => path,
76            Err(error) => {
77                diagnostics.push(error);
78                continue;
79            }
80        };
81        if let Some(first_span) =
82            canonical_includes.insert(include_path.clone(), include.span.clone())
83        {
84            diagnostics.push(
85                Diagnostic::error(
86                    "AS1009",
87                    format!("duplicate include `{}`", include.value),
88                    include.span.clone(),
89                )
90                .with_secondary(first_span, "first included here"),
91            );
92            continue;
93        }
94
95        match loading::load_yaml(&root, &include_path)
96            .and_then(|node| surface::decode_domain(&node))
97        {
98            Ok(domain) => application.extend(domain),
99            Err(mut errors) => diagnostics.append(&mut errors),
100        }
101    }
102
103    if !diagnostics.is_empty() {
104        return Err(diagnostics);
105    }
106    let warnings = lint::warnings(&application);
107    lower::build_ir(surface_root, application, local_modules).map(|ir| CompileReport {
108        ir,
109        diagnostics: warnings,
110    })
111}
112
113/// Return the selected preset's effective module configuration after project overrides.
114///
115/// # Errors
116///
117/// Returns root parsing, validation, or preset lock diagnostics.
118pub fn expanded_preset(project_root: &Path) -> Result<Option<String>, Vec<Diagnostic>> {
119    let root = canonical_project_root(project_root)?;
120    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
121    let surface_root = surface::decode_root(&root_node)?;
122    let mut diagnostics = validation::validate_root(&surface_root);
123    diagnostics.extend(preset::validate_lock(&root, &surface_root));
124    if !diagnostics.is_empty() {
125        return Err(diagnostics);
126    }
127    Ok(surface_root
128        .preset
129        .as_ref()
130        .and(surface_root.expanded_modules.as_ref())
131        .map(preset::render_expanded_modules))
132}
133
134/// Build the canonical lock candidate for an explicit project update.
135///
136/// Existing version and digest fields may be stale, but the lock must remain readable so its
137/// template identity can be preserved. The returned source must still pass a complete staged
138/// project compilation before it replaces the current lock.
139///
140/// # Errors
141///
142/// Returns root configuration, lock parsing, or unsupported preset diagnostics.
143pub fn updated_project_lock(project_root: &Path) -> Result<String, Vec<Diagnostic>> {
144    let root = canonical_project_root(project_root)?;
145    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
146    let surface_root = surface::decode_root(&root_node)?;
147    let diagnostics = validation::validate_root(&surface_root);
148    if !diagnostics.is_empty() {
149        return Err(diagnostics);
150    }
151    let (local_modules, module_diagnostics) =
152        module::load_local_modules(&root, &surface_root.module_manifests);
153    if !module_diagnostics.is_empty() {
154        return Err(module_diagnostics);
155    }
156    preset::updated_lock(&root, &surface_root, &local_modules).map_err(|error| vec![error])
157}
158
159fn canonical_project_root(project_root: &Path) -> Result<PathBuf, Vec<Diagnostic>> {
160    fs::canonicalize(project_root).map_err(|error| {
161        vec![Diagnostic::error(
162            "AS1008",
163            format!(
164                "cannot access project root `{}`: {error}",
165                project_root.display()
166            ),
167            loading::synthetic_span(&project_root.to_string_lossy()),
168        )]
169    })
170}