buildl-lua 0.3.1

Lua build-file evaluation for buildl, on the airsl embedded runtime.
Documentation
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
//! What each `buildl` primitive reads from its arguments, and the staged record it produces.
//!
//! Its own file because the argument shape of each primitive is the build-file API's contract,
//! and keeping all of them together keeps them consistent: positional parameters are read left
//! to right, then an option table is checked for unknown keys, then its accepted fields are read
//! in the order each primitive lists them. A refusal after the name is known names it.
//!
//! Responsibilities: [`target`], [`rule`], [`alias`], [`option`], [`subdir`], [`pattern`],
//! [`discovered`].
//!
//! Non-responsibilities: staging the records and installing the functions, which the `buildl`
//! module does.

use airsl::mlua::Value;
use buildl_core::{
    Directory, EvaluationFailure, Freshness, Label, NetworkAccess, OutputSource, SettingName,
    StagedAlias, StagedRule, StagedSetting, StagedTarget, TargetName, TargetRole, Written,
};

use crate::env_marks;
use crate::refusal::Refusal;
use crate::values::{closed, field, flag, list, optional_list, optional_text, string, table, text};

/// The fields `buildl.target` accepts, in the order they are read.
const TARGET_FIELDS: [&str; 9] = [
    "rule", "run", "inputs", "deps", "outputs", "env", "network", "stdout", "always",
];
/// The fields `buildl.test` accepts: those of a target, less `stdout`. A test is a record of its
/// exit status and what it printed, so what it prints is never its output.
const TEST_FIELDS: [&str; 8] = [
    "rule", "run", "inputs", "deps", "outputs", "env", "network", "always",
];
/// The fields `buildl.discover` accepts: those of a target, less the two a discovery target
/// does not take. Its one output is placed by buildl, and it is never always-run.
const DISCOVER_FIELDS: [&str; 7] = ["rule", "run", "inputs", "deps", "env", "network", "stdout"];
/// The fields `buildl.rule` accepts, in the order they are read.
const RULE_FIELDS: [&str; 2] = ["run", "desc"];
/// The fields `buildl.option` accepts.
const OPTION_FIELDS: [&str; 1] = ["default"];

/// `buildl.target(name, options)`, `buildl.test(name, options)` and `buildl.discover(name,
/// options)`, told apart by `role`.
///
/// A discovery target's table is closed over [`DISCOVER_FIELDS`], so `outputs` and `always` are
/// unknown fields to it.
pub(crate) fn target(
    name: &Value,
    options: &Value,
    role: TargetRole,
) -> Result<StagedTarget, Refusal> {
    let name: Written<TargetName> = text(name, "name")?;
    let subject = name.as_written().to_owned();
    target_fields(name, options, role).map_err(|refusal| refusal.about(&subject))
}

fn target_fields(
    name: Written<TargetName>,
    options: &Value,
    role: TargetRole,
) -> Result<StagedTarget, Refusal> {
    let options = table(options, "options")?;
    closed(
        &options,
        match role {
            TargetRole::Build => &TARGET_FIELDS[..],
            TargetRole::Test => &TEST_FIELDS[..],
            TargetRole::Discovery => &DISCOVER_FIELDS[..],
        },
    )?;
    Ok(StagedTarget {
        name,
        role,
        rule: optional_text(&field(&options, "rule")?, "rule")?,
        run: optional_list(&field(&options, "run")?, "run")?,
        inputs: optional_list(&field(&options, "inputs")?, "inputs")?.unwrap_or_default(),
        deps: optional_list(&field(&options, "deps")?, "deps")?.unwrap_or_default(),
        outputs: optional_list(&field(&options, "outputs")?, "outputs")?,
        env: env_marks::stage(&field(&options, "env")?)?,
        network: match flag(&field(&options, "network")?, "network")? {
            Some(true) => NetworkAccess::Declared,
            Some(false) | None => NetworkAccess::Sealed,
        },
        output_source: match flag(&field(&options, "stdout")?, "stdout")? {
            Some(true) => OutputSource::Stdout,
            Some(false) | None => OutputSource::Command,
        },
        freshness: match flag(&field(&options, "always")?, "always")? {
            Some(true) => Freshness::Always,
            Some(false) | None => Freshness::Cached,
        },
    })
}

/// `buildl.rule(name, options)`.
pub(crate) fn rule(name: &Value, options: &Value) -> Result<StagedRule, Refusal> {
    let name: Written<TargetName> = text(name, "name")?;
    let subject = name.as_written().to_owned();
    rule_fields(name, options).map_err(|refusal| refusal.about(&subject))
}

fn rule_fields(name: Written<TargetName>, options: &Value) -> Result<StagedRule, Refusal> {
    let options = table(options, "options")?;
    closed(&options, &RULE_FIELDS)?;
    Ok(StagedRule {
        name,
        run: list(&field(&options, "run")?, "run")?,
        description: optional_text(&field(&options, "desc")?, "desc")?,
    })
}

/// `buildl.alias(name, target)`.
pub(crate) fn alias(name: &Value, target: &Value) -> Result<StagedAlias, Refusal> {
    let name: Written<TargetName> = text(name, "name")?;
    let target = text(target, "target").map_err(|refusal| refusal.about(name.as_written()))?;
    Ok(StagedAlias { name, target })
}

/// `buildl.option(name, options)`.
pub(crate) fn option(name: &Value, options: &Value) -> Result<StagedSetting, Refusal> {
    let name: Written<SettingName> = text(name, "name")?;
    let subject = name.as_written().to_owned();
    option_fields(name, options).map_err(|refusal| refusal.about(&subject))
}

fn option_fields(name: Written<SettingName>, options: &Value) -> Result<StagedSetting, Refusal> {
    let options = table(options, "options")?;
    closed(&options, &OPTION_FIELDS)?;
    Ok(StagedSetting {
        name,
        default: text(&field(&options, "default")?, "default")?,
    })
}

/// `buildl.subdir(path)`.
pub(crate) fn subdir(path: &Value) -> Result<Written<Directory>, Refusal> {
    text(path, "path")
}

/// The pattern argument of `buildl.sources(pattern)`.
pub(crate) fn pattern(pattern: &Value) -> Result<String, Refusal> {
    string(pattern, "pattern")
}

/// The label argument of `buildl.discovered(label)`, resolved against `base` as a dependency is.
pub(crate) fn discovered(label: &Value, base: &Directory) -> Result<Label, Refusal> {
    let raw = string(label, "label")?;
    Label::resolve(&raw, base).map_err(|error| {
        Refusal::new(
            EvaluationFailure::Refused,
            format!("field 'label' must be a target label, found {raw:?}: {error}"),
        )
    })
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid Lua snippets; a panic is the intended failure signal"
    )]

    use airsl::mlua::{Lua, Value};
    use buildl_core::{
        Directory, EvaluationFailure, Freshness, Label, NetworkAccess, OutputSource, StagedAlias,
        StagedEnv, StagedMark, StagedRule, StagedSetting, StagedTarget, TargetRole, Written,
    };

    use super::{alias, discovered, option, pattern, rule, subdir, target};
    use crate::refusal::CallSite;

    fn eval(lua: &Lua, source: &str) -> Value {
        lua.load(source).eval::<Value>().unwrap()
    }

    fn strings<T>(texts: &[&str]) -> Vec<Written<T>> {
        texts.iter().map(|text| Written::new(*text)).collect()
    }

    #[test]
    fn target_reads_every_field() {
        let lua = Lua::new();
        let staged = target(
            &eval(&lua, "return 'app'"),
            &eval(
                &lua,
                "return { rule = 'cc', run = { 'cc', '$in' }, inputs = { { 'a.c' }, 'b.c' }, \
                 deps = { '//lib:text' }, outputs = { 'app' }, env = { HOME = 'unkeyed' }, \
                 network = true, always = true }",
            ),
            TargetRole::Build,
        )
        .unwrap();
        assert_eq!(
            staged,
            StagedTarget {
                name: Written::new("app"),
                role: TargetRole::Build,
                rule: Some(Written::new("cc")),
                run: Some(strings(&["cc", "$in"])),
                inputs: strings(&["a.c", "b.c"]),
                deps: strings(&["//lib:text"]),
                outputs: Some(strings(&["app"])),
                env: vec![StagedEnv::Marked {
                    name: Written::new("HOME"),
                    mark: StagedMark::Word(Written::new("unkeyed")),
                }],
                network: NetworkAccess::Declared,
                output_source: OutputSource::Command,
                freshness: Freshness::Always,
            }
        );
    }

    #[test]
    fn env_on_test_and_discover_is_read_the_same() {
        let lua = Lua::new();
        let env_of = |role| {
            target(
                &eval(&lua, "return 'x'"),
                &eval(
                    &lua,
                    "return { run = { 'x' }, env = { HOME = 'unkeyed', FLAGS = 'key' } }",
                ),
                role,
            )
            .unwrap()
            .env
        };
        let build = env_of(TargetRole::Build);
        assert_eq!(build.len(), 2);
        assert_eq!(env_of(TargetRole::Test), build);
        assert_eq!(env_of(TargetRole::Discovery), build);
    }

    #[test]
    fn env_must_be_a_table() {
        let lua = Lua::new();
        let refusal = target(
            &eval(&lua, "return 'app'"),
            &eval(&lua, "return { run = { 'x' }, env = 'HOME' }"),
            TargetRole::Build,
        )
        .unwrap_err();
        assert_eq!(
            refusal.diagnostic("target", None).as_str(),
            "buildl.target 'app': field 'env' must be a table, found string"
        );
    }

    #[test]
    fn target_defaults_every_absent_field() {
        let lua = Lua::new();
        let staged = target(
            &eval(&lua, "return 'app_test'"),
            &eval(&lua, "return { network = false, always = false }"),
            TargetRole::Test,
        )
        .unwrap();
        assert_eq!(
            staged,
            StagedTarget {
                name: Written::new("app_test"),
                role: TargetRole::Test,
                rule: None,
                run: None,
                inputs: Vec::new(),
                deps: Vec::new(),
                outputs: None,
                env: Vec::new(),
                network: NetworkAccess::Sealed,
                output_source: OutputSource::Command,
                freshness: Freshness::Cached,
            }
        );
    }

    #[test]
    fn target_reads_stdout_as_the_output_source() {
        let lua = Lua::new();
        let stdout = |source: &str, role| {
            target(&eval(&lua, "return 'gen'"), &eval(&lua, source), role)
                .unwrap()
                .output_source
        };
        assert_eq!(
            stdout(
                "return { run = { 'gen' }, stdout = true }",
                TargetRole::Build
            ),
            OutputSource::Stdout
        );
        assert_eq!(
            stdout(
                "return { run = { 'gen' }, stdout = false }",
                TargetRole::Build
            ),
            OutputSource::Command
        );
    }

    #[test]
    fn a_discovery_target_takes_stdout() {
        let lua = Lua::new();
        let staged = target(
            &eval(&lua, "return 'pkgs'"),
            &eval(&lua, "return { run = { 'list' }, stdout = true }"),
            TargetRole::Discovery,
        )
        .unwrap();
        assert_eq!(staged.output_source, OutputSource::Stdout);
    }

    #[test]
    fn a_test_refuses_stdout() {
        let lua = Lua::new();
        let refusal = target(
            &eval(&lua, "return 'app_test'"),
            &eval(&lua, "return { run = { 't' }, stdout = true }"),
            TargetRole::Test,
        )
        .unwrap_err();
        assert_eq!(
            refusal.failure(),
            &EvaluationFailure::UnknownField {
                field: Written::new("stdout"),
            }
        );
    }

    #[test]
    fn stdout_must_be_a_boolean() {
        let lua = Lua::new();
        let refusal = target(
            &eval(&lua, "return 'gen'"),
            &eval(&lua, "return { run = { 'gen' }, stdout = 'yes' }"),
            TargetRole::Build,
        )
        .unwrap_err();
        assert_eq!(
            refusal.failure(),
            &EvaluationFailure::WrongFieldType {
                field: Written::new("stdout"),
            }
        );
    }

    #[test]
    fn a_bad_name_is_refused_before_the_options_are_looked_at() {
        let refusal = target(&Value::Nil, &Value::Nil, TargetRole::Build).unwrap_err();
        assert_eq!(
            refusal.diagnostic("target", None).as_str(),
            "buildl.target: field 'name' must be a string, found nil"
        );
    }

    #[test]
    fn an_unknown_field_is_refused_before_a_wrongly_typed_one() {
        let lua = Lua::new();
        let refusal = target(
            &eval(&lua, "return 'app'"),
            &eval(&lua, "return { run = 1, srcs = {} }"),
            TargetRole::Build,
        )
        .unwrap_err();
        assert_eq!(
            refusal.failure(),
            &EvaluationFailure::UnknownField {
                field: Written::new("srcs"),
            }
        );
        assert_eq!(
            refusal
                .diagnostic("target", Some(&CallSite::BuildFile { line: 4 }))
                .as_str(),
            "line 4: buildl.target 'app': unknown field 'srcs'"
        );
    }

    #[test]
    fn accepted_fields_are_checked_in_their_listed_order() {
        let lua = Lua::new();
        let refusal = target(
            &eval(&lua, "return 'app'"),
            &eval(&lua, "return { always = 1, run = 1 }"),
            TargetRole::Build,
        )
        .unwrap_err();
        assert_eq!(
            refusal.failure(),
            &EvaluationFailure::WrongFieldType {
                field: Written::new("run"),
            }
        );
    }

    #[test]
    fn rule_requires_run_and_reads_desc() {
        let lua = Lua::new();
        let staged = rule(
            &eval(&lua, "return 'cc'"),
            &eval(
                &lua,
                "return { run = { 'cc', '-c' }, desc = 'compile $in' }",
            ),
        )
        .unwrap();
        assert_eq!(
            staged,
            StagedRule {
                name: Written::new("cc"),
                run: strings(&["cc", "-c"]),
                description: Some(Written::new("compile $in")),
            }
        );
        let refusal = rule(&eval(&lua, "return 'cc'"), &eval(&lua, "return {}")).unwrap_err();
        assert_eq!(
            refusal.diagnostic("rule", None).as_str(),
            "buildl.rule 'cc': field 'run' must be a list of strings, found nil"
        );
    }

    #[test]
    fn alias_reads_two_strings() {
        let lua = Lua::new();
        assert_eq!(
            alias(&eval(&lua, "return 'default'"), &eval(&lua, "return 'app'")).unwrap(),
            StagedAlias {
                name: Written::new("default"),
                target: Written::new("app"),
            }
        );
        let refusal = alias(&eval(&lua, "return 'default'"), &Value::Nil).unwrap_err();
        assert_eq!(
            refusal.diagnostic("alias", None).as_str(),
            "buildl.alias 'default': field 'target' must be a string, found nil"
        );
    }

    #[test]
    fn option_requires_a_string_default() {
        let lua = Lua::new();
        assert_eq!(
            option(
                &eval(&lua, "return 'mode'"),
                &eval(&lua, "return { default = 'debug' }")
            )
            .unwrap(),
            StagedSetting {
                name: Written::new("mode"),
                default: Written::new("debug"),
            }
        );
        let refusal = option(
            &eval(&lua, "return 'jobs'"),
            &eval(&lua, "return { default = 4 }"),
        )
        .unwrap_err();
        assert_eq!(
            refusal.diagnostic("option", None).as_str(),
            "buildl.option 'jobs': field 'default' must be a string, found integer"
        );
    }

    #[test]
    fn subdir_and_pattern_read_one_string() {
        let lua = Lua::new();
        assert_eq!(
            subdir(&eval(&lua, "return 'lib'")).unwrap(),
            Written::new("lib")
        );
        assert_eq!(pattern(&eval(&lua, "return '*.c'")).unwrap(), "*.c");
        assert_eq!(
            pattern(&Value::Nil)
                .unwrap_err()
                .diagnostic("sources", None)
                .as_str(),
            "buildl.sources: field 'pattern' must be a string, found nil"
        );
    }

    #[test]
    fn a_discovery_target_takes_a_target_s_fields_less_outputs_and_always() {
        let lua = Lua::new();
        let staged = target(
            &eval(&lua, "return 'pkgs'"),
            &eval(&lua, "return { run = { 'go' }, network = true }"),
            TargetRole::Discovery,
        )
        .unwrap();
        assert_eq!(staged.role, TargetRole::Discovery);
        assert_eq!(staged.outputs, None);
        assert_eq!(staged.freshness, Freshness::Cached);
        for (field, name) in [
            ("outputs = { 'p' }", "outputs"),
            ("always = true", "always"),
        ] {
            let refusal = target(
                &eval(&lua, "return 'pkgs'"),
                &eval(&lua, &format!("return {{ run = {{ 'go' }}, {field} }}")),
                TargetRole::Discovery,
            )
            .unwrap_err();
            assert_eq!(
                refusal.failure(),
                &EvaluationFailure::UnknownField {
                    field: Written::new(name),
                }
            );
        }
    }

    #[test]
    fn discovered_resolves_a_label_against_the_directory() {
        let lua = Lua::new();
        let base = Directory::parse("svc").unwrap();
        for raw in [":pkgs", "pkgs", "//svc:pkgs"] {
            assert_eq!(
                discovered(&eval(&lua, &format!("return '{raw}'")), &base).unwrap(),
                Label::parse("//svc:pkgs").unwrap(),
                "{raw}"
            );
        }
    }

    #[test]
    fn discovered_refuses_a_value_that_is_not_a_label() {
        let lua = Lua::new();
        let base = Directory::root();
        let refusal = discovered(&Value::Nil, &base).unwrap_err();
        assert_eq!(
            refusal.diagnostic("discovered", None).as_str(),
            "buildl.discovered: field 'label' must be a string, found nil"
        );
        let refusal = discovered(&eval(&lua, "return '//svc'"), &base).unwrap_err();
        assert_eq!(refusal.failure(), &EvaluationFailure::Refused);
        assert!(
            refusal.diagnostic("discovered", None).as_str().starts_with(
                "buildl.discovered: field 'label' must be a target label, found \"//svc\""
            ),
            "{refusal:?}"
        );
    }
}