1use 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#[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 #[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 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}