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, IgnoreRules, 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. Nor does it list a path the source's
50/// [`IgnoreRules`] report ignored, an ignore file included.
51///
52/// # Examples
53///
54/// ```
55/// use std::collections::BTreeMap;
56/// use std::fs;
57/// use std::path::PathBuf;
58///
59/// use buildl_core::{
60///     BuildFile, DeclarationSource, Directory, Discovered, Evaluated, NothingIgnored, Provenance,
61/// };
62/// use buildl_lua::{DeclarationLimits, LuaSource};
63///
64/// let workspace = tempfile::tempdir()?;
65/// let root = fs::canonicalize(workspace.path())?;
66/// fs::write(root.join("build.lua"), "buildl.alias('default', 'app')")?;
67///
68/// let skipped = [Directory::parse("out")?, Directory::parse(".buildl")?];
69/// let source = LuaSource::new(
70///     &root,
71///     DeclarationLimits::default(),
72///     skipped,
73///     NothingIgnored,
74///     BTreeMap::new(),
75/// );
76/// let file = BuildFile::new(Provenance::new(PathBuf::from("build.lua"), Directory::root()));
77/// assert!(matches!(
78///     source.evaluate(&file, &Discovered::empty())?,
79///     Evaluated::Staged(staged) if staged.declarations.len() == 1
80/// ));
81/// # Ok::<(), Box<dyn std::error::Error>>(())
82/// ```
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct LuaSource<I> {
85    root: PathBuf,
86    limits: DeclarationLimits,
87    skipped: Vec<Directory>,
88    ignore: I,
89    plugins: BTreeMap<PluginName, PathBuf>,
90}
91
92impl<I: IgnoreRules + Clone + Send + 'static> LuaSource<I> {
93    /// A source for the workspace at `root`, evaluating under `limits`, whose `buildl.sources`
94    /// stays out of `skipped` and of every path `ignore` reports ignored, and whose `buildl.use`
95    /// loads the plugins in `plugins`.
96    ///
97    /// `root` must be the workspace root's canonical, absolute path. `buildl.sources` walks
98    /// beneath it and refuses any directory that resolves outside it.
99    ///
100    /// `skipped` names workspace-relative directories. The walk neither lists, enters nor counts
101    /// anything inside one. Each is matched by its whole path from the workspace root, so `out`
102    /// skips `<root>/out` and not `<root>/lib/out`. A build file whose own directory is a skipped
103    /// directory, or lies inside one, gets an empty list from `buildl.sources`. An empty `skipped`
104    /// skips nothing: the walk then lists the workspace's own output and state directories too.
105    ///
106    /// `ignore` is asked about each entry the walk meets, by its workspace-relative path and
107    /// kind, after the skipped directories are ruled out; an entry whose workspace-relative path
108    /// is not UTF-8 is not asked. The walk neither lists, enters nor counts an entry it reports
109    /// ignored, and a build file whose own directory is ignored gets an empty list. An error from
110    /// `ignore` stops the walk and refuses the `buildl.sources` call with the error's text. Pass [`NothingIgnored`](buildl_core::NothingIgnored) for a workspace
111    /// with no ignore files.
112    ///
113    /// `plugins` maps each plugin name a build file may use to the directory holding its
114    /// `extension.toml`. The caller has already checked the directories, so this source reads
115    /// them as given. A plugin's `require` stays inside its own directory, however that directory
116    /// is reached.
117    #[must_use]
118    pub fn new(
119        root: impl Into<PathBuf>,
120        limits: DeclarationLimits,
121        skipped: impl IntoIterator<Item = Directory>,
122        ignore: I,
123        plugins: BTreeMap<PluginName, PathBuf>,
124    ) -> Self {
125        Self {
126            root: root.into(),
127            limits,
128            skipped: skipped.into_iter().collect(),
129            ignore,
130            plugins,
131        }
132    }
133}
134
135impl<I: IgnoreRules + Clone + Send + 'static> DeclarationSource for LuaSource<I> {
136    /// Evaluates `file`; `buildl.discovered` reads `discovered`.
137    ///
138    /// A file that does not exist is [`Evaluated::Absent`].
139    ///
140    /// # Errors
141    ///
142    /// Returns [`Error::Evaluation`] when the file cannot be read, is not UTF-8, does not parse,
143    /// raises, is refused an operation, reaches a ceiling, calls a `buildl` primitive with
144    /// arguments it does not accept, or uses a plugin that is unknown, cyclic, malformed or
145    /// raises. A refusal from a primitive is reported even when the build
146    /// file caught it with `pcall` and carried on.
147    fn evaluate(&self, file: &BuildFile, discovered: &Discovered) -> Result<Evaluated> {
148        let path = self.root.join(file.file());
149        let bytes = match fs::read(&path) {
150            Ok(bytes) => bytes,
151            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Evaluated::Absent),
152            Err(error) => {
153                return Err(failed(
154                    file,
155                    EvaluationFailure::Runtime,
156                    format!("{}: {error}", path.display()),
157                ));
158            }
159        };
160        let Ok(text) = String::from_utf8(bytes) else {
161            return Err(failed(file, EvaluationFailure::Syntax, "not UTF-8 text"));
162        };
163
164        let staging = Arc::new(Mutex::new(Staging::new(self.limits.memory_bytes().get())));
165        let outcome = BuildlModule::new(
166            Arc::clone(&staging),
167            Sources::new(
168                &self.root,
169                file.directory(),
170                self.limits.walk_entries(),
171                &self.skipped,
172                self.ignore.clone(),
173            ),
174            Results::new(discovered, file.directory()),
175            &self.root,
176            self.plugins.clone(),
177        )
178        .and_then(|module| engine::build(&self.limits, module))
179        .and_then(|engine| {
180            let chunk = file.file().to_string_lossy().into_owned();
181            engine.eval(&Script::from_source(text, chunk)?)
182        });
183
184        let staged = mem::replace(
185            &mut *staging.lock().unwrap_or_else(PoisonError::into_inner),
186            Staging::new(0),
187        );
188        let staged = staged
189            .finish()
190            .map_err(|(failure, diagnostic)| Error::Evaluation {
191                provenance: file.provenance().clone(),
192                failure,
193                diagnostic,
194            })?;
195        outcome.map_err(|error| failed(file, classify(&error), error.to_string()))?;
196        Ok(Evaluated::Staged(staged))
197    }
198}
199
200fn failed(file: &BuildFile, failure: EvaluationFailure, diagnostic: impl Into<String>) -> Error {
201    Error::Evaluation {
202        provenance: file.provenance().clone(),
203        failure,
204        diagnostic: Diagnostic::new(diagnostic),
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    #![expect(
211        clippy::unwrap_used,
212        clippy::panic,
213        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
214    )]
215
216    use std::collections::BTreeMap;
217    use std::fs;
218    use std::path::{Path, PathBuf};
219
220    use buildl_core::{
221        BuildFile, DeclarationSource, Directory, Discovered, Error, Evaluated, EvaluationFailure,
222        NothingIgnored, Provenance, StagedItem,
223    };
224
225    use super::LuaSource;
226    use crate::limits::DeclarationLimits;
227
228    fn root_file() -> BuildFile {
229        BuildFile::new(Provenance::new(
230            PathBuf::from("build.lua"),
231            Directory::root(),
232        ))
233    }
234
235    fn workspace(build_lua: &[u8]) -> (tempfile::TempDir, PathBuf) {
236        let dir = tempfile::tempdir().unwrap();
237        let root = fs::canonicalize(dir.path()).unwrap();
238        fs::write(root.join("build.lua"), build_lua).unwrap();
239        (dir, root)
240    }
241
242    fn failure(root: &Path) -> EvaluationFailure {
243        match LuaSource::new(
244            root,
245            DeclarationLimits::default(),
246            [],
247            NothingIgnored,
248            BTreeMap::new(),
249        )
250        .evaluate(&root_file(), &Discovered::empty())
251        {
252            Err(Error::Evaluation { failure, .. }) => failure,
253            other => panic!("expected an evaluation failure, got {other:?}"),
254        }
255    }
256
257    #[test]
258    fn a_missing_file_is_absent() {
259        let dir = tempfile::tempdir().unwrap();
260        let source = LuaSource::new(
261            dir.path(),
262            DeclarationLimits::default(),
263            [],
264            NothingIgnored,
265            BTreeMap::new(),
266        );
267        assert_eq!(
268            source.evaluate(&root_file(), &Discovered::empty()).unwrap(),
269            Evaluated::Absent
270        );
271    }
272
273    #[test]
274    fn a_file_that_is_not_utf8_is_a_syntax_failure() {
275        let (_dir, root) = workspace(b"return '\xff'");
276        assert_eq!(failure(&root), EvaluationFailure::Syntax);
277    }
278
279    #[test]
280    fn a_refusal_caught_by_pcall_is_still_reported() {
281        let (_dir, root) = workspace(b"pcall(buildl.target, 'app', 1)\nreturn 'ok'");
282        assert_eq!(
283            failure(&root),
284            EvaluationFailure::WrongFieldType {
285                field: buildl_core::Written::new("options"),
286            }
287        );
288    }
289
290    #[test]
291    fn an_uncaught_refusal_is_reported_as_the_recorded_failure() {
292        let (_dir, root) = workspace(b"buildl.target('app', 1)");
293        assert_eq!(
294            failure(&root),
295            EvaluationFailure::WrongFieldType {
296                field: buildl_core::Written::new("options"),
297            }
298        );
299    }
300
301    #[test]
302    fn a_build_file_that_is_a_directory_is_a_runtime_failure() {
303        let dir = tempfile::tempdir().unwrap();
304        let root = fs::canonicalize(dir.path()).unwrap();
305        fs::create_dir(root.join("build.lua")).unwrap();
306        assert_eq!(failure(&root), EvaluationFailure::Runtime);
307    }
308
309    #[test]
310    fn the_source_can_be_shared_across_threads() {
311        const fn assert_send_sync<T: Send + Sync>() {}
312        assert_send_sync::<LuaSource<NothingIgnored>>();
313    }
314
315    #[test]
316    fn an_airsl_failure_is_classified() {
317        let (_dir, root) = workspace(b"error('boom')");
318        assert_eq!(failure(&root), EvaluationFailure::Runtime);
319    }
320
321    #[test]
322    fn evaluation_failures_carry_the_file_s_provenance() {
323        let (_dir, root) = workspace(b"return (");
324        let error = LuaSource::new(
325            &root,
326            DeclarationLimits::default(),
327            [],
328            NothingIgnored,
329            BTreeMap::new(),
330        )
331        .evaluate(&root_file(), &Discovered::empty())
332        .unwrap_err();
333        assert!(
334            error.to_string().starts_with("build.lua: syntax error: "),
335            "{error}"
336        );
337    }
338
339    #[test]
340    fn a_source_keeps_the_directories_it_was_built_with() {
341        let skipped = [
342            Directory::parse("out").unwrap(),
343            Directory::parse(".buildl").unwrap(),
344        ];
345        let source = LuaSource::new(
346            "/ws",
347            DeclarationLimits::default(),
348            skipped.clone(),
349            NothingIgnored,
350            BTreeMap::new(),
351        );
352        assert_eq!(source.skipped, skipped);
353        assert_eq!(
354            LuaSource::new(
355                "/ws",
356                DeclarationLimits::default(),
357                [],
358                NothingIgnored,
359                BTreeMap::new()
360            )
361            .skipped,
362            []
363        );
364    }
365
366    #[test]
367    fn a_skipped_directory_is_kept_out_of_the_sources_a_file_lists() {
368        let (_dir, root) = workspace(
369            b"buildl.target('app', { run = { 'cc' }, inputs = buildl.sources('**/*.c') })",
370        );
371        fs::create_dir_all(root.join("out")).unwrap();
372        fs::write(root.join("out/o.c"), "").unwrap();
373        fs::write(root.join("a.c"), "").unwrap();
374        let Evaluated::Staged(staged) = LuaSource::new(
375            &root,
376            DeclarationLimits::default(),
377            [Directory::parse("out").unwrap()],
378            NothingIgnored,
379            BTreeMap::new(),
380        )
381        .evaluate(&root_file(), &Discovered::empty())
382        .unwrap() else {
383            panic!("the build file exists");
384        };
385        let StagedItem::Target(target) = &staged.declarations[0].item else {
386            panic!("the build file declares a target");
387        };
388        assert_eq!(target.inputs.len(), 1);
389        assert_eq!(target.inputs[0].as_written(), "a.c");
390    }
391
392    #[test]
393    fn a_staged_file_is_returned_with_its_declarations() {
394        let (_dir, root) = workspace(b"buildl.subdir('lib')\nbuildl.alias('default', 'app')");
395        let Evaluated::Staged(staged) = LuaSource::new(
396            &root,
397            DeclarationLimits::default(),
398            [],
399            NothingIgnored,
400            BTreeMap::new(),
401        )
402        .evaluate(&root_file(), &Discovered::empty())
403        .unwrap() else {
404            panic!("the build file exists");
405        };
406        assert_eq!(staged.declarations.len(), 1);
407        assert_eq!(staged.subdirs.len(), 1);
408    }
409}