buildl-core 0.3.0

Domain data, ports, and pure pipeline logic for the buildl build system — no I/O, no Lua.
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
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
//! The traversal: which build files are evaluated, and what their staged values become.
//!
//! Its own file because it is where Load meets its ports: the entry point that hands build files to
//! a dispatcher, and the conversion of staged values into validated declarations. The walk along
//! `subdir` requests and the sort that makes the result independent of evaluation order live in
//! `loading`.
//!
//! Responsibilities: [`load`], which hands each build file to a
//! [`Dispatcher`] and returns what `loading` makes of the results; the per-file steps `evaluation`
//! calls, among them asking the [`IgnoreRules`] port about each input and each requested
//! subdirectory; and the order declarations are returned in.
//!
//! Non-responsibilities: evaluating a build file, which the
//! [`DeclarationSource`] port does; deciding which paths are ignored, which the [`IgnoreRules`]
//! port does; deciding how many files are evaluated at a time, which the dispatcher does; and
//! checking one declaration against another, which the phase that builds the graph does.

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;

use super::evaluation::{FileResult, evaluate_file};
use super::loading::Loading;
use crate::error::{ActionFound, DeclarationField, DeclarationSite, Error, NameKind, Result};
use crate::ports::{DeclarationSource, Dispatcher, IgnoreRules};
use crate::types::{
    Action, Alias, Argument, BuildFile, Command, Declaration, DeclarationOrder, Declared,
    Directory, Discovered, EntryKind, EntryName, EnvMark, EnvName, Freshness, IgnoredPath,
    Ignoring, Label, Origin, OutputName, OutputSource, Provenance, Rule, Setting, SourcePath,
    StagedAlias, StagedDeclaration, StagedEnv, StagedItem, StagedMark, StagedRule, StagedSetting,
    StagedSubdir, StagedTarget, Target, TargetName, TargetRole, Turn, Written,
};

/// Evaluates the workspace's build files and returns their declarations, validated and sorted.
///
/// The walk starts at the workspace root and follows `subdir` requests, evaluating each directory
/// once, with `dispatcher` deciding how many files are evaluated at a time. Nothing is discovered
/// from the filesystem: the evaluated build files are exactly the root's and those a `subdir`
/// call reaches. `discovered` is handed to every evaluation, and each `inputs` entry and each
/// requested `subdir` is asked of `rules` once it parses. The result is sorted by declaring
/// directory, then declared name, then the whole declaration, and the error is the one a walk in
/// breadth-first order would meet first, so neither depends on the order anything was evaluated or
/// declared in.
///
/// # Errors
///
/// Returns the first error met in breadth-first order, one of:
///
/// - whatever `source` returns for a build file it cannot evaluate;
/// - [`Error::MissingBuildFile`] when the root or a requested directory holds no build file;
/// - [`Error::InvalidDeclaration`] when a staged value fails its grammar, including a `subdir`
///   that would leave the workspace, and a discovery target that names `outputs` or always runs;
/// - [`Error::Ignored`] when `rules` report an `inputs` entry or a requested `subdir` ignored;
/// - whatever `rules` return for a path it cannot decide, an [`Error::IgnoreFile`];
/// - [`Error::ActionConflict`] when a target names both or neither of `rule` and `run`;
/// - [`Error::LostBuildFiles`] when `dispatcher` returned without evaluating a build file it was
///   given;
///
/// or the error `dispatcher` itself returns.
pub fn load<S: DeclarationSource, I: IgnoreRules, D: Dispatcher>(
    source: &S,
    rules: &I,
    dispatcher: &mut D,
    entry: &EntryName,
    discovered: &Discovered,
) -> Result<Vec<Declaration>> {
    let stop = AtomicBool::new(false);
    let mut loading = Loading::new(entry, &stop);
    dispatcher.dispatch(
        |directory: Directory, _tell: &(dyn Fn(()) + Sync)| {
            let result = evaluate_file(source, rules, entry, &directory, discovered, &stop);
            (directory, result)
        },
        |turn: Turn<(), (Directory, FileResult)>| match turn {
            Turn::Begin => loading.begin(),
            Turn::Told(()) => Vec::new(),
            Turn::Done((directory, result)) => loading.done(directory, result),
        },
    )?;
    loading.finish()
}

/// The build file of `directory`: the entry name, joined under the directory.
pub(super) fn build_file(directory: &Directory, entry: &EntryName) -> BuildFile {
    let path = if directory.is_root() {
        PathBuf::from(entry.as_str())
    } else {
        PathBuf::from(format!("{directory}/{entry}"))
    };
    BuildFile::new(Provenance::new(path, directory.clone()))
}

/// Where a staged value was written: the build file, whose code made the call, and the call's
/// position in the file.
struct Site<'a> {
    provenance: &'a Provenance,
    origin: &'a Origin,
    order: DeclarationOrder,
}

impl Site<'_> {
    /// The directory the build file is evaluated in.
    const fn directory(&self) -> &Directory {
        self.provenance.directory()
    }

    /// Wraps a grammar failure of `field` with this site.
    fn invalid(&self, field: DeclarationField) -> impl FnOnce(Error) -> Error + '_ {
        move |source| Error::InvalidDeclaration {
            provenance: self.provenance.clone(),
            origin: self.origin.clone(),
            order: self.order,
            field,
            source: Box::new(source),
        }
    }

    /// An `inputs` entry or `subdir` at this site, `path`, is ignored by `ignoring`.
    fn ignored(&self, path: IgnoredPath, ignoring: Ignoring) -> Error {
        Error::Ignored {
            provenance: self.provenance.clone(),
            origin: self.origin.clone(),
            order: self.order,
            path: Box::new(path),
            ignoring: Box::new(ignoring),
        }
    }

    /// A target at this site found `found` instead of exactly one action.
    fn conflict(&self, found: ActionFound) -> Error {
        Error::ActionConflict {
            provenance: self.provenance.clone(),
            origin: self.origin.clone(),
            order: self.order,
            found,
        }
    }
}

/// Resolves a file's `subdir` requests under its directory, sorted and without repeats, asking
/// `rules` about each as a folder.
///
/// Sorting here makes the breadth-first order independent of the order the requests were made in.
/// A directory the grammar refuses is never asked, and one `rules` ignore is refused, so its build
/// file is never handed to the source.
pub(super) fn resolve_subdirs<I: IgnoreRules>(
    subdirs: &[StagedSubdir],
    provenance: &Provenance,
    rules: &I,
) -> Result<Vec<Directory>> {
    let mut resolved = Vec::with_capacity(subdirs.len());
    for subdir in subdirs {
        let site = Site {
            provenance,
            origin: &Origin::BuildFile,
            order: subdir.order,
        };
        let directory = subdir
            .path
            .under(site.directory())
            .map_err(site.invalid(DeclarationField::Subdir))?;
        if let Some(ignoring) = rules.ignored(directory.as_str(), EntryKind::Folder)? {
            return Err(site.ignored(IgnoredPath::Subdir(directory), ignoring));
        }
        resolved.push(directory);
    }
    resolved.sort();
    resolved.dedup();
    Ok(resolved)
}

/// Converts one staged declaration into a validated one.
pub(super) fn convert<I: IgnoreRules>(
    staged: StagedDeclaration,
    provenance: &Provenance,
    rules: &I,
) -> Result<Declaration> {
    let site = Site {
        provenance,
        origin: &staged.origin,
        order: staged.order,
    };
    let item = match staged.item {
        StagedItem::Target(target) => Declared::Target(convert_target(target, &site, rules)?),
        StagedItem::Rule(rule) => Declared::Rule(convert_rule(rule, &site)?),
        StagedItem::Alias(alias) => Declared::Alias(convert_alias(&alias, &site)?),
        StagedItem::Setting(setting) => Declared::Setting(convert_setting(&setting, &site)?),
    };
    Ok(Declaration::new(provenance.clone(), staged.origin, item))
}

/// The label a declared name gets: always in the declaring directory.
fn declared_label(name: &Written<TargetName>, site: &Site<'_>) -> Result<Label> {
    let name = name.parse().map_err(site.invalid(DeclarationField::Name))?;
    Ok(Label::new(site.directory().clone(), name))
}

/// A `run` list, every argument validated and the list non-empty.
fn convert_command(run: &[Written<Argument>], site: &Site<'_>) -> Result<Command> {
    let mut arguments = Vec::with_capacity(run.len());
    for argument in run {
        arguments.push(
            argument
                .parse()
                .map_err(site.invalid(DeclarationField::Run))?,
        );
    }
    Command::new(arguments).map_err(site.invalid(DeclarationField::Run))
}

/// An input, joined under the declaring directory, validated as a workspace path and then asked of
/// `rules` as a file.
///
/// A path the grammar refuses is never asked.
fn convert_input<I: IgnoreRules>(
    input: &Written<SourcePath>,
    site: &Site<'_>,
    rules: &I,
) -> Result<SourcePath> {
    let directory = site.directory();
    let joined = if directory.is_root() {
        input.as_written().to_owned()
    } else {
        format!("{directory}/{}", input.as_written())
    };
    let path = SourcePath::parse(joined).map_err(site.invalid(DeclarationField::Input))?;
    match rules.ignored(path.as_str(), EntryKind::File)? {
        Some(ignoring) => Err(site.ignored(IgnoredPath::Input(path), ignoring)),
        None => Ok(path),
    }
}

/// Refuses what a discovery target may not carry: its output is fixed and it is always cached.
fn refuse_discovery_overrides(staged: &StagedTarget, site: &Site<'_>) -> Result<()> {
    if let Some(outputs) = &staged.outputs {
        let value = outputs
            .first()
            .map_or_else(String::new, |output| output.as_written().to_owned());
        return Err(site.invalid(DeclarationField::Output)(Error::InvalidName {
            kind: NameKind::OutputName,
            value,
            reason: "a discovery target's output is fixed, so it takes no outputs",
        }));
    }
    if staged.freshness == Freshness::Always {
        return Err(site.invalid(DeclarationField::Freshness)(
            Error::NotAccepted {
                reason: "a discovery target is always cached, so it cannot always run",
            },
        ));
    }
    Ok(())
}

fn convert_target<I: IgnoreRules>(
    staged: StagedTarget,
    site: &Site<'_>,
    rules: &I,
) -> Result<Target> {
    let label = declared_label(&staged.name, site)?;
    if staged.role == TargetRole::Discovery {
        refuse_discovery_overrides(&staged, site)?;
    }
    let action = match (staged.rule, staged.run) {
        (Some(rule), None) => Action::UseRule(
            rule.resolve(site.directory())
                .map_err(site.invalid(DeclarationField::Rule))?,
        ),
        (None, Some(run)) => Action::Run(convert_command(&run, site)?),
        (Some(_), Some(_)) => return Err(site.conflict(ActionFound::Both)),
        (None, None) => return Err(site.conflict(ActionFound::Neither)),
    };
    let mut inputs = Vec::with_capacity(staged.inputs.len());
    for input in &staged.inputs {
        inputs.push(convert_input(input, site, rules)?);
    }
    let mut deps = Vec::with_capacity(staged.deps.len());
    for dep in &staged.deps {
        deps.push(
            dep.resolve(site.directory())
                .map_err(site.invalid(DeclarationField::Dep))?,
        );
    }
    let outputs = match staged.outputs {
        Some(written) => {
            let mut outputs = Vec::with_capacity(written.len());
            for output in &written {
                outputs.push(
                    output
                        .parse()
                        .map_err(site.invalid(DeclarationField::Output))?,
                );
            }
            outputs
        }
        // A build target is its output, so it defaults to one named for itself. A test is a record
        // of its exit status and what it printed, so it produces no file unless it names one. A
        // discovery target's one output is its name with `.json`, which is what a build file reads.
        None => match staged.role {
            TargetRole::Build => vec![
                OutputName::parse(label.name().as_str())
                    .map_err(site.invalid(DeclarationField::Output))?,
            ],
            TargetRole::Test => Vec::new(),
            TargetRole::Discovery => vec![
                OutputName::parse(format!("{}.json", label.name()))
                    .map_err(site.invalid(DeclarationField::Output))?,
            ],
        },
    };
    if staged.output_source == OutputSource::Stdout && outputs.len() != 1 {
        return Err(site.invalid(DeclarationField::Stdout)(
            Error::StdoutOutputs {
                target: label,
                outputs: outputs.len(),
            },
        ));
    }
    let env = convert_env(&staged.env, &label, site)?;
    Ok(Target {
        label,
        role: staged.role,
        action,
        inputs,
        deps,
        outputs,
        env,
        network: staged.network,
        output_source: staged.output_source,
        freshness: staged.freshness,
    })
}

/// Turns a target's staged `env` entries into its marked variables.
///
/// A list entry is refused before anything else, so a table that is both a list and badly marked
/// is told to mark its variables. Past that, the first entry in staged order that is refused is
/// the one reported.
fn convert_env(
    entries: &[StagedEnv],
    label: &Label,
    site: &Site<'_>,
) -> Result<BTreeMap<EnvName, EnvMark>> {
    let at = || {
        Box::new(DeclarationSite {
            label: label.clone(),
            provenance: site.provenance.clone(),
            origin: site.origin.clone(),
        })
    };
    if entries
        .iter()
        .any(|entry| matches!(entry, StagedEnv::ListEntry))
    {
        return Err(Error::EnvNotMarked { site: at() });
    }
    let mut env = BTreeMap::new();
    for entry in entries {
        match entry {
            StagedEnv::Marked { name, mark } => {
                let name = name.parse().map_err(site.invalid(DeclarationField::Env))?;
                let mark = match mark {
                    StagedMark::Word(word) => word.parse().map_err(|_| Error::EnvBadMark {
                        site: at(),
                        name: name.clone(),
                        found: format!("{:?}", word.as_written()),
                    })?,
                    StagedMark::NotAString { found } => {
                        return Err(Error::EnvBadMark {
                            site: at(),
                            name,
                            found: found.clone(),
                        });
                    }
                };
                env.insert(name, mark);
            }
            StagedEnv::NotAName { found } => {
                return Err(site.invalid(DeclarationField::Env)(Error::InvalidName {
                    kind: NameKind::EnvName,
                    value: format!("<{found}>"),
                    reason: "must be a string",
                }));
            }
            StagedEnv::NotUtf8Name => {
                return Err(site.invalid(DeclarationField::Env)(Error::InvalidName {
                    kind: NameKind::EnvName,
                    value: String::from("<non-UTF-8 text>"),
                    reason: "must be valid UTF-8",
                }));
            }
            StagedEnv::ListEntry => {}
        }
    }
    Ok(env)
}

fn convert_rule(staged: StagedRule, site: &Site<'_>) -> Result<Rule> {
    let label = declared_label(&staged.name, site)?;
    let run = convert_command(&staged.run, site)?;
    let description = match staged.description {
        Some(description) => Some(
            description
                .parse()
                .map_err(site.invalid(DeclarationField::Description))?,
        ),
        None => None,
    };
    Ok(Rule {
        label,
        run,
        description,
    })
}

fn convert_alias(staged: &StagedAlias, site: &Site<'_>) -> Result<Alias> {
    let label = declared_label(&staged.name, site)?;
    let target = staged
        .target
        .resolve(site.directory())
        .map_err(site.invalid(DeclarationField::Target))?;
    Ok(Alias { label, target })
}

fn convert_setting(staged: &StagedSetting, site: &Site<'_>) -> Result<Setting> {
    let name = staged
        .name
        .parse()
        .map_err(site.invalid(DeclarationField::SettingName))?;
    let default = staged
        .default
        .parse()
        .map_err(site.invalid(DeclarationField::SettingValue))?;
    Ok(Setting { name, default })
}

/// The order Load returns declarations in: declaring directory, then declared name as bytes,
/// then the whole declaration.
///
/// The last key makes the order total without the order calls were made in, which a `pairs`
/// loop changes from one evaluation to the next.
pub(crate) fn declaration_order(a: &Declaration, b: &Declaration) -> Ordering {
    a.provenance()
        .directory()
        .cmp(b.provenance().directory())
        .then_with(|| a.item().name().cmp(b.item().name()))
        .then_with(|| a.cmp(b))
}

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

    use std::collections::{BTreeMap, BTreeSet};
    use std::path::{Path, PathBuf};

    use super::{build_file, convert, declaration_order, resolve_subdirs};
    use crate::error::{ActionFound, DeclarationField, Error, NameKind};
    use crate::ports::{IgnoreRules, NothingIgnored};
    use crate::types::{
        Action, Declaration, DeclarationOrder, Declared, Directory, EntryKind, EntryName, EnvMark,
        EnvName, Freshness, Ignoring, Label, NetworkAccess, Origin, OutputName, OutputSource,
        PluginName, PluginRef, PluginVersion, Provenance, StagedAlias, StagedDeclaration,
        StagedEnv, StagedItem, StagedMark, StagedRule, StagedSetting, StagedSubdir, StagedTarget,
        Target, TargetRole, Written,
    };

    fn file_in(directory: &str) -> Provenance {
        let directory = Directory::parse(directory).unwrap();
        let path = if directory.is_root() {
            PathBuf::from("build.lua")
        } else {
            PathBuf::from(format!("{directory}/build.lua"))
        };
        Provenance::new(path, directory)
    }

    fn staged_target(name: &str) -> StagedTarget {
        StagedTarget {
            name: Written::new(name),
            role: TargetRole::Build,
            rule: None,
            run: Some(vec![Written::new("cc")]),
            inputs: Vec::new(),
            deps: Vec::new(),
            outputs: None,
            env: Vec::new(),
            network: NetworkAccess::Sealed,
            output_source: OutputSource::Command,
            freshness: Freshness::Cached,
        }
    }

    fn marked(name: &str, mark: &str) -> StagedEnv {
        StagedEnv::Marked {
            name: Written::new(name),
            mark: StagedMark::Word(Written::new(mark)),
        }
    }

    fn declare(item: StagedItem) -> StagedDeclaration {
        StagedDeclaration {
            order: DeclarationOrder::new(4),
            origin: Origin::BuildFile,
            item,
        }
    }

    fn convert_target_in(
        directory: &str,
        target: StagedTarget,
    ) -> crate::error::Result<Declaration> {
        convert(
            declare(StagedItem::Target(target)),
            &file_in(directory),
            &NothingIgnored,
        )
    }

    fn invalid_field(result: crate::error::Result<Declaration>) -> DeclarationField {
        match result.unwrap_err() {
            Error::InvalidDeclaration { field, order, .. } => {
                assert_eq!(order, DeclarationOrder::new(4));
                field
            }
            other => unreachable!("expected InvalidDeclaration, got {other:?}"),
        }
    }

    fn target_of(declaration: &Declaration) -> &Target {
        match declaration.item() {
            Declared::Target(target) => target,
            other => unreachable!("expected a target, got {other:?}"),
        }
    }

    #[test]
    fn the_build_file_is_the_entry_joined_under_its_directory() {
        let entry = EntryName::parse("build.lua").unwrap();
        let root = build_file(&Directory::root(), &entry);
        assert_eq!(root.file(), Path::new("build.lua"));
        assert!(root.directory().is_root());
        let lib = build_file(&Directory::parse("lib/text").unwrap(), &entry);
        assert_eq!(lib.file(), Path::new("lib/text/build.lua"));
        assert_eq!(lib.directory().as_str(), "lib/text");
    }

    #[test]
    fn subdirs_resolve_under_the_file_sorted_and_without_repeats() {
        let subdirs = ["zeta", "alpha", "zeta", "mid"].map(|raw| StagedSubdir {
            path: Written::new(raw),
            order: DeclarationOrder::new(0),
        });
        let resolved = resolve_subdirs(&subdirs, &file_in("lib"), &NothingIgnored).unwrap();
        let rendered: Vec<&str> = resolved.iter().map(Directory::as_str).collect();
        assert_eq!(rendered, ["lib/alpha", "lib/mid", "lib/zeta"]);
    }

    #[test]
    fn a_subdir_that_leaves_the_workspace_is_an_invalid_declaration() {
        for raw in ["../x", "/x", ""] {
            let subdirs = [StagedSubdir {
                path: Written::new(raw),
                order: DeclarationOrder::new(7),
            }];
            match resolve_subdirs(&subdirs, &file_in("lib"), &NothingIgnored).unwrap_err() {
                Error::InvalidDeclaration {
                    provenance,
                    order,
                    field,
                    ..
                } => {
                    assert_eq!(provenance, file_in("lib"));
                    assert_eq!(order, DeclarationOrder::new(7));
                    assert_eq!(field, DeclarationField::Subdir);
                }
                other => unreachable!("expected InvalidDeclaration, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_target_is_named_in_its_directory_and_resolves_every_dep_form() {
        let mut target = staged_target("app");
        target.deps = ["main.o", ":util.o", "//lib:text"]
            .map(Written::new)
            .to_vec();
        let declaration = convert_target_in("app", target).unwrap();
        assert_eq!(declaration.provenance(), &file_in("app"));
        let target = target_of(&declaration);
        assert_eq!(target.label.to_string(), "//app:app");
        let deps: Vec<String> = target.deps.iter().map(ToString::to_string).collect();
        assert_eq!(deps, ["//app:main.o", "//app:util.o", "//lib:text"]);
    }

    #[test]
    fn env_table_of_marks_is_read() {
        let mut staged = staged_target("app");
        staged.env = vec![marked("RUSTFLAGS", "key"), marked("HOME", "unkeyed")];
        let declaration = convert_target_in("", staged).unwrap();
        assert_eq!(
            target_of(&declaration).env,
            BTreeMap::from([
                (EnvName::parse("HOME").unwrap(), EnvMark::Unkeyed),
                (EnvName::parse("RUSTFLAGS").unwrap(), EnvMark::Key),
            ])
        );
    }

    #[test]
    fn empty_or_absent_env_declares_nothing() {
        let declaration = convert_target_in("", staged_target("app")).unwrap();
        assert!(target_of(&declaration).env.is_empty());
    }

    /// The refusal `staged` earns, rendered as a user would read it.
    fn env_refusal(staged: Vec<StagedEnv>) -> (Error, String) {
        let mut target = staged_target("app");
        target.env = staged;
        let error = convert_target_in("", target).unwrap_err();
        let text = error.to_string();
        (error, text)
    }

    #[test]
    fn env_list_is_refused() {
        let (error, text) = env_refusal(vec![StagedEnv::ListEntry]);
        assert!(matches!(error, Error::EnvNotMarked { .. }), "{error:?}");
        assert_eq!(
            text,
            "build.lua: //:app: env must mark each variable \"key\" or \"unkeyed\", such as \
             env = { HOME = \"unkeyed\" }"
        );
    }

    #[test]
    fn env_mixed_table_is_refused() {
        let (error, _) = env_refusal(vec![StagedEnv::ListEntry, marked("PATH", "unkeyed")]);
        assert!(matches!(error, Error::EnvNotMarked { .. }), "{error:?}");
    }

    #[test]
    fn env_bad_mark_is_refused() {
        let (error, text) = env_refusal(vec![marked("HOME", "pass")]);
        assert!(matches!(error, Error::EnvBadMark { .. }), "{error:?}");
        assert_eq!(
            text,
            "build.lua: //:app: env HOME is marked \"pass\"; mark it \"key\" or \"unkeyed\""
        );
        let (_, text) = env_refusal(vec![StagedEnv::Marked {
            name: Written::new("HOME"),
            mark: StagedMark::NotAString {
                found: "true".to_owned(),
            },
        }]);
        assert_eq!(
            text,
            "build.lua: //:app: env HOME is marked true; mark it \"key\" or \"unkeyed\""
        );
    }

    #[test]
    fn env_list_entry_wins_over_a_bad_mark() {
        let (error, _) = env_refusal(vec![marked("HOME", "pass"), StagedEnv::ListEntry]);
        assert!(matches!(error, Error::EnvNotMarked { .. }), "{error:?}");
    }

    #[test]
    fn env_bad_name_is_refused() {
        let (error, _) = env_refusal(vec![marked("A-B", "key")]);
        let Error::InvalidDeclaration { field, source, .. } = error else {
            unreachable!("expected InvalidDeclaration");
        };
        assert_eq!(field, DeclarationField::Env);
        assert!(
            matches!(
                *source,
                Error::InvalidName {
                    kind: NameKind::EnvName,
                    ..
                }
            ),
            "{source:?}"
        );
        let (error, _) = env_refusal(vec![StagedEnv::NotAName {
            found: "boolean".to_owned(),
        }]);
        assert!(
            matches!(
                error,
                Error::InvalidDeclaration {
                    field: DeclarationField::Env,
                    ..
                }
            ),
            "{error:?}"
        );
    }

    #[test]
    fn env_key_that_is_not_utf8_is_refused_as_such() {
        let (error, _) = env_refusal(vec![StagedEnv::NotUtf8Name]);
        let Error::InvalidDeclaration { field, source, .. } = error else {
            unreachable!("expected InvalidDeclaration");
        };
        assert_eq!(field, DeclarationField::Env);
        assert_eq!(
            source.to_string(),
            "invalid environment variable name: \"<non-UTF-8 text>\" — must be valid UTF-8"
        );
    }

    #[test]
    fn outputs_default_to_the_target_name() {
        let declaration = convert_target_in("app", staged_target("app")).unwrap();
        let outputs: Vec<&str> = target_of(&declaration)
            .outputs
            .iter()
            .map(OutputName::as_str)
            .collect();
        assert_eq!(outputs, ["app"]);
    }

    #[test]
    fn a_discovery_defaults_to_one_json_output_named_for_it() {
        let mut staged = staged_target("pkgs");
        staged.role = TargetRole::Discovery;
        let declaration = convert_target_in("svc", staged).unwrap();
        let outputs: Vec<&str> = target_of(&declaration)
            .outputs
            .iter()
            .map(OutputName::as_str)
            .collect();
        assert_eq!(outputs, ["pkgs.json"]);
    }

    #[test]
    fn a_discovery_naming_outputs_or_always_is_refused_on_that_field() {
        let mut with_outputs = staged_target("pkgs");
        with_outputs.role = TargetRole::Discovery;
        with_outputs.outputs = Some(Vec::new());
        let mut always = staged_target("pkgs");
        always.role = TargetRole::Discovery;
        always.freshness = Freshness::Always;
        for (staged, expected) in [
            (with_outputs, DeclarationField::Output),
            (always, DeclarationField::Freshness),
        ] {
            match convert_target_in("svc", staged).unwrap_err() {
                Error::InvalidDeclaration { field, .. } => assert_eq!(field, expected),
                other => unreachable!("expected InvalidDeclaration, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_stdout_target_with_two_outputs_is_refused() {
        let mut staged = staged_target("gen");
        staged.output_source = OutputSource::Stdout;
        staged.outputs = Some(vec![Written::new("a.txt"), Written::new("b.txt")]);
        let err = convert_target_in("svc", staged).unwrap_err();
        match &err {
            Error::InvalidDeclaration { field, .. } => {
                assert_eq!(*field, DeclarationField::Stdout);
            }
            other => unreachable!("expected InvalidDeclaration, got {other:?}"),
        }
        let rendered = err.to_string();
        assert!(rendered.contains("invalid stdout: "), "{rendered}");
        assert!(rendered.contains("//svc:gen"), "{rendered}");
        assert!(rendered.contains("2 outputs"), "{rendered}");
    }

    #[test]
    fn a_stdout_target_with_no_output_is_refused() {
        let mut staged = staged_target("gen");
        staged.output_source = OutputSource::Stdout;
        staged.outputs = Some(Vec::new());
        let err = convert_target_in("svc", staged).unwrap_err();
        match &err {
            Error::InvalidDeclaration { field, .. } => {
                assert_eq!(*field, DeclarationField::Stdout);
            }
            other => unreachable!("expected InvalidDeclaration, got {other:?}"),
        }
        let rendered = err.to_string();
        assert!(rendered.contains("invalid stdout: "), "{rendered}");
        assert!(rendered.contains("//svc:gen"), "{rendered}");
        assert!(rendered.contains("0 outputs"), "{rendered}");
    }

    #[test]
    fn a_stdout_target_with_one_output_is_accepted() {
        let mut named = staged_target("gen");
        named.output_source = OutputSource::Stdout;
        named.outputs = Some(vec![Written::new("gen.txt")]);
        let declaration = convert_target_in("svc", named).unwrap();
        assert_eq!(target_of(&declaration).output_source, OutputSource::Stdout);

        let mut defaulted = staged_target("gen");
        defaulted.output_source = OutputSource::Stdout;
        let declaration = convert_target_in("svc", defaulted).unwrap();
        assert_eq!(target_of(&declaration).outputs.len(), 1);

        let mut discovery = staged_target("pkgs");
        discovery.role = TargetRole::Discovery;
        discovery.output_source = OutputSource::Stdout;
        let declaration = convert_target_in("svc", discovery).unwrap();
        assert_eq!(target_of(&declaration).output_source, OutputSource::Stdout);
    }

    #[test]
    fn a_test_declares_no_outputs_by_default() {
        let mut staged = staged_target("app_test");
        staged.role = TargetRole::Test;
        let declaration = convert_target_in("app", staged).unwrap();
        assert_eq!(target_of(&declaration).outputs, Vec::<OutputName>::new());
    }

    #[test]
    fn a_test_keeps_the_outputs_it_declares() {
        let mut staged = staged_target("app_test");
        staged.role = TargetRole::Test;
        staged.outputs = Some(vec![Written::new("junit.xml")]);
        let declaration = convert_target_in("app", staged).unwrap();
        let outputs: Vec<&str> = target_of(&declaration)
            .outputs
            .iter()
            .map(OutputName::as_str)
            .collect();
        assert_eq!(outputs, ["junit.xml"]);
    }

    #[test]
    fn inputs_join_under_the_declaring_directory() {
        let mut target = staged_target("app");
        target.inputs = vec![Written::new("src/main.c")];
        let declaration = convert_target_in("app", target).unwrap();
        assert_eq!(target_of(&declaration).inputs[0].as_str(), "app/src/main.c");
        let mut at_root = staged_target("app");
        at_root.inputs = vec![Written::new("main.c")];
        let declaration = convert_target_in("", at_root).unwrap();
        assert_eq!(target_of(&declaration).inputs[0].as_str(), "main.c");
    }

    /// Rules that ignore one path, and note every path they are asked about.
    struct IgnoringOne {
        path: &'static str,
        asked: std::sync::Mutex<Vec<(String, EntryKind)>>,
    }

    impl IgnoringOne {
        fn new(path: &'static str) -> Self {
            Self {
                path,
                asked: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    impl IgnoreRules for IgnoringOne {
        fn ignored(&self, path: &str, kind: EntryKind) -> crate::error::Result<Option<Ignoring>> {
            self.asked.lock().unwrap().push((path.to_owned(), kind));
            Ok((path == self.path).then(|| Ignoring::new("app/.buildlignore", "*.md")))
        }
    }

    #[test]
    fn an_ignored_input_is_refused_at_its_site_with_its_joined_path() {
        let mut target = staged_target("app");
        target.inputs = vec![Written::new("a.md")];
        let rules = IgnoringOne::new("app/a.md");
        let error =
            convert(declare(StagedItem::Target(target)), &file_in("app"), &rules).unwrap_err();
        match error {
            Error::Ignored {
                provenance,
                order,
                path,
                ignoring,
                ..
            } => {
                assert_eq!(provenance.file(), Path::new("app/build.lua"));
                assert_eq!(order, DeclarationOrder::new(4));
                assert_eq!(path.to_string(), "app/a.md");
                assert_eq!(ignoring.pattern(), "*.md");
            }
            other => unreachable!("expected Ignored, got {other:?}"),
        }
        assert_eq!(
            *rules.asked.lock().unwrap(),
            [("app/a.md".to_owned(), EntryKind::File)]
        );
    }

    #[test]
    fn an_ignored_subdir_is_refused_at_its_site_with_its_joined_path() {
        let subdirs = [StagedSubdir {
            path: Written::new("sub"),
            order: DeclarationOrder::new(3),
        }];
        let rules = IgnoringOne::new("app/sub");
        match resolve_subdirs(&subdirs, &file_in("app"), &rules).unwrap_err() {
            Error::Ignored {
                provenance,
                order,
                path,
                ..
            } => {
                assert_eq!(provenance.file(), Path::new("app/build.lua"));
                assert_eq!(order, DeclarationOrder::new(3));
                assert_eq!(path.to_string(), "app/sub");
            }
            other => unreachable!("expected Ignored, got {other:?}"),
        }
        assert_eq!(
            *rules.asked.lock().unwrap(),
            [("app/sub".to_owned(), EntryKind::Folder)]
        );
    }

    #[test]
    fn a_subdir_that_fails_its_grammar_is_not_asked() {
        let subdirs = [StagedSubdir {
            path: Written::new("../x"),
            order: DeclarationOrder::new(0),
        }];
        let rules = IgnoringOne::new("../x");
        match resolve_subdirs(&subdirs, &file_in(""), &rules).unwrap_err() {
            Error::InvalidDeclaration { field, .. } => assert_eq!(field, DeclarationField::Subdir),
            other => unreachable!("expected InvalidDeclaration, got {other:?}"),
        }
        assert!(rules.asked.lock().unwrap().is_empty());
    }

    #[test]
    fn an_input_that_fails_its_grammar_is_not_asked() {
        let mut target = staged_target("app");
        target.inputs = vec![Written::new("../x")];
        let rules = IgnoringOne::new("../x");
        let result = convert(declare(StagedItem::Target(target)), &file_in(""), &rules);
        assert_eq!(invalid_field(result), DeclarationField::Input);
        assert!(rules.asked.lock().unwrap().is_empty());
    }

    #[test]
    fn a_rule_reference_resolves_against_the_declaring_directory() {
        let mut target = staged_target("main.o");
        target.run = None;
        target.rule = Some(Written::new("cc"));
        let declaration = convert_target_in("app", target).unwrap();
        assert_eq!(
            target_of(&declaration).action,
            Action::UseRule(Label::parse("//app:cc").unwrap())
        );
    }

    #[test]
    fn a_target_needs_exactly_one_of_rule_and_run() {
        let mut both = staged_target("app");
        both.rule = Some(Written::new("cc"));
        let mut neither = staged_target("app");
        neither.run = None;
        for (target, expected) in [(both, ActionFound::Both), (neither, ActionFound::Neither)] {
            match convert_target_in("", target).unwrap_err() {
                Error::ActionConflict { found, order, .. } => {
                    assert_eq!(found, expected);
                    assert_eq!(order, DeclarationOrder::new(4));
                }
                other => unreachable!("expected ActionConflict, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_refused_declaration_of_a_plugin_carries_the_plugins_origin() {
        let go = PluginRef {
            name: PluginName::parse("go").unwrap(),
            version: PluginVersion::parse("1.2.0").unwrap(),
            run: BTreeSet::new(),
            env: BTreeSet::new(),
            unkeyed: BTreeSet::new(),
        };
        let origin = Origin::plugins(vec![go]).unwrap();
        let by_plugin = |target: StagedTarget| StagedDeclaration {
            origin: origin.clone(),
            ..declare(StagedItem::Target(target))
        };
        let mut neither = staged_target("app");
        neither.run = None;
        match convert(by_plugin(neither), &file_in(""), &NothingIgnored).unwrap_err() {
            Error::ActionConflict { origin: found, .. } => assert_eq!(found, origin),
            other => unreachable!("expected ActionConflict, got {other:?}"),
        }
        match convert(
            by_plugin(staged_target("a/b")),
            &file_in(""),
            &NothingIgnored,
        )
        .unwrap_err()
        {
            Error::InvalidDeclaration { origin: found, .. } => assert_eq!(found, origin),
            other => unreachable!("expected InvalidDeclaration, got {other:?}"),
        }
    }

    #[test]
    fn an_empty_run_is_an_invalid_command() {
        let mut target = staged_target("app");
        target.run = Some(Vec::new());
        let err = convert_target_in("", target).unwrap_err();
        assert!(
            err.to_string()
                .ends_with(r#"invalid run: invalid command: "" — must hold at least one argument"#),
            "{err}"
        );
    }

    #[test]
    fn a_name_cannot_leave_its_directory() {
        let target = staged_target("//other:x");
        assert_eq!(
            invalid_field(convert_target_in("", target)),
            DeclarationField::Name
        );
    }

    #[test]
    fn each_invalid_target_field_is_named() {
        let mut dep = staged_target("app");
        dep.deps = vec![Written::new("//lib")];
        assert_eq!(
            invalid_field(convert_target_in("", dep)),
            DeclarationField::Dep
        );

        let mut input = staged_target("app");
        input.inputs = vec![Written::new("../x")];
        assert_eq!(
            invalid_field(convert_target_in("", input)),
            DeclarationField::Input
        );

        let mut output = staged_target("app");
        output.outputs = Some(vec![Written::new("/abs")]);
        assert_eq!(
            invalid_field(convert_target_in("", output)),
            DeclarationField::Output
        );

        let mut env = staged_target("app");
        env.env = vec![marked("1X", "key")];
        assert_eq!(
            invalid_field(convert_target_in("", env)),
            DeclarationField::Env
        );

        let mut run = staged_target("app");
        run.run = Some(vec![Written::new("a\0b")]);
        assert_eq!(
            invalid_field(convert_target_in("", run)),
            DeclarationField::Run
        );

        let mut rule = staged_target("app");
        rule.run = None;
        rule.rule = Some(Written::new("//tools"));
        assert_eq!(
            invalid_field(convert_target_in("", rule)),
            DeclarationField::Rule
        );
    }

    #[test]
    fn rules_aliases_and_settings_convert_and_name_their_invalid_fields() {
        let file = file_in("");
        let rule = StagedRule {
            name: Written::new("cc"),
            run: vec![Written::new("cc"), Written::new("$in")],
            description: Some(Written::new("compile $in")),
        };
        let converted = convert(
            declare(StagedItem::Rule(rule.clone())),
            &file,
            &NothingIgnored,
        )
        .unwrap();
        assert_eq!(converted.item().name(), "cc");

        let mut bad_description = rule;
        bad_description.description = Some(Written::new("two\nlines"));
        assert_eq!(
            invalid_field(convert(
                declare(StagedItem::Rule(bad_description)),
                &file,
                &NothingIgnored
            )),
            DeclarationField::Description
        );

        let alias = StagedAlias {
            name: Written::new("default"),
            target: Written::new("app"),
        };
        let converted = convert(declare(StagedItem::Alias(alias)), &file, &NothingIgnored).unwrap();
        match converted.item() {
            Declared::Alias(alias) => assert_eq!(alias.target.to_string(), "//:app"),
            other => unreachable!("expected an alias, got {other:?}"),
        }
        let bad_alias = StagedAlias {
            name: Written::new("default"),
            target: Written::new("a/b"),
        };
        assert_eq!(
            invalid_field(convert(
                declare(StagedItem::Alias(bad_alias)),
                &file,
                &NothingIgnored
            )),
            DeclarationField::Target
        );

        let setting = StagedSetting {
            name: Written::new("test_filter"),
            default: Written::new(""),
        };
        assert!(
            convert(
                declare(StagedItem::Setting(setting)),
                &file,
                &NothingIgnored
            )
            .is_ok()
        );
        let bad_name = StagedSetting {
            name: Written::new("a.b"),
            default: Written::new(""),
        };
        assert_eq!(
            invalid_field(convert(
                declare(StagedItem::Setting(bad_name)),
                &file,
                &NothingIgnored
            )),
            DeclarationField::SettingName
        );
        let bad_value = StagedSetting {
            name: Written::new("x"),
            default: Written::new("a\0b"),
        };
        assert_eq!(
            invalid_field(convert(
                declare(StagedItem::Setting(bad_value)),
                &file,
                &NothingIgnored
            )),
            DeclarationField::SettingValue
        );
    }

    #[test]
    fn sorting_orders_by_directory_then_name_then_value() {
        let declare_in = |directory: &str, name: &str| {
            convert_target_in(directory, staged_target(name)).unwrap()
        };
        let mut declarations = [
            declare_in("lib", "a"),
            declare_in("", "zeta"),
            declare_in("", "alpha"),
            declare_in("app", "m"),
        ];
        declarations.sort_by(declaration_order);
        let rendered: Vec<String> = declarations
            .iter()
            .map(|d| target_of(d).label.to_string())
            .collect();
        assert_eq!(rendered, ["//:alpha", "//:zeta", "//app:m", "//lib:a"]);
    }

    #[test]
    fn declarations_sharing_a_directory_and_name_sort_by_content_in_either_order() {
        let tool = |program: &str| {
            let mut target = staged_target("a");
            target.run = Some(vec![Written::new(program)]);
            convert_target_in("lib", target).unwrap()
        };
        let sorted = |mut declarations: Vec<Declaration>| {
            declarations.sort_by(declaration_order);
            declarations
        };
        let forward = sorted(vec![tool("ar"), tool("cc")]);
        let backward = sorted(vec![tool("cc"), tool("ar")]);
        assert_eq!(forward, backward);
    }
}