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, 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)]
75pub struct LuaSource {
76 root: PathBuf,
77 limits: DeclarationLimits,
78 skipped: Vec<Directory>,
79 plugins: BTreeMap<PluginName, PathBuf>,
80}
81
82impl LuaSource {
83 #[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 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}