buildl-core 0.1.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
//! 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; and the order declarations are returned in.
//!
//! Non-responsibilities: evaluating a build file, which the
//! [`DeclarationSource`] 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::path::PathBuf;
use std::sync::atomic::AtomicBool;

use super::evaluation::{FileResult, evaluate_file};
use super::loading::Loading;
use crate::error::{ActionFound, DeclarationField, Error, NameKind, Result};
use crate::ports::{DeclarationSource, Dispatcher};
use crate::types::{
    Action, Alias, Argument, BuildFile, Command, Declaration, DeclarationOrder, Declared,
    Directory, Discovered, EntryName, Freshness, Label, Origin, OutputName, OutputSource,
    Provenance, Rule, Setting, SourcePath, StagedAlias, StagedDeclaration, StagedItem, 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. 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::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, D: Dispatcher>(
    source: &S,
    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, 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),
        }
    }

    /// 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.
///
/// Sorting here makes the breadth-first order independent of the order the requests were made in.
pub(super) fn resolve_subdirs(
    subdirs: &[StagedSubdir],
    provenance: &Provenance,
) -> 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))?;
        resolved.push(directory);
    }
    resolved.sort();
    resolved.dedup();
    Ok(resolved)
}

/// Converts one staged declaration into a validated one.
pub(super) fn convert(staged: StagedDeclaration, provenance: &Provenance) -> 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)?),
        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 and validated as a workspace path.
fn convert_input(input: &Written<SourcePath>, site: &Site<'_>) -> Result<SourcePath> {
    let directory = site.directory();
    let joined = if directory.is_root() {
        input.as_written().to_owned()
    } else {
        format!("{directory}/{}", input.as_written())
    };
    SourcePath::parse(joined).map_err(site.invalid(DeclarationField::Input))
}

/// 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(staged: StagedTarget, site: &Site<'_>) -> 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)?);
    }
    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 mut env = Vec::with_capacity(staged.env.len());
    for name in &staged.env {
        env.push(name.parse().map_err(site.invalid(DeclarationField::Env))?);
    }
    Ok(Target {
        label,
        role: staged.role,
        action,
        inputs,
        deps,
        outputs,
        env,
        network: staged.network,
        output_source: staged.output_source,
        freshness: staged.freshness,
    })
}

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::BTreeSet;
    use std::path::{Path, PathBuf};

    use super::{build_file, convert, declaration_order, resolve_subdirs};
    use crate::error::{ActionFound, DeclarationField, Error};
    use crate::types::{
        Action, Declaration, DeclarationOrder, Declared, Directory, EntryName, Freshness, Label,
        NetworkAccess, Origin, OutputName, OutputSource, PluginName, PluginRef, PluginVersion,
        Provenance, StagedAlias, StagedDeclaration, StagedItem, 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 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))
    }

    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")).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")).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 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");
    }

    #[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(),
        };
        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("")).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("")).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![Written::new("1X")];
        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).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)),
            DeclarationField::Description
        );

        let alias = StagedAlias {
            name: Written::new("default"),
            target: Written::new("app"),
        };
        let converted = convert(declare(StagedItem::Alias(alias)), &file).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)),
            DeclarationField::Target
        );

        let setting = StagedSetting {
            name: Written::new("test_filter"),
            default: Written::new(""),
        };
        assert!(convert(declare(StagedItem::Setting(setting)), &file).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)),
            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)),
            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);
    }
}