1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use std::path::Path;
use miette::{Diagnostic, NamedSource, SourceOffset};
use mlua::Lua;
use thiserror::Error;
const FENNEL_LUA: &str = include_str!("../vendor/fennel.lua");
/// Embedded Fennel stdlib source — exposed as `(require :quire.stdlib)`
/// to user pipelines. Shipping helpers here keeps the runtime kernel
/// (`sh`/`secret`/`jobs`) small while letting common recipes live in
/// Fennel where they're easier to evolve.
const STDLIB_FNL: &str = include_str!("ci/stdlib.fnl");
/// Error kinds from the Fennel loader.
#[derive(Debug, Error, Diagnostic)]
pub enum FennelError {
#[error(transparent)]
#[diagnostic(code(fennel::io))]
Io(#[from] std::io::Error),
#[error("internal fennel error: {0}")]
#[diagnostic(code(fennel::internal))]
Internal(#[from] mlua::Error),
/// Fennel/Lua evaluation failed. `message` is pre-formatted as
/// `"{name}: {lua_error}"` so plain `Display` carries the full
/// diagnostic (suitable for tracing/Sentry). The `#[source]`
/// chain is kept so structured tools (and miette's `╰─▶` line)
/// can still walk to the underlying `mlua::Error`.
#[error("{message}")]
#[diagnostic(code(fennel::eval))]
Eval {
message: String,
#[source_code]
source_code: NamedSource<String>,
#[label("here")]
label: Option<SourceOffset>,
#[source]
source: Box<mlua::Error>,
},
/// Result couldn't be deserialized into the requested type.
/// `message` is pre-formatted as `"{name}: {deser_error}"`; see
/// `Eval` for the rationale.
#[error("{message}")]
#[diagnostic(code(fennel::type_mismatch))]
TypeMismatch {
message: String,
#[source]
source: Box<mlua::Error>,
},
}
/// Owns a Lua VM with the Fennel compiler registered as a module.
///
/// Constructed once and reused across `load_string` / `load_file` calls.
pub struct Fennel {
lua: Lua,
}
impl Fennel {
/// Create a new Fennel instance.
///
/// Loads the vendored `fennel.lua` into a fresh Lua VM and registers it
/// as the `"fennel"` global so `fennel.eval` is available for compiling
/// Fennel source.
pub fn new() -> Result<Self, FennelError> {
// Load all standard libraries including debug, which Fennel
// requires internally (traceback, getinfo). The debug library is
// marked unsafe by mlua because it can break Lua sandboxing, but
// we only run trusted, vendored Fennel code in this VM.
let lua = unsafe { Lua::unsafe_new() };
// Load fennel.lua. The file returns its module table directly.
let fennel_module: mlua::Table = lua.load(FENNEL_LUA).set_name("fennel.lua").eval()?;
lua.globals().set("fennel", fennel_module)?;
// Seed a placeholder `quire.ci` module exposing only an empty
// `runtime` stub. The stub is the canonical runtime table:
// `RuntimeHandle::install` mutates it in place and `uninstall`
// clears it. `registration::register` overwrites the rest of
// `quire.ci` (job/image) but carries this same stub
// forward as the new module's `runtime` field, so references
// captured before, during, and after registration all point at
// the same Lua table. There is no `quire.runtime` module — all
// access flows through `(require :quire.ci) → .runtime`.
let stub: mlua::Table = lua.create_table()?;
let placeholder: mlua::Table = lua.create_table()?;
placeholder.set("runtime", stub)?;
let package: mlua::Table = lua.globals().get("package")?;
let loaded: mlua::Table = package.get("loaded")?;
loaded.set("quire.ci", placeholder)?;
let f = Self { lua };
f.preload_stdlib()?;
Ok(f)
}
/// Compile the embedded `quire.stdlib` and register it in
/// `package.loaded` so `(require :quire.stdlib)` returns the
/// module table without hitting the filesystem.
fn preload_stdlib(&self) -> Result<(), FennelError> {
let module = self.eval_raw(STDLIB_FNL, "quire.stdlib", |_| Ok(()))?;
let package: mlua::Table = self.lua.globals().get("package")?;
let loaded: mlua::Table = package.get("loaded")?;
loaded.set("quire.stdlib", module)?;
Ok(())
}
/// Borrow the underlying Lua VM. Useful for callers that need to
/// `to_value` / `from_value` against the same VM the Fennel script
/// ran in.
pub fn lua(&self) -> &Lua {
&self.lua
}
/// Compile and evaluate a Fennel source string, returning the raw
/// Lua value.
///
/// `setup` is called before evaluation and can inject globals or
/// modify the VM.
///
/// `name` is used as the Lua source name (for tracebacks) and in
/// miette error messages.
pub fn eval_raw(
&self,
source: &str,
name: &str,
setup: impl Fn(&Lua) -> mlua::Result<()>,
) -> Result<mlua::Value, FennelError> {
setup(&self.lua)?;
let fennel: mlua::Table = self.lua.globals().get("fennel")?;
let eval: mlua::Function = fennel.get("eval")?;
let opts = self.lua.create_table()?;
opts.set("filename", name)?;
// Align Lua line numbers with Fennel source lines so debug
// info points back at the user's `.fnl`.
opts.set("correlate", true)?;
let result = eval
.call::<mlua::Value>((source, opts))
.map_err(|e| FennelError::from_lua(source, name, e))?;
Ok(result)
}
/// Compile and evaluate a Fennel source string, deserializing the result
/// into `T`.
///
/// `name` is used in error messages — typically a filename or a synthetic
/// label like `HEAD:.quire/config.fnl`.
///
/// `on_unknown` is called for every field key present in the Fennel value
/// but not consumed by `T` at any nesting depth. Pass `|_| {}` to ignore.
pub fn load_string<T>(
&self,
source: &str,
name: &str,
mut on_unknown: impl FnMut(&serde_ignored::Path<'_>),
) -> Result<T, FennelError>
where
T: serde::de::DeserializeOwned,
{
let result = self.eval_raw(source, name, |_| Ok(()))?;
let de = mlua::serde::Deserializer::new(result);
serde_ignored::deserialize(de, |path| on_unknown(&path)).map_err(|e| {
FennelError::TypeMismatch {
message: format!("{name}: {e}"),
source: Box::new(e),
}
})
}
/// Load and evaluate a Fennel file from disk, deserializing the result
/// into `T`.
///
/// `on_unknown` is forwarded to [`load_string`] — see its docs.
pub fn load_file<T>(
&self,
path: &Path,
on_unknown: impl FnMut(&serde_ignored::Path<'_>),
) -> Result<T, FennelError>
where
T: serde::de::DeserializeOwned,
{
let source = fs_err::read_to_string(path)?;
self.load_string(&source, &path.display().to_string(), on_unknown)
}
/// Create a fresh Fennel VM and load `path` into `T`.
///
/// Convenience wrapper for callers that only need a one-shot config load
/// and don't need to reuse the VM. Warns via `tracing::warn!` for any
/// unknown fields (all in a single message).
pub fn load_config<T>(path: &Path) -> Result<T, FennelError>
where
T: serde::de::DeserializeOwned,
{
let source = fs_err::read_to_string(path)?;
Self::load_config_str(&source, &path.display().to_string())
}
/// Create a fresh Fennel VM and parse `source` into `T`.
///
/// Like [`load_config`] but reads from a string rather than a file.
/// `name` is used in error messages (e.g. `".quire/config.fnl"`).
/// Warns via `tracing::warn!` for any unknown fields (all in a single message).
pub fn load_config_str<T>(source: &str, name: &str) -> Result<T, FennelError>
where
T: serde::de::DeserializeOwned,
{
let mut unknown = Vec::new();
let result =
Self::new()?.load_string(source, name, |path| unknown.push(path.to_string()))?;
if !unknown.is_empty() {
tracing::warn!(config = %name, fields = ?unknown, "unknown config fields ignored");
}
Ok(result)
}
}
impl FennelError {
/// Construct an `Eval` error from an mlua error, extracting line
/// information when available.
/// Wrap an `mlua::Error` in an `Eval` variant with source-code
/// context. Used at compile time by the Fennel loader and at run
/// time by the executor so a failing run-fn surfaces with the
/// same inline source annotation as a compile error.
pub fn from_lua(source: &str, name: &str, err: mlua::Error) -> Self {
// Try to extract a line (and optional column) from the Lua
// error for a label. None when the error message doesn't carry
// a line — miette renders the source block without an inline
// pointer in that case.
let label = extract_line_col(&err.to_string())
.and_then(|(line, col)| line_col_offset(source, line, col));
// Fold the source name + lua error into the top-level message
// so plain `Display` (tracing, Sentry, logs) carries the full
// diagnostic. `#[source]` retains the mlua error for the
// structural chain.
let message = format!("{name}: {err}");
FennelError::Eval {
message,
source_code: NamedSource::new(name, source.to_string()),
label,
source: Box::new(err),
}
}
}
/// Try to extract a line and optional column from a Lua error message.
///
/// Lua/Fennel errors embed the source location as `name:LINE:COLUMN: message`.
/// The name may contain colons (e.g. `HEAD:.quire/config.fnl`), so splitting
/// from the left breaks. Match the first `:LINE:COLUMN: ` run, which is
/// unambiguous — filenames don't end with `:digits:digits:`.
fn extract_line_col(msg: &str) -> Option<(usize, Option<usize>)> {
// Match `:LINE:COLUMN: ` (parse error) or `:LINE: ` (runtime error).
let re = regex::Regex::new(r":(\d+)(?::(\d+))?: ").ok()?;
let caps = re.captures(msg)?;
let line = caps
.get(1)?
.as_str()
.parse::<usize>()
.ok()
.filter(|&n| n > 0)?;
let col = caps.get(2).and_then(|m| m.as_str().parse::<usize>().ok());
Some((line, col))
}
/// Convert a 1-based line (and optional column) to a byte offset in
/// the source. Column is also 1-based. When column is None, points
/// at the start of the line.
fn line_col_offset(source: &str, line: usize, col: Option<usize>) -> Option<SourceOffset> {
let mut current_line = 1;
for (i, ch) in source.char_indices() {
if current_line == line {
let byte_offset = if let Some(col) = col {
// Advance col-1 characters from the start of the line.
let line_start = i;
let line_end = source[line_start..]
.find('\n')
.map(|n| line_start + n)
.unwrap_or(source.len());
let line_text = &source[line_start..line_end];
let mut byte_pos = 0;
for (idx, c) in line_text.char_indices() {
if idx + 1 == col {
byte_pos = idx;
break;
}
byte_pos = idx + c.len_utf8();
}
line_start + byte_pos
} else {
i
};
return Some(SourceOffset::from(byte_offset));
}
if ch == '\n' {
current_line += 1;
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, Deserialize, PartialEq)]
struct MirrorConfig {
mirror: Mirror,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Mirror {
url: String,
}
#[derive(Debug, Deserialize, PartialEq)]
struct FullConfig {
mirror: Mirror,
notifications: Notifications,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Notifications {
to: Vec<String>,
on: Vec<String>,
}
fn fennel() -> Fennel {
Fennel::new().expect("Fennel::new() should succeed")
}
#[test]
fn load_string_round_trips_simple_table() {
let f = fennel();
let config: MirrorConfig = f
.load_string(
r#"{:mirror {:url "https://github.com/owner/repo.git"}}"#,
"test",
|_| {},
)
.expect("load_string should succeed");
assert_eq!(
config,
MirrorConfig {
mirror: Mirror {
url: "https://github.com/owner/repo.git".to_string(),
}
}
);
}
#[test]
fn load_string_round_trips_nested_table_with_lists() {
let f = fennel();
let source = r#"
{:mirror {:url "https://github.com/owner/repo.git"}
:notifications {:to ["alpha@example.com"]
:on [:ci-failed :mirror-failed]}}
"#;
let config: FullConfig = f
.load_string(source, "config.fnl", |_| {})
.expect("load_string should succeed");
assert_eq!(
config,
FullConfig {
mirror: Mirror {
url: "https://github.com/owner/repo.git".to_string(),
},
notifications: Notifications {
to: vec!["alpha@example.com".to_string()],
on: vec!["ci-failed".to_string(), "mirror-failed".to_string()],
},
}
);
}
#[test]
fn load_string_rejects_malformed_fennel() {
let f = fennel();
let source = "{:bad {:}";
let result: Result<MirrorConfig, _> = f.load_string(source, "bad.fnl", |_| {});
let err = result.unwrap_err();
let FennelError::Eval {
message,
source_code,
label,
..
} = &err
else {
panic!("expected Eval, got {err:?}");
};
assert!(
message.starts_with("bad.fnl: "),
"message should fold name + lua error: {message}"
);
assert!(
message.len() > "bad.fnl: ".len(),
"message should include the lua error detail, got {message:?}"
);
assert_eq!(source_code.inner(), source);
assert!(
label.is_some(),
"label should be set for line-bearing error"
);
}
#[test]
fn load_string_rejects_type_mismatch() {
let f = fennel();
let result: Result<MirrorConfig, _> =
f.load_string("{:mirror {:url 42}}", "types.fnl", |_| {});
let err = result.unwrap_err();
let FennelError::TypeMismatch { message, .. } = &err else {
panic!("expected TypeMismatch, got {err:?}");
};
assert!(
message.starts_with("types.fnl: "),
"message should fold name + deser error: {message}"
);
assert!(
message.len() > "types.fnl: ".len(),
"message should include the deser error detail, got {message:?}"
);
}
#[test]
fn load_string_callback_fires_for_unknown_top_level_field() {
let f = fennel();
let mut unknown = Vec::new();
let result: Result<MirrorConfig, _> = f.load_string(
r#"{:mirror {:url "https://github.com/owner/repo.git"} :oops 1}"#,
"warn.fnl",
|path| unknown.push(path.to_string()),
);
assert!(result.is_ok(), "unexpected error: {:?}", result.err());
assert_eq!(unknown, ["oops"]);
}
#[test]
fn load_string_callback_fires_for_unknown_nested_field() {
let f = fennel();
let mut unknown = Vec::new();
let result: Result<MirrorConfig, _> = f.load_string(
r#"{:mirror {:url "https://github.com/owner/repo.git" :extra "hi"}}"#,
"warn-nested.fnl",
|path| unknown.push(path.to_string()),
);
assert!(result.is_ok(), "unexpected error: {:?}", result.err());
assert_eq!(unknown, ["mirror.extra"]);
}
#[test]
fn load_file_reads_from_disk() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("config.fnl");
fs_err::write(
&path,
r#"{:mirror {:url "https://github.com/owner/repo.git"}}"#,
)
.expect("write");
let f = fennel();
let config: MirrorConfig = f
.load_file(&path, |_| {})
.expect("load_file should succeed");
assert_eq!(
config,
MirrorConfig {
mirror: Mirror {
url: "https://github.com/owner/repo.git".to_string(),
}
}
);
}
#[test]
fn load_file_rejects_missing_file() {
let f = fennel();
let result: Result<MirrorConfig, _> = f.load_file(Path::new("/no/such/file.fnl"), |_| {});
let err = result.unwrap_err();
assert!(
matches!(&err, FennelError::Io(e) if e.kind() == std::io::ErrorKind::NotFound),
"expected NotFound io error, got: {err}"
);
assert!(
err.to_string().contains("/no/such/file.fnl"),
"io error should mention path: {err}"
);
}
#[test]
fn error_label_works_with_colon_in_name() {
let f = fennel();
let source = "\n{:bad {:}";
let result: Result<MirrorConfig, _> =
f.load_string(source, "HEAD:.quire/config.fnl", |_| {});
let err = result.unwrap_err();
let FennelError::Eval { label, .. } = &err else {
unreachable!()
};
assert_eq!(
label
.expect("label should be set when line is extractable")
.offset(),
8,
"label should point at the exact error column in line 2"
);
}
#[test]
fn eval_raw_setup_can_inject_globals() {
let f = fennel();
let result = f
.eval_raw("custom_var", "test", |lua| {
lua.globals().set("custom_var", 42)
})
.expect("eval_raw should succeed");
assert_eq!(result.as_integer(), Some(42));
}
#[test]
fn stdlib_module_preloaded_at_construction() {
let f = fennel();
let module: mlua::Table = f
.lua()
.load(r#"return require("quire.stdlib")"#)
.eval()
.expect("require quire.stdlib");
let _: mlua::Function = module.get("mirror").expect("mirror should be a function");
}
#[test]
fn quire_ci_placeholder_exposes_empty_runtime_stub() {
let f = fennel();
// Before registration runs, `(require :quire.ci)` returns a
// placeholder table with only an empty `runtime` stub —
// primitives are nil until `RuntimeHandle::install` populates
// them. There is no `quire.runtime` module and no `runtime`
// global; the placeholder is the only access path.
let stub: mlua::Table = f
.lua()
.load(r#"return require("quire.ci").runtime"#)
.eval()
.expect("require quire.ci.runtime");
assert!(matches!(
stub.get::<mlua::Value>("sh").expect("sh"),
mlua::Value::Nil
));
let global: mlua::Value = f.lua().globals().get("runtime").expect("globals lookup");
assert!(matches!(global, mlua::Value::Nil));
let quire_runtime: mlua::Value = f
.lua()
.load(r#"return package.loaded["quire.runtime"]"#)
.eval()
.expect("eval");
assert!(matches!(quire_runtime, mlua::Value::Nil));
}
#[test]
fn extract_line_col_parses_line_and_column() {
assert_eq!(
super::extract_line_col("name.fnl:5:12: parse error"),
Some((5, Some(12)))
);
}
#[test]
fn extract_line_col_parses_line_only() {
assert_eq!(
super::extract_line_col("name.fnl:7: runtime error"),
Some((7, None))
);
}
#[test]
fn extract_line_col_handles_colon_in_name() {
assert_eq!(
super::extract_line_col("HEAD:.quire/config.fnl:3:1: oops"),
Some((3, Some(1)))
);
}
#[test]
fn extract_line_col_returns_none_without_location() {
assert!(super::extract_line_col("no location info").is_none());
}
#[test]
fn line_col_offset_returns_none_when_line_exceeds_source() {
// Source has 2 lines, ask for line 10.
assert!(super::line_col_offset("line1\nline2\n", 10, None).is_none());
}
}