Skip to main content

ruxla_build/
lib.rs

1//! Compiles environments exported from JAX into the Rust modules of a
2//! crate, from its build script.
3//!
4//! `ruxla.export_env` (or `python -m ruxla.export`) writes each environment
5//! to a directory (`manifest.json`, `reset.json`, `step.json`, ...). A build
6//! script imports every such directory under one root and generates, in
7//! `$OUT_DIR/ruxla_envs.rs`, a module per environment with a unit struct
8//! `Env` that implements [`CompiledEnv`](ruxla_env::compiled::CompiledEnv),
9//! plus `MODULES` (the module names) and `visit` (an environment by name,
10//! through a [`Visitor`](ruxla_env::compiled::Visitor)).
11//!
12//! ```toml
13//! [dependencies]
14//! ruxla-env = "..."
15//! ruxla-codegen = "..."   # the generated code refers to these three crates
16//! ruxla-ir = "..."
17//!
18//! [build-dependencies]
19//! ruxla-build = "..."
20//!
21//! # The code generator runs in the build script: optimize it.
22//! [profile.dev.build-override]
23//! opt-level = 3
24//! [profile.release.build-override]
25//! opt-level = 3
26//! ```
27//!
28//! ```ignore
29//! // build.rs
30//! fn main() {
31//!     ruxla_build::compile_envs("envs");
32//! }
33//! ```
34//!
35//! ```ignore
36//! // lib.rs
37//! ruxla_env::include_envs!();
38//!
39//! // gymnax_cartpole_v1::Env, MODULES, visit(...)
40//! ```
41//!
42//! A `cdylib` that also has `ruxla_env::export_vec_envs!();` can be loaded by
43//! programs built separately, such as `ruxla.compile_env` in Python
44//! (`ruxla_env::dylib`).
45
46use std::fmt::Write as _;
47use std::path::{Path, PathBuf};
48
49pub use ruxla_codegen::Options;
50use ruxla_env::compiled::generate_from_functions;
51use ruxla_env::jax_env::load_functions;
52
53/// The file that [`Builder::compile`] writes in `$OUT_DIR`.
54pub const OUT_FILE: &str = "ruxla_envs.rs";
55
56/// Compiles every exported environment under `dir` (see [`Builder`]):
57/// `RUXLA_JAX_ENVS` replaces `dir` and `RUXLA_JAX_ENVS_ONLY` selects modules.
58/// Returns the compiled modules.
59///
60/// # Panics
61///
62/// Panics outside a build script (without `OUT_DIR`).
63pub fn compile_envs(dir: impl AsRef<Path>) -> Vec<String> {
64    Builder::from_env(dir).compile()
65}
66
67/// The compilation of a directory of exported environments.
68#[derive(Clone, Debug)]
69pub struct Builder {
70    dir: PathBuf,
71    only: Option<Vec<String>>,
72    options: Options,
73}
74
75impl Builder {
76    /// The environments under `dir` (each subdirectory with a
77    /// `manifest.json`), compiled with fast math.
78    pub fn new(dir: impl AsRef<Path>) -> Self {
79        Self {
80            dir: dir.as_ref().to_path_buf(),
81            only: None,
82            options: Options {
83                fast_math: true,
84                ..Options::default()
85            },
86        }
87    }
88
89    /// [`Builder::new`] with `RUXLA_JAX_ENVS` in place of `dir` if it is set,
90    /// and the modules of `RUXLA_JAX_ENVS_ONLY` (separated by commas) only.
91    /// A relative `dir` is taken from `CARGO_MANIFEST_DIR`.
92    pub fn from_env(dir: impl AsRef<Path>) -> Self {
93        println!("cargo::rerun-if-env-changed=RUXLA_JAX_ENVS");
94        println!("cargo::rerun-if-env-changed=RUXLA_JAX_ENVS_ONLY");
95        let dir = match std::env::var_os("RUXLA_JAX_ENVS") {
96            Some(d) => PathBuf::from(d),
97            None => match std::env::var_os("CARGO_MANIFEST_DIR") {
98                Some(m) if dir.as_ref().is_relative() => PathBuf::from(m).join(dir),
99                _ => dir.as_ref().to_path_buf(),
100            },
101        };
102        let mut builder = Self::new(dir);
103        if let Ok(only) = std::env::var("RUXLA_JAX_ENVS_ONLY") {
104            builder = builder.only(only.split(',').map(str::trim));
105        }
106        builder
107    }
108
109    /// Compiles only these modules.
110    pub fn only<S: Into<String>>(mut self, modules: impl IntoIterator<Item = S>) -> Self {
111        self.only = Some(modules.into_iter().map(Into::into).collect());
112        self
113    }
114
115    /// The options of the code generator.
116    pub fn options(mut self, options: Options) -> Self {
117        self.options = options;
118        self
119    }
120
121    /// The modules to compile: the subdirectories with a manifest, sorted.
122    pub fn modules(&self) -> Vec<String> {
123        let Ok(entries) = std::fs::read_dir(&self.dir) else {
124            return Vec::new();
125        };
126        let mut out: Vec<String> = entries
127            .filter_map(Result::ok)
128            .filter(|e| e.path().join("manifest.json").is_file())
129            .filter_map(|e| e.file_name().to_str().map(str::to_string))
130            .filter(|m| self.only.as_ref().is_none_or(|o| o.contains(m)))
131            .collect();
132        out.sort();
133        out
134    }
135
136    /// Generates the code of every module: `(code, compiled modules,
137    /// failures)`. A module that fails to import or generate is left out,
138    /// with its error among the failures.
139    pub fn generate(&self) -> (String, Vec<String>, Vec<(String, String)>) {
140        let mut modules = Vec::new();
141        let mut failures = Vec::new();
142        let mut code = String::new();
143        for module in self.modules() {
144            let generated = load_functions(&self.dir.join(&module))
145                .map_err(|e| e.to_string())
146                .and_then(|f| {
147                    generate_from_functions(&f, &module, &self.options).map_err(|e| e.to_string())
148                });
149            match generated {
150                Ok(g) => {
151                    writeln!(code, "{g}").expect("write to a string");
152                    modules.push(module);
153                }
154                Err(e) => failures.push((module, e)),
155            }
156        }
157        code.push_str(&footer(&modules, &self.dir));
158        (code, modules, failures)
159    }
160
161    /// Generates the code (see [`Builder::generate`]) into
162    /// `$OUT_DIR/ruxla_envs.rs` for `ruxla_env::include_envs!`, tells Cargo to rerun
163    /// when the exports change, and warns about modules that failed. Returns
164    /// the compiled modules.
165    ///
166    /// # Panics
167    ///
168    /// Panics outside a build script (without `OUT_DIR`) or if the file
169    /// cannot be written.
170    pub fn compile(&self) -> Vec<String> {
171        println!("cargo::rerun-if-changed={}", self.dir.display());
172        for module in self.modules() {
173            for f in [
174                "manifest.json",
175                "reset.json",
176                "step.json",
177                "legal_action_mask.json",
178            ] {
179                let path = self.dir.join(&module).join(f);
180                println!("cargo::rerun-if-changed={}", path.display());
181            }
182        }
183        let (code, modules, failures) = self.generate();
184        for (module, e) in failures {
185            println!("cargo::warning={module}: not compiled: {e}");
186        }
187        let out =
188            PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR (run from a build script)"))
189                .join(OUT_FILE);
190        std::fs::write(&out, code)
191            .unwrap_or_else(|e| panic!("cannot write {}: {e}", out.display()));
192        modules
193    }
194}
195
196/// `MODULES`, `DATA_DIR`, and `visit` of the generated code.
197fn footer(modules: &[String], dir: &Path) -> String {
198    let mut code = String::new();
199    let w = &mut code;
200    writeln!(w, "/// The modules of the compiled environments, sorted.").unwrap();
201    writeln!(w, "pub const MODULES: &[&str] = &{modules:?};").unwrap();
202    writeln!(
203        w,
204        "/// The directory of the exported environments at build time."
205    )
206    .unwrap();
207    writeln!(
208        w,
209        "pub const DATA_DIR: &str = {:?};",
210        dir.display().to_string()
211    )
212    .unwrap();
213    writeln!(
214        w,
215        "/// Calls `visitor` with the environment of `module`, if it was compiled."
216    )
217    .unwrap();
218    writeln!(
219        w,
220        "pub fn visit<V: ::ruxla_env::compiled::Visitor>(module: &str, visitor: &mut V) -> Option<V::Output> {{"
221    )
222    .unwrap();
223    if modules.is_empty() {
224        writeln!(w, "    let _ = (module, visitor);\n    None").unwrap();
225    } else {
226        writeln!(w, "    match module {{").unwrap();
227        for m in modules {
228            writeln!(
229                w,
230                "        {m:?} => Some(visitor.visit(module, &{m}::Env)),"
231            )
232            .unwrap();
233        }
234        writeln!(w, "        _ => None,\n    }}").unwrap();
235    }
236    writeln!(w, "}}").unwrap();
237    code
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn no_exports_give_an_empty_crate() {
246        let b = Builder::new("/nonexistent/ruxla-build-test");
247        assert!(b.modules().is_empty());
248        let (code, modules, failures) = b.generate();
249        assert!(modules.is_empty() && failures.is_empty());
250        assert!(code.contains("pub const MODULES: &[&str] = &[];"));
251        assert!(code.contains("None"));
252    }
253
254    #[test]
255    fn only_filters_modules() {
256        let dir = std::env::temp_dir().join(format!("ruxla-build-test-{}", std::process::id()));
257        for m in ["a_env", "b_env"] {
258            std::fs::create_dir_all(dir.join(m)).unwrap();
259            std::fs::write(dir.join(m).join("manifest.json"), "{}").unwrap();
260        }
261        std::fs::create_dir_all(dir.join("not_an_env")).unwrap();
262        assert_eq!(Builder::new(&dir).modules(), ["a_env", "b_env"]);
263        assert_eq!(Builder::new(&dir).only(["b_env"]).modules(), ["b_env"]);
264        // An invalid manifest is a failure, not a panic.
265        let (_, modules, failures) = Builder::new(&dir).generate();
266        assert!(modules.is_empty());
267        assert_eq!(failures.len(), 2);
268        std::fs::remove_dir_all(dir).unwrap();
269    }
270}