ctb_formats_stagel/
convert.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! StageL source conversion and bootstrap build utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub fn run_stagel_bootstrap_convert(
30    debug_build: bool,
31    typecheck_build: bool,
32    cache_dir: Option<&std::path::Path>,
33    input_file: &std::path::Path,
34    target_lang: &str,
35) -> Result<Vec<u8>> {
36    let input_bytes = std::fs::read(input_file).with_context(|| {
37        format!("Failed to read input file: {input_file:?}")
38    })?;
39
40    // Reason for fallback: default module stem name "input" used if file_stem is invalid UTF-8 or absent.
41    let filename = input_file
42        .file_stem()
43        .and_then(|s| s.to_str())
44        .unwrap_or("input");
45
46    let do_convert = || -> Result<Vec<u8>> {
47        let parsed = crate::parse::parse(&input_bytes, filename)?;
48        let codegen_out = crate::codegen::codegen(
49            &parsed,
50            target_lang,
51            debug_build,
52            typecheck_build,
53        )?;
54        Ok(codegen_out)
55    };
56
57    if let Some(cache_dir) = cache_dir {
58        use sha2::{Digest, Sha512};
59        let sha512_hex = |data: &[u8]| -> String {
60            let mut hasher = Sha512::new();
61            hasher.update(data);
62            bin2hex(hasher.finalize())
63        };
64
65        let exe_path = std::env::current_exe()?;
66        let exe_bytes = std::fs::read(&exe_path)?;
67        let exe_hash = sha512_hex(&exe_bytes);
68
69        let input_hash = sha512_hex(&input_bytes);
70
71        let debug_flag = if debug_build { "--debug" } else { "--no-debug" };
72        let typecheck_flag = if typecheck_build {
73            "--runtime-type-checks"
74        } else {
75            "--no-runtime-type-checks"
76        };
77        let config_str =
78            format!("{debug_flag}:{typecheck_flag}:{target_lang}\n");
79        let config_hash = sha512_hex(config_str.as_bytes());
80
81        let hash_a = input_hash.get(0..1).context("Invalid hash")?;
82        let hash_b = input_hash.get(1..2).context("Invalid hash")?;
83        let hash_c = input_hash.get(2..3).context("Invalid hash")?;
84
85        let cache_subdir = cache_dir.join(format!(
86            ".stagel-cache/1/{exe_hash}/{exe_hash}/{config_hash}/{hash_a}/{hash_b}/{hash_c}"
87        ));
88
89        std::fs::create_dir_all(&cache_subdir)?;
90        let cache_file = cache_subdir.join(&input_hash);
91
92        if cache_file.exists() {
93            let cached_bytes = std::fs::read(&cache_file)?;
94            return Ok(cached_bytes);
95        }
96
97        let output_bytes = do_convert()?;
98        let tmp_file = cache_subdir.join(format!("{input_hash}.tmp"));
99        std::fs::write(&tmp_file, &output_bytes)?;
100        std::fs::rename(&tmp_file, &cache_file)?;
101
102        Ok(output_bytes)
103    } else {
104        do_convert()
105    }
106}