Skip to main content

buildl_lua/
source.rs

1//! [`LuaSource`], the [`DeclarationSource`] that evaluates build files with airsl.
2//!
3//! Its own file because it is the adapter's entry point: it turns one [`BuildFile`] into either
4//! the declarations the file staged or the one failure that stopped it. Every evaluation gets a
5//! fresh engine and a fresh staging buffer, so nothing one file does can reach the next.
6//!
7//! Responsibilities: [`LuaSource`] and its [`DeclarationSource`] implementation.
8//!
9//! Non-responsibilities: deciding which build files to evaluate, and what their declarations
10//! mean. Both are the caller's.
11
12use std::collections::BTreeMap;
13use std::fs;
14use std::io::ErrorKind;
15use std::mem;
16use std::path::PathBuf;
17use std::sync::{Arc, Mutex, PoisonError};
18
19use airsl::Script;
20use buildl_core::{
21    BuildFile, DeclarationSource, Diagnostic, Directory, Discovered, Error, Evaluated,
22    EvaluationFailure, PluginName, Result,
23};
24
25use crate::classify::classify;
26use crate::engine;
27use crate::limits::DeclarationLimits;
28use crate::module::BuildlModule;
29use crate::results::Results;
30use crate::sources::Sources;
31use crate::staging::Staging;
32
33/// Evaluates build files on the airsl embedded runtime, one fresh engine per file.
34///
35/// A build file runs on airsl's minimal Lua surface with no grants, under `limits`. It sees
36/// the `buildl` module table as both `buildl` and `airsstack.buildl`, and the curated modules
37/// `json`, `path`, `regex`, `hash` and `glob` under `airsstack`.
38///
39/// `buildl.use(name)` loads the plugin the source was built with a directory for under that name,
40/// and refuses any other name. A plugin runs under its own environment, narrowed from the build
41/// file's, and every declaration it makes carries the plugin as its origin.
42///
43/// `buildl.discover` declares a discovery target. `buildl.discovered(label)` returns, as a Lua
44/// string, the bytes the map handed to [`evaluate`](DeclarationSource::evaluate) holds for that
45/// target, or `nil`; a relative label resolves against the build file's directory.
46///
47/// `buildl.sources` never lists a file under a directory the source was built to skip. A source
48/// built with the workspace's output and state directories therefore keeps a build file at the
49/// workspace root from seeing what the build wrote.
50///
51/// # Examples
52///
53/// ```
54/// use std::collections::BTreeMap;
55/// use std::fs;
56/// use std::path::PathBuf;
57///
58/// use buildl_core::{BuildFile, DeclarationSource, Directory, Discovered, Evaluated, Provenance};
59/// use buildl_lua::{DeclarationLimits, LuaSource};
60///
61/// let workspace = tempfile::tempdir()?;
62/// let root = fs::canonicalize(workspace.path())?;
63/// fs::write(root.join("build.lua"), "buildl.alias('default', 'app')")?;
64///
65/// let skipped = [Directory::parse("out")?, Directory::parse(".buildl")?];
66/// let source = LuaSource::new(&root, DeclarationLimits::default(), skipped, BTreeMap::new());
67/// let file = BuildFile::new(Provenance::new(PathBuf::from("build.lua"), Directory::root()));
68/// assert!(matches!(
69///     source.evaluate(&file, &Discovered::empty())?,
70///     Evaluated::Staged(staged) if staged.declarations.len() == 1
71/// ));
72/// # Ok::<(), Box<dyn std::error::Error>>(())
73/// ```
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct LuaSource {
76    root: PathBuf,
77    limits: DeclarationLimits,
78    skipped: Vec<Directory>,
79    plugins: BTreeMap<PluginName, PathBuf>,
80}
81
82impl LuaSource {
83    /// A source for the workspace at `root`, evaluating under `limits`, whose `buildl.sources`
84    /// stays out of `skipped` and whose `buildl.use` loads the plugins in `plugins`.
85    ///
86    /// `root` must be the workspace root's canonical, absolute path. `buildl.sources` walks
87    /// beneath it and refuses any directory that resolves outside it.
88    ///
89    /// `skipped` names workspace-relative directories. The walk neither lists, enters nor counts
90    /// anything inside one. Each is matched by its whole path from the workspace root, so `out`
91    /// skips `<root>/out` and not `<root>/lib/out`. A build file whose own directory is a skipped
92    /// directory, or lies inside one, gets an empty list from `buildl.sources`. An empty `skipped`
93    /// skips nothing: the walk then lists the workspace's own output and state directories too.
94    ///
95    /// `plugins` maps each plugin name a build file may use to the directory holding its
96    /// `extension.toml`. The caller has already checked the directories, so this source reads
97    /// them as given. A plugin's `require` stays inside its own directory, however that directory
98    /// is reached.
99    #[must_use]
100    pub fn new(
101        root: impl Into<PathBuf>,
102        limits: DeclarationLimits,
103        skipped: impl IntoIterator<Item = Directory>,
104        plugins: BTreeMap<PluginName, PathBuf>,
105    ) -> Self {
106        Self {
107            root: root.into(),
108            limits,
109            skipped: skipped.into_iter().collect(),
110            plugins,
111        }
112    }
113}
114
115impl DeclarationSource for LuaSource {
116    /// Evaluates `file`; `buildl.discovered` reads `discovered`.
117    ///
118    /// A file that does not exist is [`Evaluated::Absent`].
119    ///
120    /// # Errors
121    ///
122    /// Returns [`Error::Evaluation`] when the file cannot be read, is not UTF-8, does not parse,
123    /// raises, is refused an operation, reaches a ceiling, calls a `buildl` primitive with
124    /// arguments it does not accept, or uses a plugin that is unknown, cyclic, malformed or
125    /// raises. A refusal from a primitive is reported even when the build
126    /// file caught it with `pcall` and carried on.
127    fn evaluate(&self, file: &BuildFile, discovered: &Discovered) -> Result<Evaluated> {
128        let path = self.root.join(file.file());
129        let bytes = match fs::read(&path) {
130            Ok(bytes) => bytes,
131            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Evaluated::Absent),
132            Err(error) => {
133                return Err(failed(
134                    file,
135                    EvaluationFailure::Runtime,
136                    format!("{}: {error}", path.display()),
137                ));
138            }
139        };
140        let Ok(text) = String::from_utf8(bytes) else {
141            return Err(failed(file, EvaluationFailure::Syntax, "not UTF-8 text"));
142        };
143
144        let staging = Arc::new(Mutex::new(Staging::new(self.limits.memory_bytes().get())));
145        let outcome = BuildlModule::new(
146            Arc::clone(&staging),
147            Sources::new(
148                &self.root,
149                file.directory(),
150                self.limits.walk_entries(),
151                &self.skipped,
152            ),
153            Results::new(discovered, file.directory()),
154            &self.root,
155            self.plugins.clone(),
156        )
157        .and_then(|module| engine::build(&self.limits, module))
158        .and_then(|engine| {
159            let chunk = file.file().to_string_lossy().into_owned();
160            engine.eval(&Script::from_source(text, chunk)?)
161        });
162
163        let staged = mem::replace(
164            &mut *staging.lock().unwrap_or_else(PoisonError::into_inner),
165            Staging::new(0),
166        );
167        let staged = staged
168            .finish()
169            .map_err(|(failure, diagnostic)| Error::Evaluation {
170                provenance: file.provenance().clone(),
171                failure,
172                diagnostic,
173            })?;
174        outcome.map_err(|error| failed(file, classify(&error), error.to_string()))?;
175        Ok(Evaluated::Staged(staged))
176    }
177}
178
179fn failed(file: &BuildFile, failure: EvaluationFailure, diagnostic: impl Into<String>) -> Error {
180    Error::Evaluation {
181        provenance: file.provenance().clone(),
182        failure,
183        diagnostic: Diagnostic::new(diagnostic),
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    #![expect(
190        clippy::unwrap_used,
191        clippy::panic,
192        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
193    )]
194
195    use std::collections::BTreeMap;
196    use std::fs;
197    use std::path::{Path, PathBuf};
198
199    use buildl_core::{
200        BuildFile, DeclarationSource, Directory, Discovered, Error, Evaluated, EvaluationFailure,
201        Provenance, StagedItem,
202    };
203
204    use super::LuaSource;
205    use crate::limits::DeclarationLimits;
206
207    fn root_file() -> BuildFile {
208        BuildFile::new(Provenance::new(
209            PathBuf::from("build.lua"),
210            Directory::root(),
211        ))
212    }
213
214    fn workspace(build_lua: &[u8]) -> (tempfile::TempDir, PathBuf) {
215        let dir = tempfile::tempdir().unwrap();
216        let root = fs::canonicalize(dir.path()).unwrap();
217        fs::write(root.join("build.lua"), build_lua).unwrap();
218        (dir, root)
219    }
220
221    fn failure(root: &Path) -> EvaluationFailure {
222        match LuaSource::new(root, DeclarationLimits::default(), [], BTreeMap::new())
223            .evaluate(&root_file(), &Discovered::empty())
224        {
225            Err(Error::Evaluation { failure, .. }) => failure,
226            other => panic!("expected an evaluation failure, got {other:?}"),
227        }
228    }
229
230    #[test]
231    fn a_missing_file_is_absent() {
232        let dir = tempfile::tempdir().unwrap();
233        let source = LuaSource::new(
234            dir.path(),
235            DeclarationLimits::default(),
236            [],
237            BTreeMap::new(),
238        );
239        assert_eq!(
240            source.evaluate(&root_file(), &Discovered::empty()).unwrap(),
241            Evaluated::Absent
242        );
243    }
244
245    #[test]
246    fn a_file_that_is_not_utf8_is_a_syntax_failure() {
247        let (_dir, root) = workspace(b"return '\xff'");
248        assert_eq!(failure(&root), EvaluationFailure::Syntax);
249    }
250
251    #[test]
252    fn a_refusal_caught_by_pcall_is_still_reported() {
253        let (_dir, root) = workspace(b"pcall(buildl.target, 'app', 1)\nreturn 'ok'");
254        assert_eq!(
255            failure(&root),
256            EvaluationFailure::WrongFieldType {
257                field: buildl_core::Written::new("options"),
258            }
259        );
260    }
261
262    #[test]
263    fn an_uncaught_refusal_is_reported_as_the_recorded_failure() {
264        let (_dir, root) = workspace(b"buildl.target('app', 1)");
265        assert_eq!(
266            failure(&root),
267            EvaluationFailure::WrongFieldType {
268                field: buildl_core::Written::new("options"),
269            }
270        );
271    }
272
273    #[test]
274    fn a_build_file_that_is_a_directory_is_a_runtime_failure() {
275        let dir = tempfile::tempdir().unwrap();
276        let root = fs::canonicalize(dir.path()).unwrap();
277        fs::create_dir(root.join("build.lua")).unwrap();
278        assert_eq!(failure(&root), EvaluationFailure::Runtime);
279    }
280
281    #[test]
282    fn the_source_can_be_shared_across_threads() {
283        const fn assert_send_sync<T: Send + Sync>() {}
284        assert_send_sync::<LuaSource>();
285    }
286
287    #[test]
288    fn an_airsl_failure_is_classified() {
289        let (_dir, root) = workspace(b"error('boom')");
290        assert_eq!(failure(&root), EvaluationFailure::Runtime);
291    }
292
293    #[test]
294    fn evaluation_failures_carry_the_file_s_provenance() {
295        let (_dir, root) = workspace(b"return (");
296        let error = LuaSource::new(&root, DeclarationLimits::default(), [], BTreeMap::new())
297            .evaluate(&root_file(), &Discovered::empty())
298            .unwrap_err();
299        assert!(
300            error.to_string().starts_with("build.lua: syntax error: "),
301            "{error}"
302        );
303    }
304
305    #[test]
306    fn a_source_keeps_the_directories_it_was_built_with() {
307        let skipped = [
308            Directory::parse("out").unwrap(),
309            Directory::parse(".buildl").unwrap(),
310        ];
311        let source = LuaSource::new(
312            "/ws",
313            DeclarationLimits::default(),
314            skipped.clone(),
315            BTreeMap::new(),
316        );
317        assert_eq!(source.skipped, skipped);
318        assert_eq!(
319            LuaSource::new("/ws", DeclarationLimits::default(), [], BTreeMap::new()).skipped,
320            []
321        );
322    }
323
324    #[test]
325    fn a_skipped_directory_is_kept_out_of_the_sources_a_file_lists() {
326        let (_dir, root) = workspace(
327            b"buildl.target('app', { run = { 'cc' }, inputs = buildl.sources('**/*.c') })",
328        );
329        fs::create_dir_all(root.join("out")).unwrap();
330        fs::write(root.join("out/o.c"), "").unwrap();
331        fs::write(root.join("a.c"), "").unwrap();
332        let Evaluated::Staged(staged) = LuaSource::new(
333            &root,
334            DeclarationLimits::default(),
335            [Directory::parse("out").unwrap()],
336            BTreeMap::new(),
337        )
338        .evaluate(&root_file(), &Discovered::empty())
339        .unwrap() else {
340            panic!("the build file exists");
341        };
342        let StagedItem::Target(target) = &staged.declarations[0].item else {
343            panic!("the build file declares a target");
344        };
345        assert_eq!(target.inputs.len(), 1);
346        assert_eq!(target.inputs[0].as_written(), "a.c");
347    }
348
349    #[test]
350    fn a_staged_file_is_returned_with_its_declarations() {
351        let (_dir, root) = workspace(b"buildl.subdir('lib')\nbuildl.alias('default', 'app')");
352        let Evaluated::Staged(staged) =
353            LuaSource::new(&root, DeclarationLimits::default(), [], BTreeMap::new())
354                .evaluate(&root_file(), &Discovered::empty())
355                .unwrap()
356        else {
357            panic!("the build file exists");
358        };
359        assert_eq!(staged.declarations.len(), 1);
360        assert_eq!(staged.subdirs.len(), 1);
361    }
362}