1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//! Build scripts for Stak Scheme.

mod error;

pub use error::BuildError;
use glob::{glob, Paths};
use stak_compiler::compile_r7rs;
use std::{
    env,
    error::Error,
    path::{Path, PathBuf},
};
use tokio::{
    fs::{create_dir_all, read_to_string, write},
    runtime::Runtime,
    spawn,
};

/// Builds R7RS source files into bytecode target files.
pub fn build_r7rs() -> Result<(), Box<dyn Error>> {
    let runtime = Runtime::new()?;
    let _ = runtime.enter();

    runtime.block_on(build(glob("**/*.scm")?))?;

    Ok(())
}

async fn build(paths: Paths) -> Result<(), Box<dyn Error>> {
    let out_directory_variable = env::var("OUT_DIR")?;
    let out_directory = Path::new(&out_directory_variable);

    let mut handles = vec![];

    for path in paths {
        let path = path?;
        let out_path = out_directory.join(&path);

        println!("cargo::rerun-if-changed={}", path.display());

        handles.push(spawn(compile(path, out_path)))
    }

    for handle in handles {
        handle.await??;
    }

    Ok(())
}

async fn compile(src_path: PathBuf, out_path: PathBuf) -> Result<(), BuildError> {
    let string = read_to_string(src_path).await?;
    let mut buffer = vec![];

    compile_r7rs(string.as_bytes(), &mut buffer)?;

    if let Some(path) = out_path.parent() {
        create_dir_all(path).await?;
    }

    write(out_path, &buffer).await?;

    Ok(())
}