Skip to main content

buildl_core/
error.rs

1//! The crate's one error type and the `Result` alias every fallible call returns.
2//!
3//! A single file rather than one error type per module: a caller branches on a field, never on
4//! the text of a message, and every module in this crate returns the same `Result` without a
5//! conversion at the boundary.
6//!
7//! Responsibilities:
8//!
9//! - [`Error`] — every way a call into this crate can fail.
10//! - [`NameKind`] — which domain name an [`Error::InvalidName`] is about.
11//! - [`EvaluationFailure`] and [`EvaluationLimit`] — how an adapter failed to evaluate a build
12//!   file.
13//! - [`DeclarationField`] — which field of a declaration an [`Error::InvalidDeclaration`] is
14//!   about.
15//! - [`ActionFound`] — what an [`Error::ActionConflict`] found instead of one action.
16//! - [`DeclaredKind`] — what a label an [`Error::WrongReferenceKind`] is about was declared as.
17//! - [`DeclarationSite`] — a declared label, its build file and whose code declared it: the
18//!   declaration holding a bad reference, one target on a dependency cycle, one declaration of a
19//!   duplicated label, or the target a test run named that is not a test.
20//! - [`PortName`] — which port an [`Error::Adapter`] came through.
21//! - [`RemoteVariable`] and [`RemoteFlagConflict`] — which switch variable an
22//!   [`Error::RemoteSwitch`] refused, and which flag combination an [`Error::RemoteFlags`] did.
23//! - [`UnsandboxedRemote`] — what an [`Error::UploadUnsandboxed`] found asked for while actions run
24//!   bare.
25//! - [`TreeFault`] — why a list of files an [`Error::InvalidTree`] is about is not a tree.
26//! - [`Result`] — the crate-wide alias.
27//!
28//! Non-responsibilities: presentation. [`Error`]'s `Display` renders one diagnostic, on one line
29//! unless an adapter's own message spans several. An error is returned, and its caller shows it.
30
31use core::fmt;
32use std::num::NonZeroUsize;
33use std::path::PathBuf;
34
35use crate::types::{
36    Ceiling, Declaration, DeclarationOrder, DenialReason, Diagnostic, Directory, EnvName, EnvValue,
37    FieldName, InputKind, Label, Node, Origin, OutputPath, PluginName, PluginViolation, Program,
38    Provenance, RemoteUrl, SettingName, SourcePath, TargetRole, TokenSource, TreePath, Want,
39    WantedSet, Written,
40};
41
42/// The result of any fallible call in this crate.
43pub type Result<T> = core::result::Result<T, Error>;
44
45/// Every way a call into this crate can fail.
46///
47/// Non-exhaustive: adding a variant is not a breaking change for downstream crates.
48#[derive(Debug, thiserror::Error)]
49#[non_exhaustive]
50pub enum Error {
51    /// A domain name did not satisfy its grammar.
52    #[error("invalid {kind}: {value:?} — {reason}")]
53    InvalidName {
54        /// Which kind of name was being built.
55        kind: NameKind,
56        /// The rejected input, as given.
57        value: String,
58        /// Why the grammar rejected it.
59        reason: &'static str,
60    },
61    /// A remote cache is given a token but named by a `grpc://` URL, which sends it unencrypted.
62    #[error("a token would be sent in clear text to {url}; use a grpcs:// URL")]
63    InsecureToken {
64        /// The remote cache's URL.
65        url: RemoteUrl,
66    },
67    /// A declaration holds a value its kind of target does not take.
68    #[error("{reason}")]
69    NotAccepted {
70        /// Why the declaration cannot hold the value.
71        reason: &'static str,
72    },
73    /// A target whose output is its stdout does not declare exactly one output.
74    #[error(
75        "target {target} declares {outputs} outputs; a target whose output is its stdout declares exactly one"
76    )]
77    StdoutOutputs {
78        /// The target.
79        target: Label,
80        /// How many outputs it declares.
81        outputs: usize,
82    },
83    /// A value could not be serialized as JSON at all.
84    #[error("value could not be serialized as canonical JSON")]
85    CanonicalJson {
86        /// The underlying `serde_json` failure.
87        #[source]
88        source: serde_json::Error,
89    },
90    /// A floating-point number reached the canonical serializer.
91    #[error("floating-point value at {path} cannot appear in canonical JSON")]
92    FloatRejected {
93        /// Where in the value the float was found, as a JSONPath-style location.
94        path: String,
95    },
96    /// Bytes could not be read as a value: they are not JSON, or the JSON does not describe a
97    /// valid value of the type asked for.
98    #[error("canonical JSON could not be read: {source}")]
99    UnreadableJson {
100        /// The underlying `serde_json` failure, which names the line and column.
101        #[source]
102        source: serde_json::Error,
103    },
104    /// Bytes describe a valid value, but are not the bytes the canonical serializer writes for
105    /// it.
106    #[error("JSON is not in canonical form: it differs from it at byte {offset}")]
107    NonCanonicalJson {
108        /// The index of the first byte that differs from the canonical form of the value.
109        offset: usize,
110    },
111    /// A file an adapter keeps a workspace's state in does not hold what the adapter writes
112    /// there.
113    ///
114    /// Distinct from [`Error::Adapter`], which is a file that could not be read at all: this
115    /// one was read, and its content is refused. `source` is the reading failure,
116    /// [`Error::UnreadableJson`] or [`Error::NonCanonicalJson`].
117    #[error("{} is not a file buildl wrote: {source}", .file.display())]
118    CorruptState {
119        /// The file, as the adapter opened it.
120        file: PathBuf,
121        /// Why its content was refused.
122        #[source]
123        source: Box<Self>,
124    },
125    /// An adapter could not evaluate a build file.
126    #[error("{provenance}: {failure}: {diagnostic}")]
127    Evaluation {
128        /// The build file.
129        provenance: Provenance,
130        /// What kind of failure it was.
131        failure: EvaluationFailure,
132        /// The adapter's message, for display only.
133        diagnostic: Diagnostic,
134    },
135    /// A directory that had to be evaluated holds no build file.
136    #[error(
137        "no build file in //{directory}{}",
138        requested_by_suffix(.requested_by.as_ref())
139    )]
140    MissingBuildFile {
141        /// The directory.
142        directory: Directory,
143        /// The build file whose `subdir` call requested it; `None` for the workspace root.
144        requested_by: Option<Provenance>,
145    },
146    /// A value in a declaration did not satisfy its grammar.
147    #[error(
148        "{provenance}{}: declaration {order}: invalid {field}: {source}",
149        plugin_suffix(.origin)
150    )]
151    InvalidDeclaration {
152        /// The build file.
153        provenance: Provenance,
154        /// Whose code made the declaration.
155        origin: Origin,
156        /// The call's position in the file.
157        order: DeclarationOrder,
158        /// The field holding the value.
159        field: DeclarationField,
160        /// The grammar failure.
161        #[source]
162        source: Box<Self>,
163    },
164    /// A target named both or neither of `rule` and `run`.
165    #[error(
166        "{provenance}{}: declaration {order}: a target names {found}",
167        plugin_suffix(.origin)
168    )]
169    ActionConflict {
170        /// The build file.
171        provenance: Provenance,
172        /// Whose code made the declaration.
173        origin: Origin,
174        /// The call's position in the file.
175        order: DeclarationOrder,
176        /// What was found instead of exactly one.
177        found: ActionFound,
178    },
179    /// Two evaluations of the same workspace declared different things.
180    #[error("{provenance}: declarations differ between two evaluations")]
181    Nondeterministic {
182        /// The build file to fix: the one whose declaration the other evaluation lacks.
183        provenance: Provenance,
184        /// The first evaluation's declaration at the first difference; `None` past its end.
185        first_run: Option<Box<Declaration>>,
186        /// The second evaluation's declaration at the first difference; `None` past its end.
187        second_run: Option<Box<Declaration>>,
188    },
189    /// The build files, evaluated with the results of the discovery targets, declared different
190    /// discovery targets than they did without them.
191    #[error(
192        "{provenance}: discovery target {label} differs once discovery results are read; a \
193         discovery target may not depend on a discovery result"
194    )]
195    DiscoveryChanged {
196        /// The first discovery target, in declaration order, that one evaluation declared and
197        /// the other did not or declared differently.
198        label: Label,
199        /// The build file that declares it.
200        provenance: Provenance,
201    },
202    /// A label was declared more than once, as any mix of target, rule and alias.
203    #[error("{label} is declared more than once: {}", declaring_sites(.sites))]
204    DuplicateLabel {
205        /// The label.
206        label: Label,
207        /// Every declaration of it, with its build file and whose code made it, in the
208        /// declarations' own order.
209        sites: Vec<DeclarationSite>,
210    },
211    /// A build setting was declared more than once.
212    #[error("setting {name} is declared more than once: {}", sites_list(.sites))]
213    DuplicateSetting {
214        /// The setting.
215        name: SettingName,
216        /// The build file of every declaration of it, in the declarations' own order.
217        sites: Vec<Provenance>,
218    },
219    /// A reference names a label nothing declares.
220    #[error(
221        "{}: {field} {reference} is not declared{}",
222        .site,
223        suggestion_suffix(.suggestion.as_ref())
224    )]
225    UnknownReference {
226        /// The declaration holding the reference, and its build file.
227        site: Box<DeclarationSite>,
228        /// Which field holds it: a dependency, a rule reference or an alias's target.
229        field: DeclarationField,
230        /// The label that was named.
231        reference: Label,
232        /// The nearest declared label the field could have named, if one is near enough.
233        suggestion: Option<Label>,
234    },
235    /// A reference names a declaration of a kind its field cannot name.
236    #[error(
237        "{}: {field} {reference} names {}, declared in {declared_in}",
238        .site,
239        .found.with_article()
240    )]
241    WrongReferenceKind {
242        /// The declaration holding the reference, and its build file.
243        site: Box<DeclarationSite>,
244        /// Which field holds it: a dependency, a rule reference or an alias's target.
245        field: DeclarationField,
246        /// The label that was named.
247        reference: Label,
248        /// What that label was declared as.
249        found: DeclaredKind,
250        /// The build file that declared it.
251        declared_in: Provenance,
252    },
253    /// A command references a build setting nothing declares.
254    #[error(
255        "{}: setting {name} is not declared{}",
256        .site,
257        suggestion_suffix(.suggestion.as_ref())
258    )]
259    UnknownSetting {
260        /// The target or rule holding the reference in its command, or the rule holding it in
261        /// its description, and its build file.
262        site: Box<DeclarationSite>,
263        /// The name after `$opt:`, as written.
264        name: String,
265        /// The nearest declared setting, if one is near enough.
266        suggestion: Option<SettingName>,
267    },
268    /// The targets' dependencies form a cycle.
269    #[error("dependency cycle: {}", cycle_path(.path))]
270    DependencyCycle {
271        /// The targets on the cycle, lowest label first; each depends on the next, and the last
272        /// on the first.
273        path: Vec<DeclarationSite>,
274    },
275    /// The workspace declares more targets than the graph has ids for.
276    #[error("{count} targets are more than a graph can number")]
277    TooManyTargets {
278        /// How many targets were declared.
279        count: usize,
280    },
281    /// A build wants something its workspace's ceiling does not allow.
282    #[error("{}", refusal(.want, .site.as_deref(), .ceiling))]
283    Refused {
284        /// What was wanted.
285        want: Want,
286        /// The lowest-labelled target wanting it, and its build file; `None` for a directory
287        /// the build writes into, which the workspace names and no target declares.
288        site: Option<Box<DeclarationSite>>,
289        /// What the workspace allows.
290        ceiling: Box<Ceiling>,
291    },
292    /// A plugin's target wants something its plugin does not allow.
293    #[error("{}: {}", .violation.site, .violation)]
294    PluginRefused {
295        /// The want, the target that made it, and the plugin that does not allow it.
296        violation: Box<PluginViolation>,
297    },
298    /// The approver did not approve what a build wants.
299    #[error("{}", denial(.reason, .unapproved))]
300    NotApproved {
301        /// What was not approved.
302        unapproved: Box<WantedSet>,
303        /// Why, in words for the user.
304        reason: DenialReason,
305    },
306    /// A command names a program that cannot be found.
307    #[error(
308        "{}: program {program} was not found",
309        .site
310    )]
311    MissingTool {
312        /// The lowest-labelled target whose command names the program, and its build file.
313        site: Box<DeclarationSite>,
314        /// The program.
315        program: Program,
316    },
317    /// A target's `env` is a list, or holds a list entry, where each variable needs a mark.
318    #[error(
319        "{}: env must mark each variable \"key\" or \"unkeyed\", such as env = {{ HOME = \"unkeyed\" }}",
320        .site
321    )]
322    EnvNotMarked {
323        /// The target, and its build file.
324        site: Box<DeclarationSite>,
325    },
326    /// A target marks a variable with something other than `"key"` or `"unkeyed"`.
327    #[error(
328        "{}: env {name} is marked {found}; mark it \"key\" or \"unkeyed\"",
329        .site
330    )]
331    EnvBadMark {
332        /// The target, and its build file.
333        site: Box<DeclarationSite>,
334        /// The variable.
335        name: EnvName,
336        /// The mark as a refusal shows it: the written word in quotes, or the kind of value.
337        found: String,
338    },
339    /// A command holds one of this machine's folders, which would give its target another key on
340    /// every machine.
341    #[error(
342        "{}: the command holds this machine's path {folder}; it would give the target another \
343         key on every machine",
344        .site
345    )]
346    MachinePathInCommand {
347        /// The target or rule whose command holds it, and its build file.
348        site: Box<DeclarationSite>,
349        /// The longest of this machine's folders the command holds.
350        folder: String,
351    },
352    /// The value of a variable a target marks `key` holds one of this machine's folders.
353    #[error(
354        "{}: the variable {name} holds this machine's path {folder}; mark it \"unkeyed\" if it \
355         only finds files",
356        .site
357    )]
358    MachinePathInVariable {
359        /// The first target, in graph order, that marks the variable `key`, and its build file.
360        site: Box<DeclarationSite>,
361        /// The variable.
362        name: EnvName,
363        /// The longest of this machine's folders the value holds.
364        folder: String,
365    },
366    /// The value of a setting a target's command names holds one of this machine's folders.
367    #[error(
368        "{}: the setting {name} holds this machine's path {folder}; it would give the target \
369         another key on every machine",
370        .site
371    )]
372    MachinePathInSetting {
373        /// The first target, in graph order, whose command names the setting, and its build file.
374        site: Box<DeclarationSite>,
375        /// The setting.
376        name: SettingName,
377        /// The longest of this machine's folders the value holds.
378        folder: String,
379    },
380    /// The output of a discovery target holds one of this machine's folders.
381    #[error("{}: its output holds this machine's path {folder}", .site)]
382    MachinePathInDiscovery {
383        /// The discovery target, and its build file.
384        site: Box<DeclarationSite>,
385        /// The longest of this machine's folders the output holds.
386        folder: String,
387    },
388    /// An `env.unkeyed` list names a variable the same table's `env.read` does not.
389    #[error("{file}: {table} env.unkeyed lists {name}, which env.read does not")]
390    UnkeyedNotRead {
391        /// The file the list is in, as the diagnostic names it.
392        file: String,
393        /// The table holding the list, as the diagnostic names it.
394        table: String,
395        /// The variable.
396        name: EnvName,
397    },
398    /// A target declares an environment variable the workspace's execution strategy sets itself.
399    #[error(
400        "{}: env {name} is set to {value} by the sandbox and cannot be declared",
401        .site
402    )]
403    PinnedEnv {
404        /// The variable.
405        name: EnvName,
406        /// The value the strategy gives it.
407        value: EnvValue,
408        /// The lowest-labelled target declaring the variable, and its build file.
409        site: Box<DeclarationSite>,
410    },
411    /// A target reads a workspace file that does not exist.
412    #[error(
413        "{}: input {path} does not exist",
414        .site
415    )]
416    MissingInput {
417        /// The lowest-labelled target declaring the input, and its build file.
418        site: Box<DeclarationSite>,
419        /// The file.
420        path: SourcePath,
421    },
422    /// A target reads a workspace path that holds something other than a regular file.
423    #[error(
424        "{}: input {path} is {found}; an input must be a regular file",
425        .site
426    )]
427    InputNotAFile {
428        /// The lowest-labelled target declaring the input, and its build file.
429        site: Box<DeclarationSite>,
430        /// The path.
431        path: SourcePath,
432        /// What stands there.
433        found: InputKind,
434    },
435    /// A setting was given a value for this run, but nothing declares it.
436    #[error("setting {name} is overridden but not declared")]
437    UnknownOverride {
438        /// The setting that was named.
439        name: SettingName,
440    },
441    /// A run or a query was asked for a target, and no target or alias has that label.
442    #[error(
443        "target {label} was asked for but is not declared{}",
444        suggestion_suffix(.suggestion.as_ref())
445    )]
446    UnknownTarget {
447        /// The label that was asked for.
448        label: Label,
449        /// The nearest declared target or alias, if one is near enough.
450        suggestion: Option<Label>,
451    },
452    /// A test run was asked for a target that is not a test.
453    #[error(
454        "target {asked} was asked for as a test, but {} is declared with {} in {}",
455        .site.label,
456        .declared_with.declaring_function(),
457        .site.located()
458    )]
459    NotATest {
460        /// The label that was asked for.
461        asked: Label,
462        /// The role the target it names was declared with, which says which function declared it.
463        declared_with: TargetRole,
464        /// The target it names, which is the same label unless an alias was followed, and its
465        /// build file.
466        site: Box<DeclarationSite>,
467    },
468    /// A query was written in neither of the two forms a query takes.
469    #[error("query `{expression}` is not deps(<target>) or rdeps(<target>)")]
470    InvalidQuery {
471        /// The query as it was written.
472        expression: String,
473    },
474    /// A log was asked for a target with no run in it.
475    #[error(
476        "target {label} has no run in the log{}{}",
477        suggestion_suffix(.suggestion.as_ref()),
478        damaged_suffix(.damaged)
479    )]
480    NoRun {
481        /// The label that was asked for.
482        label: Label,
483        /// The nearest label the log has a run for, if one is near enough.
484        suggestion: Option<Label>,
485        /// Every damaged line of the log, by number, in order: one of them may have been this
486        /// target's run.
487        damaged: Vec<NonZeroUsize>,
488    },
489    /// What a target printed in its last logged run is no longer in the content store.
490    #[error("target {label}: the output of its last logged run is no longer in the store")]
491    MissingOutput {
492        /// The target whose output is gone.
493        label: Label,
494    },
495    /// A plan was handed over with a graph it was not made from.
496    #[error("the plan was not made from this graph")]
497    ForeignPlan,
498    /// Uploading to the remote cache, or having the remote run actions, was asked for, and
499    /// actions run bare.
500    ///
501    /// A bare action can read files it did not declare, so a result it produced is not known to
502    /// depend only on its declared inputs, and no one else could trust it.
503    #[error("{}", which.diagnostic())]
504    UploadUnsandboxed {
505        /// What was asked for.
506        which: UnsandboxedRemote,
507    },
508    /// The remote cache's token is named, and cannot be used: the variable is unset or not text,
509    /// the file is unreadable, or the token holds a character a header cannot carry.
510    ///
511    /// The error names where the token should have come from and never holds the token itself.
512    #[error(
513        "the remote cache token from {} cannot be used: it is missing or unreadable, \
514         or it holds a character a header cannot carry",
515        token_source(.from)
516    )]
517    RemoteToken {
518        /// The variable or file the token was to come from.
519        from: TokenSource,
520    },
521    /// A remote cache switch variable holds something other than `1` or `0`.
522    #[error("{name} is {value:?}, and must be 1 or 0")]
523    RemoteSwitch {
524        /// The variable.
525        name: RemoteVariable,
526        /// What it holds, as text.
527        value: String,
528    },
529    /// The remote cache flags of a run contradict each other or the workspace.
530    #[error("{conflict}")]
531    RemoteFlags {
532        /// What is wrong with the combination.
533        conflict: RemoteFlagConflict,
534    },
535    /// Two outputs would be written to one place: the same path, or a path that another output
536    /// needs as a directory.
537    #[error(
538        "{path}: {} ({}) and {} ({}) cannot both write here",
539        .first.label,
540        .first.located(),
541        .second.label,
542        .second.located()
543    )]
544    OutputConflict {
545        /// The shorter of the two paths: the one both outputs need.
546        path: OutputPath,
547        /// The lower-labelled of the two targets, and its build file.
548        first: Box<DeclarationSite>,
549        /// The other target, and its build file; the same target when it declares both outputs.
550        second: Box<DeclarationSite>,
551    },
552    /// A command names no program once its placeholders are expanded: it expanded to no
553    /// argument, or its first argument is empty or still holds a `$`.
554    #[error(
555        "{}: the command names no program once expanded",
556        .site
557    )]
558    NoProgram {
559        /// The target whose command it is, and its build file.
560        site: Box<DeclarationSite>,
561    },
562    /// The dispatcher returned success and left targets without an outcome: it lost a task, or
563    /// the result of one, and with it everything that waited on that target.
564    ///
565    /// Not an [`Error::Adapter`]: that carries an adapter's own failure as text for display,
566    /// while this names the targets left without an outcome, as data.
567    #[error("{}", lost_by_the_dispatcher(.targets))]
568    DispatcherFault {
569        /// The targets without an outcome. Never empty; in label order.
570        targets: Vec<Label>,
571    },
572    /// The dispatcher returned success and left build files unevaluated: it lost a task, or the
573    /// result of one.
574    ///
575    /// The load's counterpart of [`Error::DispatcherFault`], naming directories, not targets.
576    #[error("{}", lost_build_files(.directories))]
577    LostBuildFiles {
578        /// The directories whose build file was not evaluated. Never empty; in directory order.
579        directories: Vec<Directory>,
580    },
581    /// An adapter could not do what a port asked of it.
582    #[error("{port}: {diagnostic}")]
583    Adapter {
584        /// The port whose adapter failed.
585        port: PortName,
586        /// The adapter's message, for display only.
587        diagnostic: Diagnostic,
588    },
589    /// A list of files is not a directory tree.
590    #[error("not a tree: {fault}")]
591    InvalidTree {
592        /// What is wrong with the list.
593        fault: TreeFault,
594    },
595    /// A plugin's directory holds something other than regular files with Unicode names.
596    #[error(
597        "plugin {plugin}: {} is not a regular file with a Unicode name; a plugin holds regular files only",
598        .path.display()
599    )]
600    PluginTree {
601        /// The plugin.
602        plugin: PluginName,
603        /// The first such path found.
604        path: PathBuf,
605    },
606    /// A plugin `buildl.toml` names is not there to use: it is a directory that does not
607    /// exist, a git plugin that `buildl.lock` does not pin as `buildl.toml` names it or whose
608    /// store is missing, or a git revision that holds no file, or no folder at the plugin's `dir`.
609    #[error("plugin {plugin} is not fetched: {reason}")]
610    PluginNotFetched {
611        /// The plugin.
612        plugin: PluginName,
613        /// What is missing, and what to do about it.
614        reason: String,
615    },
616    /// A plugin's files are not the ones `buildl.lock` pinned: the store was changed after the
617    /// plugin was fetched.
618    #[error("plugin {plugin} was changed after it was fetched: {reason}")]
619    PluginChanged {
620        /// The plugin.
621        plugin: PluginName,
622        /// How the files differ from the lock.
623        reason: String,
624    },
625    /// `git` could not fetch a plugin: it is not installed, or it refused the repository, the
626    /// revision or the checkout.
627    #[error("plugin {plugin} could not be fetched: {diagnostic}")]
628    PluginFetch {
629        /// The plugin.
630        plugin: PluginName,
631        /// What `git` printed, or why it could not be run, for display only.
632        diagnostic: Diagnostic,
633    },
634}
635
636/// A lost load as one sentence naming the port at fault and the directories whose build file it
637/// left unevaluated, the workspace root shown as `//`.
638fn lost_build_files(directories: &[Directory]) -> String {
639    let shown: Vec<String> = directories.iter().map(|d| format!("//{d}")).collect();
640    format!(
641        "{}: returned without evaluating the build files of {}",
642        PortName::Dispatcher,
643        shown.join(", ")
644    )
645}
646
647/// A dispatcher fault as one sentence naming the port at fault and the targets it left without
648/// an outcome.
649fn lost_by_the_dispatcher(targets: &[Label]) -> String {
650    let labels: Vec<String> = targets.iter().map(ToString::to_string).collect();
651    format!(
652        "{}: returned without an outcome for {}",
653        PortName::Dispatcher,
654        labels.join(", ")
655    )
656}
657
658/// Where a token is read from, as a phrase: `environment variable NAME` or `file PATH`.
659fn token_source(from: &TokenSource) -> String {
660    match from {
661        TokenSource::Env(name) => format!("environment variable {name}"),
662        TokenSource::File(path) => format!("file {path}"),
663    }
664}
665
666/// The suffix naming who required a missing build file.
667fn requested_by_suffix(requested_by: Option<&Provenance>) -> String {
668    requested_by.map_or_else(
669        || " (the workspace root)".to_owned(),
670        |provenance| format!(" (requested by {provenance})"),
671    )
672}
673
674/// The build files of a duplicated name, separated by commas.
675fn sites_list(sites: &[Provenance]) -> String {
676    let rendered: Vec<String> = sites.iter().map(ToString::to_string).collect();
677    rendered.join(", ")
678}
679
680/// The build file of every declaration of a duplicated label, separated by commas, each followed
681/// by the plugin chain when a plugin made it.
682fn declaring_sites(sites: &[DeclarationSite]) -> String {
683    let rendered: Vec<String> = sites
684        .iter()
685        .map(|site| format!("{}{}", site.provenance, plugin_suffix(&site.origin)))
686        .collect();
687    rendered.join(", ")
688}
689
690/// ` (plugin <chain>)` when a plugin made the declaration; nothing for a build file.
691fn plugin_suffix(origin: &Origin) -> String {
692    match origin {
693        Origin::BuildFile => String::new(),
694        chain @ Origin::Plugins(_) => format!(" (plugin {chain})"),
695    }
696}
697
698/// The suffix offering the nearest declared name, when there is one.
699fn suggestion_suffix<T: fmt::Display>(suggestion: Option<&T>) -> String {
700    suggestion.map_or_else(String::new, |nearest| format!(" (did you mean {nearest}?)"))
701}
702
703/// The suffix counting the damaged lines of a log, when there are any.
704fn damaged_suffix(damaged: &[NonZeroUsize]) -> String {
705    let numbers: Vec<String> = damaged.iter().map(ToString::to_string).collect();
706    match numbers.as_slice() {
707        [] => String::new(),
708        [only] => format!("; 1 damaged line was skipped (line {only})"),
709        many => format!(
710            "; {} damaged lines were skipped (lines {})",
711            many.len(),
712            many.join(", ")
713        ),
714    }
715}
716
717/// A cycle as its labels and build files, closed by repeating the first label.
718fn cycle_path(path: &[DeclarationSite]) -> String {
719    let mut rendered: Vec<String> = path
720        .iter()
721        .map(|site| format!("{} ({})", site.label, site.located()))
722        .collect();
723    if let Some(first) = path.first() {
724        rendered.push(first.label.to_string());
725    }
726    rendered.join(" -> ")
727}
728
729/// A denial as its reason, then the wants it covers on lines of their own; the reason alone when
730/// the set is empty.
731fn denial(reason: &DenialReason, unapproved: &WantedSet) -> String {
732    if unapproved.is_empty() {
733        reason.to_string()
734    } else {
735        format!("{reason}\n{unapproved}")
736    }
737}
738
739/// A refusal as one sentence: who wanted what, and what the ceiling allows of that kind.
740fn refusal(want: &Want, site: Option<&DeclarationSite>, ceiling: &Ceiling) -> String {
741    let (wanted, list, allowed) = match want {
742        Want::Program(program) => (
743            format!("program {program}"),
744            "proc.run",
745            allowed_list(&ceiling.run),
746        ),
747        Want::Env(name) => (
748            format!("environment variable {name}"),
749            "env.read",
750            allowed_list(&ceiling.env),
751        ),
752        Want::Unkeyed(name) => (
753            format!("unkeyed variable {name}"),
754            "env.unkeyed",
755            allowed_list(&ceiling.unkeyed),
756        ),
757        Want::Read(path) => (
758            format!("input {path}"),
759            "fs.read",
760            allowed_list(ceiling.read.iter().map(directory_text)),
761        ),
762        Want::Write(directory) => (
763            format!("directory {}", directory_text(directory)),
764            "fs.write",
765            allowed_list(ceiling.write.iter().map(directory_text)),
766        ),
767        Want::Network(label) => (
768            format!("network of {label}"),
769            "network",
770            "nothing".to_owned(),
771        ),
772    };
773    let holder = site.map_or_else(String::new, |site| format!("{site}: "));
774    format!("{holder}{wanted} is outside the ceiling ({list} allows: {allowed})")
775}
776
777/// The entries of one ceiling list, separated by commas; `nothing` for an empty list.
778pub(crate) fn allowed_list<T: fmt::Display>(entries: impl IntoIterator<Item = T>) -> String {
779    let rendered: Vec<String> = entries.into_iter().map(|entry| entry.to_string()).collect();
780    if rendered.is_empty() {
781        "nothing".to_owned()
782    } else {
783        rendered.join(", ")
784    }
785}
786
787/// A directory as a refusal shows it: the workspace root, whose text is empty, as `.`.
788pub(crate) fn directory_text(directory: &Directory) -> &str {
789    if directory.is_root() {
790        "."
791    } else {
792        directory.as_str()
793    }
794}
795
796/// What a label was declared as.
797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
798#[non_exhaustive]
799pub enum DeclaredKind {
800    /// A build or test target.
801    Target,
802    /// A rule.
803    Rule,
804    /// An alias.
805    Alias,
806}
807
808impl DeclaredKind {
809    /// The kind with its indefinite article, for a sentence.
810    const fn with_article(self) -> &'static str {
811        match self {
812            Self::Target => "a target",
813            Self::Rule => "a rule",
814            Self::Alias => "an alias",
815        }
816    }
817}
818
819impl fmt::Display for DeclaredKind {
820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821        f.write_str(match self {
822            Self::Target => "target",
823            Self::Rule => "rule",
824            Self::Alias => "alias",
825        })
826    }
827}
828
829/// A declared label, the build file that declared it, and whose code made the declaration.
830///
831/// Names the declaration an error is about: the one holding a bad reference, one target on a
832/// dependency cycle, one declaration of a duplicated label, or the target a test run named that
833/// is not a test. Displays as `<file>: <label>`, followed by `(plugin <chain>)` when a
834/// plugin made the declaration.
835#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct DeclarationSite {
837    /// The declared label.
838    pub label: Label,
839    /// The build file that declared it.
840    pub provenance: Provenance,
841    /// Whose code made the declaration: the build file itself, or a plugin chain.
842    pub origin: Origin,
843}
844
845impl DeclarationSite {
846    /// The build file, then the plugin chain when a plugin made the declaration: `build.lua` or
847    /// `build.lua, plugin ourgo@0.1.0 > go@1.2.0`.
848    fn located(&self) -> String {
849        match &self.origin {
850            Origin::BuildFile => self.provenance.to_string(),
851            chain @ Origin::Plugins(_) => format!("{}, plugin {chain}", self.provenance),
852        }
853    }
854}
855
856impl fmt::Display for DeclarationSite {
857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858        write!(
859            f,
860            "{}: {}{}",
861            self.provenance,
862            self.label,
863            plugin_suffix(&self.origin)
864        )
865    }
866}
867
868impl From<&Node> for DeclarationSite {
869    /// The site of a graph node: its label, the build file that declared it, and its origin.
870    fn from(node: &Node) -> Self {
871        Self {
872            label: node.label.clone(),
873            provenance: node.provenance.clone(),
874            origin: node.origin.clone(),
875        }
876    }
877}
878
879/// Which port an [`Error::Adapter`] came through.
880///
881/// Non-exhaustive for the same reason [`Error`] is: a new port is not a breaking change.
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883#[non_exhaustive]
884pub enum PortName {
885    /// The workspace manifest.
886    Manifest,
887    /// The machine actions run on.
888    Host,
889    /// File metadata and content digests.
890    Digester,
891    /// The recorded digests of files already hashed.
892    StatCache,
893    /// The programs commands name.
894    ToolResolver,
895    /// The recorded results of earlier builds.
896    ActionCache,
897    /// The store of content by digest: outputs, and what actions printed.
898    ContentStore,
899    /// The build log.
900    EventLog,
901    /// The build log, read back.
902    RunHistory,
903    /// What runs an action.
904    ExecStrategy,
905    /// What hands actions to workers.
906    Dispatcher,
907    /// The record of the graph a build resolved.
908    GraphRecord,
909    /// What lists and removes what the content store holds.
910    Sweep,
911    /// What settles whether a build may run.
912    Approver,
913    /// Where plugins are fetched to and the lock that pins them.
914    PluginStore,
915    /// The cache of results shared between machines.
916    RemoteCache,
917    /// What reports changed files in the workspace.
918    Changes,
919}
920
921impl fmt::Display for PortName {
922    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923        f.write_str(match self {
924            Self::Manifest => "manifest",
925            Self::Host => "host",
926            Self::Digester => "digester",
927            Self::StatCache => "stat cache",
928            Self::ToolResolver => "tool resolver",
929            Self::ActionCache => "action cache",
930            Self::ContentStore => "content store",
931            Self::EventLog => "event log",
932            Self::RunHistory => "run history",
933            Self::ExecStrategy => "exec strategy",
934            Self::Dispatcher => "dispatcher",
935            Self::GraphRecord => "graph record",
936            Self::Sweep => "sweep",
937            Self::Approver => "approver",
938            Self::PluginStore => "plugin store",
939            Self::RemoteCache => "remote cache",
940            Self::Changes => "file watcher",
941        })
942    }
943}
944
945/// A ceiling an evaluation can reach.
946#[derive(Debug, Clone, Copy, PartialEq, Eq)]
947#[non_exhaustive]
948pub enum EvaluationLimit {
949    /// The instruction ceiling.
950    Instructions,
951    /// The memory ceiling.
952    Memory,
953    /// The byte budget on what one file may stage: the in-memory size of each staged record plus
954    /// the byte length of its text, up to the memory ceiling.
955    Staging,
956    /// The cap on directory entries the host-side source walk may visit for one build file.
957    Walk,
958}
959
960impl fmt::Display for EvaluationLimit {
961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962        f.write_str(match self {
963            Self::Instructions => "instruction ceiling",
964            Self::Memory => "memory ceiling",
965            Self::Staging => "staging cap",
966            Self::Walk => "walk cap",
967        })
968    }
969}
970
971/// How an adapter failed to evaluate one build file.
972///
973/// Closed for an adapter, which reports every failure through it without a new variant; open
974/// for a caller matching on it, which keeps a wildcard arm.
975#[derive(Debug, Clone, PartialEq, Eq)]
976#[non_exhaustive]
977pub enum EvaluationFailure {
978    /// The build file does not parse.
979    Syntax,
980    /// Evaluation raised an error.
981    Runtime,
982    /// The runtime refused an operation the declaration policy does not grant.
983    Refused,
984    /// A ceiling was reached.
985    LimitReached {
986        /// Which ceiling.
987        limit: EvaluationLimit,
988    },
989    /// An option table holds a field its primitive does not accept.
990    UnknownField {
991        /// The field, as written.
992        field: Written<FieldName>,
993    },
994    /// A field holds a value of the wrong type.
995    WrongFieldType {
996        /// The field, as written.
997        field: Written<FieldName>,
998    },
999}
1000
1001impl fmt::Display for EvaluationFailure {
1002    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1003        match self {
1004            Self::Syntax => f.write_str("syntax error"),
1005            Self::Runtime => f.write_str("runtime error"),
1006            Self::Refused => f.write_str("operation refused"),
1007            Self::LimitReached { limit } => write!(f, "{limit} reached"),
1008            Self::UnknownField { field } => write!(f, "unknown field {:?}", field.as_written()),
1009            Self::WrongFieldType { field } => {
1010                write!(f, "field {:?} has the wrong type", field.as_written())
1011            }
1012        }
1013    }
1014}
1015
1016/// Which field of a declaration an [`Error::InvalidDeclaration`] is about.
1017#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1018#[non_exhaustive]
1019pub enum DeclarationField {
1020    /// A target's, rule's or alias's name.
1021    Name,
1022    /// An entry of `deps`.
1023    Dep,
1024    /// An entry of `inputs`.
1025    Input,
1026    /// An entry of `outputs`.
1027    Output,
1028    /// An entry of `env`.
1029    Env,
1030    /// The `run` command or one of its arguments.
1031    Run,
1032    /// The `rule` reference.
1033    Rule,
1034    /// A rule's `desc`.
1035    Description,
1036    /// An alias's target.
1037    Target,
1038    /// A setting's name.
1039    SettingName,
1040    /// A setting's default value.
1041    SettingValue,
1042    /// A target's `always` flag.
1043    Freshness,
1044    /// A target's `stdout` flag.
1045    Stdout,
1046    /// A `subdir` request.
1047    Subdir,
1048}
1049
1050impl fmt::Display for DeclarationField {
1051    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1052        f.write_str(match self {
1053            Self::Name => "name",
1054            Self::Dep => "dep",
1055            Self::Input => "input",
1056            Self::Output => "output",
1057            Self::Env => "env",
1058            Self::Run => "run",
1059            Self::Rule => "rule",
1060            Self::Description => "description",
1061            Self::Target => "target",
1062            Self::SettingName => "setting name",
1063            Self::SettingValue => "setting value",
1064            Self::Freshness => "freshness",
1065            Self::Stdout => "stdout",
1066            Self::Subdir => "subdir",
1067        })
1068    }
1069}
1070
1071/// What an [`Error::ActionConflict`] found instead of exactly one of `rule` and `run`.
1072#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1073pub enum ActionFound {
1074    /// Both were given.
1075    Both,
1076    /// Neither was given.
1077    Neither,
1078}
1079
1080impl fmt::Display for ActionFound {
1081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082        f.write_str(match self {
1083            Self::Both => "both 'rule' and 'run'",
1084            Self::Neither => "neither 'rule' nor 'run'",
1085        })
1086    }
1087}
1088
1089/// What a run asked of the remote that actions run bare cannot give.
1090///
1091/// Non-exhaustive for the same reason [`Error`] is.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1093#[non_exhaustive]
1094pub enum UnsandboxedRemote {
1095    /// Sending what ran here to the remote cache.
1096    Upload,
1097    /// Having the remote run the actions its cache cannot answer. When a run asks for both, this
1098    /// is the one named.
1099    Execute,
1100}
1101
1102impl UnsandboxedRemote {
1103    /// The whole refusal: what was asked for, why bare cannot give it, and the ways out.
1104    const fn diagnostic(self) -> &'static str {
1105        match self {
1106            Self::Upload => {
1107                "uploading to the remote cache needs actions to run in the input sandbox, \
1108                 but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
1109                 unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
1110            }
1111            Self::Execute => {
1112                "executing on the remote needs actions to run in the input sandbox, \
1113                 but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
1114                 setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
1115                 dropping --remote-execute"
1116            }
1117        }
1118    }
1119}
1120
1121/// The variable of a remote cache switch.
1122///
1123/// Non-exhaustive for the same reason [`Error`] is.
1124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1125#[non_exhaustive]
1126pub enum RemoteVariable {
1127    /// `BUILDL_REMOTE_UPLOAD`, which turns uploading on.
1128    Upload,
1129    /// `BUILDL_REMOTE_STRICT`, which makes a remote failure fail the build.
1130    Strict,
1131    /// `BUILDL_REMOTE_EXECUTE`, which turns remote execution on.
1132    Execute,
1133}
1134
1135impl fmt::Display for RemoteVariable {
1136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1137        f.write_str(match self {
1138            Self::Upload => "BUILDL_REMOTE_UPLOAD",
1139            Self::Strict => "BUILDL_REMOTE_STRICT",
1140            Self::Execute => "BUILDL_REMOTE_EXECUTE",
1141        })
1142    }
1143}
1144
1145/// A combination of remote cache flags that an [`Error::RemoteFlags`] refuses.
1146///
1147/// Non-exhaustive for the same reason [`Error`] is.
1148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1149#[non_exhaustive]
1150pub enum RemoteFlagConflict {
1151    /// `--no-remote` together with `--remote-upload` or `--remote-strict`.
1152    NoRemoteWithSwitch,
1153    /// `--remote-upload` or `--remote-strict` in a workspace whose `buildl.toml` has no
1154    /// `[remote]` table.
1155    SwitchWithoutRemote,
1156    /// `--remote-execute` together with `--no-remote`.
1157    NoRemoteWithExecute,
1158    /// `--remote-execute` together with `--no-remote-execute`.
1159    ExecuteBothWays,
1160    /// `--remote-execute`, `--no-remote-execute` or `--remote-jobs` in a workspace whose
1161    /// `buildl.toml` has no `[remote]` table.
1162    ExecutionWithoutRemote,
1163    /// `--remote-jobs` in a run where remote execution is off.
1164    JobsWithoutExecution,
1165}
1166
1167impl fmt::Display for RemoteFlagConflict {
1168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1169        f.write_str(match self {
1170            Self::NoRemoteWithSwitch => {
1171                "--no-remote cannot be combined with --remote-upload or --remote-strict"
1172            }
1173            Self::SwitchWithoutRemote => {
1174                "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
1175                 and this workspace has none"
1176            }
1177            Self::NoRemoteWithExecute => "--no-remote cannot be combined with --remote-execute",
1178            Self::ExecuteBothWays => "--remote-execute cannot be combined with --no-remote-execute",
1179            Self::ExecutionWithoutRemote => {
1180                "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
1181                 in buildl.toml, and this workspace has none"
1182            }
1183            Self::JobsWithoutExecution => {
1184                "--remote-jobs needs remote execution, and it is off in this run"
1185            }
1186        })
1187    }
1188}
1189
1190/// Which domain name an [`Error::InvalidName`] is about.
1191///
1192/// A type rather than a string so classification is read as a field. Non-exhaustive for the same
1193/// reason [`Error`] is.
1194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1195#[non_exhaustive]
1196pub enum NameKind {
1197    /// A workspace-relative directory path.
1198    Directory,
1199    /// The name half of a label.
1200    TargetName,
1201    /// A whole label.
1202    Label,
1203    /// A content digest.
1204    Digest,
1205    /// A workspace-relative source file path.
1206    SourcePath,
1207    /// A path inside a target's output directory.
1208    OutputName,
1209    /// An environment variable name.
1210    EnvName,
1211    /// One element of a command's argument vector.
1212    Argument,
1213    /// A whole command: a non-empty argument vector.
1214    Command,
1215    /// A rule's one-line description.
1216    Description,
1217    /// A build setting's name.
1218    SettingName,
1219    /// A build setting's value.
1220    SettingValue,
1221    /// The file name every directory's build file has.
1222    EntryName,
1223    /// A field name in a declaration's option table.
1224    FieldName,
1225    /// The name of a program a command runs.
1226    Program,
1227    /// An environment variable's value.
1228    EnvValue,
1229    /// A host platform: an operating system and an architecture.
1230    Platform,
1231    /// How many actions a build runs at once.
1232    Workers,
1233    /// How long one action may run.
1234    Timeout,
1235    /// The execution strategy a workspace runs its actions under.
1236    Isolation,
1237    /// How a workspace settles whether a build may run.
1238    Approver,
1239    /// The path of a file inside a directory an action left as an output.
1240    TreePath,
1241    /// How a declared environment variable takes part in an action key.
1242    EnvMark,
1243    /// The name of a plugin.
1244    PluginName,
1245    /// The version text a plugin's manifest states.
1246    PluginVersion,
1247    /// The chain of plugins that declared a target.
1248    PluginChain,
1249    /// A full git commit id.
1250    CommitId,
1251    /// A git tag name.
1252    TagName,
1253    /// The URL of a git repository.
1254    GitUrl,
1255    /// The URL of a remote cache.
1256    RemoteUrl,
1257    /// The instance name a remote cache is addressed under.
1258    InstanceName,
1259    /// A path to a file the host reads, such as a certificate or a token.
1260    HostPath,
1261    /// The name of the request header a remote cache's token is sent in.
1262    HeaderName,
1263    /// A workspace-relative path a file event named.
1264    ChangedPath,
1265    /// How many remote calls a run keeps in flight at once.
1266    RemoteJobs,
1267    /// How many times a failed remote call is tried again.
1268    RetryCount,
1269    /// The name of a platform property asked of the remote executor.
1270    PlatformProperty,
1271}
1272
1273impl fmt::Display for NameKind {
1274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1275        f.write_str(match self {
1276            Self::Directory => "directory",
1277            Self::TargetName => "target name",
1278            Self::Label => "label",
1279            Self::Digest => "digest",
1280            Self::SourcePath => "source path",
1281            Self::OutputName => "output name",
1282            Self::EnvName => "environment variable name",
1283            Self::Argument => "argument",
1284            Self::Command => "command",
1285            Self::Description => "description",
1286            Self::SettingName => "setting name",
1287            Self::SettingValue => "setting value",
1288            Self::EntryName => "entry file name",
1289            Self::FieldName => "field name",
1290            Self::Program => "program",
1291            Self::EnvValue => "environment variable value",
1292            Self::Platform => "platform",
1293            Self::Workers => "worker count",
1294            Self::Timeout => "timeout",
1295            Self::Isolation => "execution strategy",
1296            Self::Approver => "approver mode",
1297            Self::TreePath => "tree path",
1298            Self::EnvMark => "environment variable mark",
1299            Self::PluginName => "plugin name",
1300            Self::PluginVersion => "plugin version",
1301            Self::PluginChain => "plugin chain",
1302            Self::CommitId => "commit id",
1303            Self::TagName => "tag name",
1304            Self::GitUrl => "git URL",
1305            Self::RemoteUrl => "remote cache URL",
1306            Self::InstanceName => "instance name",
1307            Self::HostPath => "host path",
1308            Self::HeaderName => "header name",
1309            Self::ChangedPath => "changed path",
1310            Self::RemoteJobs => "remote job count",
1311            Self::RetryCount => "retry count",
1312            Self::PlatformProperty => "platform property name",
1313        })
1314    }
1315}
1316
1317/// Why a list of files an [`Error::InvalidTree`] is about is not a directory tree.
1318///
1319/// Non-exhaustive for the same reason [`Error`] is.
1320#[derive(Debug, Clone, PartialEq, Eq)]
1321#[non_exhaustive]
1322pub enum TreeFault {
1323    /// It holds no file.
1324    Empty,
1325    /// It lists this path twice.
1326    Repeated(TreePath),
1327    /// It lists a file at this path, and another file below it.
1328    Clash(TreePath),
1329}
1330
1331impl fmt::Display for TreeFault {
1332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333        match self {
1334            Self::Empty => f.write_str("it holds no file"),
1335            Self::Repeated(path) => write!(f, "{path} is listed twice"),
1336            Self::Clash(path) => write!(f, "{path} is both a file and a directory"),
1337        }
1338    }
1339}
1340
1341#[cfg(test)]
1342mod tests {
1343    #![expect(
1344        clippy::unwrap_used,
1345        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
1346    )]
1347
1348    use std::collections::{BTreeMap, BTreeSet};
1349    use std::num::NonZeroUsize;
1350    use std::path::PathBuf;
1351
1352    use super::{
1353        ActionFound, DeclarationField, DeclarationSite, DeclaredKind, Error, EvaluationFailure,
1354        EvaluationLimit, NameKind, PortName, RemoteFlagConflict, RemoteVariable, TreeFault,
1355        UnsandboxedRemote,
1356    };
1357    use crate::types::{
1358        Argument, Ceiling, Command, DeclarationOrder, DenialReason, Diagnostic, Directory, EnvName,
1359        EnvValue, FieldName, Freshness, HostPath, InputKind, Label, NetworkAccess, Node, Origin,
1360        OutputName, OutputPath, OutputSource, PluginName, PluginRef, PluginVersion,
1361        PluginViolation, Program, Provenance, RemoteUrl, SettingName, SourcePath, TargetName,
1362        TargetRole, TokenSource, TreePath, Want, WantedSet, Written,
1363    };
1364
1365    fn lib_file() -> Provenance {
1366        Provenance::new(
1367            PathBuf::from("lib/build.lua"),
1368            Directory::parse("lib").unwrap(),
1369        )
1370    }
1371
1372    fn root_file() -> Provenance {
1373        Provenance::new(PathBuf::from("build.lua"), Directory::root())
1374    }
1375
1376    fn tools_file() -> Provenance {
1377        Provenance::new(
1378            PathBuf::from("tools/build.lua"),
1379            Directory::parse("tools").unwrap(),
1380        )
1381    }
1382
1383    fn label(raw: &str) -> Label {
1384        Label::parse(raw).unwrap()
1385    }
1386
1387    /// The declaration `raw`, declared in the root build file.
1388    fn root_site(raw: &str) -> DeclarationSite {
1389        DeclarationSite {
1390            label: label(raw),
1391            provenance: root_file(),
1392            origin: Origin::BuildFile,
1393        }
1394    }
1395
1396    #[test]
1397    fn duplicate_label_names_every_site() {
1398        let err = Error::DuplicateLabel {
1399            label: label("//:a"),
1400            sites: vec![root_site("//:a"), root_site("//:a")],
1401        };
1402        assert_eq!(
1403            err.to_string(),
1404            "//:a is declared more than once: build.lua, build.lua"
1405        );
1406    }
1407
1408    #[test]
1409    fn duplicate_label_names_the_plugin_chain_of_the_declaration_a_plugin_made() {
1410        let err = Error::DuplicateLabel {
1411            label: label("//:a"),
1412            sites: vec![
1413                root_site("//:a"),
1414                DeclarationSite {
1415                    origin: ourgo_chain(),
1416                    ..root_site("//:a")
1417                },
1418            ],
1419        };
1420        assert_eq!(
1421            err.to_string(),
1422            "//:a is declared more than once: build.lua, build.lua (plugin ourgo@0.1.0 > go@1.2.0)"
1423        );
1424    }
1425
1426    #[test]
1427    fn duplicate_setting_names_every_site() {
1428        let err = Error::DuplicateSetting {
1429            name: SettingName::parse("test_filter").unwrap(),
1430            sites: vec![root_file(), lib_file()],
1431        };
1432        assert_eq!(
1433            err.to_string(),
1434            "setting test_filter is declared more than once: build.lua, lib/build.lua"
1435        );
1436    }
1437
1438    #[test]
1439    fn unknown_reference_names_the_site_the_field_and_the_nearest_label() {
1440        let err = Error::UnknownReference {
1441            site: Box::new(root_site("//:app")),
1442            field: DeclarationField::Dep,
1443            reference: label("//:mian.o"),
1444            suggestion: Some(label("//:main.o")),
1445        };
1446        assert_eq!(
1447            err.to_string(),
1448            "build.lua: //:app: dep //:mian.o is not declared (did you mean //:main.o?)"
1449        );
1450    }
1451
1452    #[test]
1453    fn unknown_reference_without_a_near_label_offers_nothing() {
1454        let err = Error::UnknownReference {
1455            site: Box::new(root_site("//:default")),
1456            field: DeclarationField::Target,
1457            reference: label("//:nope"),
1458            suggestion: None,
1459        };
1460        assert_eq!(
1461            err.to_string(),
1462            "build.lua: //:default: target //:nope is not declared"
1463        );
1464    }
1465
1466    #[test]
1467    fn wrong_reference_kind_names_what_was_found_and_where() {
1468        let err = Error::WrongReferenceKind {
1469            site: Box::new(root_site("//:app")),
1470            field: DeclarationField::Dep,
1471            reference: label("//:cc"),
1472            found: DeclaredKind::Rule,
1473            declared_in: tools_file(),
1474        };
1475        assert_eq!(
1476            err.to_string(),
1477            "build.lua: //:app: dep //:cc names a rule, declared in tools/build.lua"
1478        );
1479    }
1480
1481    #[test]
1482    fn every_declared_kind_renders_alone_and_in_a_sentence() {
1483        let cases = [
1484            (DeclaredKind::Target, "target", "names a target,"),
1485            (DeclaredKind::Rule, "rule", "names a rule,"),
1486            (DeclaredKind::Alias, "alias", "names an alias,"),
1487        ];
1488        for (found, alone, in_a_sentence) in cases {
1489            assert_eq!(found.to_string(), alone);
1490            let err = Error::WrongReferenceKind {
1491                site: Box::new(root_site("//:app")),
1492                field: DeclarationField::Rule,
1493                reference: label("//:x"),
1494                found,
1495                declared_in: root_file(),
1496            };
1497            assert!(err.to_string().contains(in_a_sentence), "{err}");
1498        }
1499    }
1500
1501    #[test]
1502    fn unknown_setting_names_the_site_and_the_nearest_setting() {
1503        let err = Error::UnknownSetting {
1504            site: Box::new(root_site("//:go_test")),
1505            name: "test_fliter".to_owned(),
1506            suggestion: Some(SettingName::parse("test_filter").unwrap()),
1507        };
1508        assert_eq!(
1509            err.to_string(),
1510            "build.lua: //:go_test: setting test_fliter is not declared \
1511             (did you mean test_filter?)"
1512        );
1513    }
1514
1515    #[test]
1516    fn dependency_cycle_lists_every_target_and_closes_on_the_first() {
1517        let err = Error::DependencyCycle {
1518            path: vec![
1519                DeclarationSite {
1520                    label: label("//:a"),
1521                    provenance: root_file(),
1522                    origin: Origin::BuildFile,
1523                },
1524                DeclarationSite {
1525                    label: label("//lib:b"),
1526                    provenance: lib_file(),
1527                    origin: Origin::BuildFile,
1528                },
1529            ],
1530        };
1531        assert_eq!(
1532            err.to_string(),
1533            "dependency cycle: //:a (build.lua) -> //lib:b (lib/build.lua) -> //:a"
1534        );
1535    }
1536
1537    #[test]
1538    fn a_cycle_of_one_names_its_target_twice() {
1539        let err = Error::DependencyCycle {
1540            path: vec![DeclarationSite {
1541                label: label("//:a"),
1542                provenance: root_file(),
1543                origin: Origin::BuildFile,
1544            }],
1545        };
1546        assert_eq!(
1547            err.to_string(),
1548            "dependency cycle: //:a (build.lua) -> //:a"
1549        );
1550    }
1551
1552    #[test]
1553    fn too_many_targets_states_the_count() {
1554        let err = Error::TooManyTargets { count: 7 };
1555        assert_eq!(
1556            err.to_string(),
1557            "7 targets are more than a graph can number"
1558        );
1559    }
1560
1561    #[test]
1562    fn a_site_is_a_nodes_label_and_its_build_file() {
1563        let node = Node {
1564            label: label("//lib:text"),
1565            provenance: lib_file(),
1566            origin: Origin::BuildFile,
1567            narrowing: Vec::new(),
1568            role: TargetRole::Build,
1569            run: Command::new(vec![Argument::parse("cc").unwrap()]).unwrap(),
1570            description: None,
1571            inputs: Vec::new(),
1572            outputs: vec![OutputName::parse("text").unwrap()],
1573            env: BTreeMap::new(),
1574            network: NetworkAccess::Sealed,
1575            output_source: OutputSource::Command,
1576            freshness: Freshness::Cached,
1577        };
1578        assert_eq!(
1579            DeclarationSite::from(&node),
1580            DeclarationSite {
1581                label: label("//lib:text"),
1582                provenance: lib_file(),
1583                origin: Origin::BuildFile,
1584            }
1585        );
1586    }
1587
1588    /// A plugin chain `ourgo@0.1.0 > go@1.2.0`.
1589    fn ourgo_chain() -> Origin {
1590        let plugin = |name: &str, version: &str| PluginRef {
1591            unkeyed: BTreeSet::new(),
1592            name: PluginName::parse(name).unwrap(),
1593            version: PluginVersion::parse(version).unwrap(),
1594            run: BTreeSet::new(),
1595            env: BTreeSet::new(),
1596        };
1597        Origin::plugins(vec![plugin("ourgo", "0.1.0"), plugin("go", "1.2.0")]).unwrap()
1598    }
1599
1600    #[test]
1601    fn a_site_with_a_plugin_origin_names_the_chain() {
1602        let site = DeclarationSite {
1603            origin: ourgo_chain(),
1604            ..root_site("//:app")
1605        };
1606        assert_eq!(
1607            site.to_string(),
1608            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0)"
1609        );
1610        let missing = Error::MissingTool {
1611            site: Box::new(site.clone()),
1612            program: Program::parse("cc").unwrap(),
1613        };
1614        assert_eq!(
1615            missing.to_string(),
1616            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0): program cc was not found"
1617        );
1618        let cycle = Error::DependencyCycle { path: vec![site] };
1619        assert_eq!(
1620            cycle.to_string(),
1621            "dependency cycle: //:app (build.lua, plugin ourgo@0.1.0 > go@1.2.0) -> //:app"
1622        );
1623    }
1624
1625    #[test]
1626    fn a_build_file_site_reads_as_today() {
1627        assert_eq!(root_site("//:app").to_string(), "build.lua: //:app");
1628        let err = Error::MissingTool {
1629            site: Box::new(root_site("//:app")),
1630            program: Program::parse("cc").unwrap(),
1631        };
1632        assert_eq!(
1633            err.to_string(),
1634            "build.lua: //:app: program cc was not found"
1635        );
1636    }
1637
1638    #[test]
1639    fn missing_tool_names_the_site_and_the_program() {
1640        let err = Error::MissingTool {
1641            site: Box::new(root_site("//:app")),
1642            program: Program::parse("cc").unwrap(),
1643        };
1644        assert_eq!(
1645            err.to_string(),
1646            "build.lua: //:app: program cc was not found"
1647        );
1648    }
1649
1650    #[test]
1651    fn pinned_env_renders_its_site_name_and_value() {
1652        let err = Error::PinnedEnv {
1653            name: EnvName::parse("TZ").unwrap(),
1654            value: EnvValue::parse("UTC").unwrap(),
1655            site: Box::new(root_site("//a:y")),
1656        };
1657        assert_eq!(
1658            err.to_string(),
1659            "build.lua: //a:y: env TZ is set to UTC by the sandbox and cannot be declared"
1660        );
1661    }
1662
1663    #[test]
1664    fn missing_input_names_the_site_and_the_path() {
1665        let err = Error::MissingInput {
1666            site: Box::new(root_site("//:app")),
1667            path: SourcePath::parse("src/main.c").unwrap(),
1668        };
1669        assert_eq!(
1670            err.to_string(),
1671            "build.lua: //:app: input src/main.c does not exist"
1672        );
1673    }
1674
1675    #[test]
1676    fn an_input_that_is_not_a_file_names_the_site_the_path_and_what_was_found() {
1677        for (found, text) in [
1678            (
1679                InputKind::Directory,
1680                "build.lua: //:app: input src is a directory; an input must be a regular file",
1681            ),
1682            (
1683                InputKind::Symlink,
1684                "build.lua: //:app: input src is a symbolic link; an input must be a regular file",
1685            ),
1686            (
1687                InputKind::Special,
1688                "build.lua: //:app: input src is a pipe, a socket or a device; an input must be a regular file",
1689            ),
1690        ] {
1691            let err = Error::InputNotAFile {
1692                site: Box::new(root_site("//:app")),
1693                path: SourcePath::parse("src").unwrap(),
1694                found,
1695            };
1696            assert_eq!(err.to_string(), text);
1697        }
1698    }
1699
1700    /// A ceiling allowing `cc` and `ld`, `HOME` and `PATH`, reads under `src`, and no write.
1701    fn ceiling() -> Ceiling {
1702        Ceiling {
1703            unkeyed: BTreeSet::new(),
1704            run: ["cc", "ld"]
1705                .into_iter()
1706                .map(|raw| Program::parse(raw).unwrap())
1707                .collect(),
1708            env: ["PATH", "HOME"]
1709                .into_iter()
1710                .map(|raw| EnvName::parse(raw).unwrap())
1711                .collect(),
1712            read: BTreeSet::from([Directory::parse("src").unwrap()]),
1713            write: BTreeSet::new(),
1714        }
1715    }
1716
1717    #[test]
1718    fn not_approved_shows_its_reason_then_the_wants() {
1719        let err = Error::NotApproved {
1720            unapproved: Box::new(WantedSet {
1721                programs: BTreeSet::from([Program::parse("protoc").unwrap()]),
1722                env: BTreeSet::new(),
1723                unkeyed: BTreeSet::new(),
1724                write: BTreeSet::from([Directory::parse("out").unwrap()]),
1725                network: BTreeSet::new(),
1726            }),
1727            reason: DenialReason::new("not approved"),
1728        };
1729        assert_eq!(
1730            err.to_string(),
1731            "not approved\n  run programs: protoc\n  write into:   out"
1732        );
1733    }
1734
1735    #[test]
1736    fn not_approved_with_nothing_unapproved_shows_only_its_reason() {
1737        let err = Error::NotApproved {
1738            unapproved: Box::new(WantedSet {
1739                programs: BTreeSet::new(),
1740                env: BTreeSet::new(),
1741                unkeyed: BTreeSet::new(),
1742                write: BTreeSet::new(),
1743                network: BTreeSet::new(),
1744            }),
1745            reason: DenialReason::new("not approved"),
1746        };
1747        assert_eq!(err.to_string(), "not approved");
1748    }
1749
1750    #[test]
1751    fn a_refused_program_names_the_site_and_what_may_run() {
1752        let err = Error::Refused {
1753            want: Want::Program(Program::parse("docker").unwrap()),
1754            site: Some(Box::new(root_site("//:image"))),
1755            ceiling: Box::new(ceiling()),
1756        };
1757        assert_eq!(
1758            err.to_string(),
1759            "build.lua: //:image: program docker is outside the ceiling (proc.run allows: cc, ld)"
1760        );
1761    }
1762
1763    /// A violation of `go@1.3.0` by `//:app`, made by `ourgo@0.1.0 > go@1.3.0`, of `want`, with
1764    /// `allowed` listed.
1765    fn violation(want: Want, allowed: &[&str]) -> Error {
1766        let plugin = |name: &str, version: &str| PluginRef {
1767            unkeyed: BTreeSet::new(),
1768            name: PluginName::parse(name).unwrap(),
1769            version: PluginVersion::parse(version).unwrap(),
1770            run: BTreeSet::new(),
1771            env: BTreeSet::new(),
1772        };
1773        let chain = vec![plugin("ourgo", "0.1.0"), plugin("go", "1.3.0")];
1774        Error::PluginRefused {
1775            violation: Box::new(PluginViolation {
1776                want,
1777                site: DeclarationSite {
1778                    label: label("//:app"),
1779                    provenance: root_file(),
1780                    origin: Origin::plugins(chain.clone()).unwrap(),
1781                },
1782                plugin: chain[1].clone(),
1783                allowed: allowed.iter().map(|text| (*text).to_owned()).collect(),
1784            }),
1785        }
1786    }
1787
1788    #[test]
1789    fn a_plugin_tree_names_the_plugin_and_the_path() {
1790        let err = Error::PluginTree {
1791            plugin: PluginName::parse("go").unwrap(),
1792            path: PathBuf::from(".buildl/plugins/go/c0ffee/bin/link"),
1793        };
1794        assert_eq!(
1795            err.to_string(),
1796            "plugin go: .buildl/plugins/go/c0ffee/bin/link is not a regular file with a Unicode \
1797             name; a plugin holds regular files only"
1798        );
1799    }
1800
1801    #[test]
1802    fn a_plugin_not_fetched_names_the_plugin_and_the_reason() {
1803        let err = Error::PluginNotFetched {
1804            plugin: PluginName::parse("go").unwrap(),
1805            reason: "run `buildl plugins fetch`".to_owned(),
1806        };
1807        assert_eq!(
1808            err.to_string(),
1809            "plugin go is not fetched: run `buildl plugins fetch`"
1810        );
1811    }
1812
1813    #[test]
1814    fn a_plugin_changed_names_the_plugin_and_the_reason() {
1815        let err = Error::PluginChanged {
1816            plugin: PluginName::parse("go").unwrap(),
1817            reason: "its files differ from buildl.lock".to_owned(),
1818        };
1819        assert_eq!(
1820            err.to_string(),
1821            "plugin go was changed after it was fetched: its files differ from buildl.lock"
1822        );
1823    }
1824
1825    #[test]
1826    fn a_plugin_fetch_names_the_plugin_and_what_git_said() {
1827        let err = Error::PluginFetch {
1828            plugin: PluginName::parse("go").unwrap(),
1829            diagnostic: Diagnostic::new("fatal: couldn't find remote ref refs/tags/v9"),
1830        };
1831        assert_eq!(
1832            err.to_string(),
1833            "plugin go could not be fetched: fatal: couldn't find remote ref refs/tags/v9"
1834        );
1835    }
1836
1837    #[test]
1838    fn a_plugin_refused_program_names_the_site_the_plugin_and_what_it_allows() {
1839        let err = violation(Want::Program(Program::parse("curl").unwrap()), &["go"]);
1840        assert_eq!(
1841            err.to_string(),
1842            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): program curl is outside plugin \
1843             go@1.3.0 (proc.run allows: go)"
1844        );
1845    }
1846
1847    #[test]
1848    fn a_plugin_refused_variable_reads_like_a_refused_program() {
1849        let err = violation(Want::Env(EnvName::parse("HOME").unwrap()), &[]);
1850        assert_eq!(
1851            err.to_string(),
1852            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): environment variable HOME is \
1853             outside plugin go@1.3.0 (env.read allows: nothing)"
1854        );
1855    }
1856
1857    #[test]
1858    fn a_plugin_refused_unkeyed_variable_names_env_unkeyed() {
1859        let err = violation(Want::Unkeyed(EnvName::parse("HOME").unwrap()), &["PATH"]);
1860        assert_eq!(
1861            err.to_string(),
1862            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): unkeyed variable HOME is outside \
1863             plugin go@1.3.0 (env.unkeyed allows: PATH)"
1864        );
1865    }
1866
1867    #[test]
1868    fn a_plugin_refused_network_says_the_network_is_not_allowed() {
1869        let err = violation(Want::Network(label("//:app")), &[]);
1870        assert_eq!(
1871            err.to_string(),
1872            "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): network is outside plugin \
1873             go@1.3.0 (network not allowed)"
1874        );
1875    }
1876
1877    #[test]
1878    fn an_unmarked_env_names_the_target_and_shows_the_form() {
1879        let err = Error::EnvNotMarked {
1880            site: Box::new(root_site("//:app")),
1881        };
1882        assert_eq!(
1883            err.to_string(),
1884            "build.lua: //:app: env must mark each variable \"key\" or \"unkeyed\", such as \
1885             env = { HOME = \"unkeyed\" }"
1886        );
1887    }
1888
1889    #[test]
1890    fn a_machine_path_in_a_command_names_the_target_and_the_folder() {
1891        let err = Error::MachinePathInCommand {
1892            site: Box::new(root_site("//:note")),
1893            folder: "/home/alice".to_owned(),
1894        };
1895        assert_eq!(
1896            err.to_string(),
1897            "build.lua: //:note: the command holds this machine's path /home/alice; it would \
1898             give the target another key on every machine"
1899        );
1900    }
1901
1902    #[test]
1903    fn a_machine_path_in_a_variable_names_the_variable_and_offers_unkeyed() {
1904        let err = Error::MachinePathInVariable {
1905            site: Box::new(root_site("//:app")),
1906            name: EnvName::parse("RUSTFLAGS").unwrap(),
1907            folder: "/home/alice".to_owned(),
1908        };
1909        assert_eq!(
1910            err.to_string(),
1911            "build.lua: //:app: the variable RUSTFLAGS holds this machine's path /home/alice; \
1912             mark it \"unkeyed\" if it only finds files"
1913        );
1914    }
1915
1916    #[test]
1917    fn a_machine_path_in_a_setting_names_the_setting_and_the_folder() {
1918        let err = Error::MachinePathInSetting {
1919            site: Box::new(root_site("//:setting")),
1920            name: SettingName::parse("prefix").unwrap(),
1921            folder: "/home/alice".to_owned(),
1922        };
1923        assert_eq!(
1924            err.to_string(),
1925            "build.lua: //:setting: the setting prefix holds this machine's path /home/alice; it \
1926             would give the target another key on every machine"
1927        );
1928    }
1929
1930    #[test]
1931    fn a_machine_path_in_a_discovery_output_names_the_target_and_the_folder() {
1932        let err = Error::MachinePathInDiscovery {
1933            site: Box::new(root_site("//:cargo.metadata")),
1934            folder: "/home/alice/shop".to_owned(),
1935        };
1936        assert_eq!(
1937            err.to_string(),
1938            "build.lua: //:cargo.metadata: its output holds this machine's path /home/alice/shop"
1939        );
1940    }
1941
1942    #[test]
1943    fn a_bad_mark_names_the_target_the_variable_and_the_mark() {
1944        let err = Error::EnvBadMark {
1945            site: Box::new(root_site("//:app")),
1946            name: EnvName::parse("HOME").unwrap(),
1947            found: "\"pass\"".to_owned(),
1948        };
1949        assert_eq!(
1950            err.to_string(),
1951            "build.lua: //:app: env HOME is marked \"pass\"; mark it \"key\" or \"unkeyed\""
1952        );
1953    }
1954
1955    #[test]
1956    fn a_refused_variable_names_the_site_and_what_may_be_read() {
1957        let err = Error::Refused {
1958            want: Want::Env(EnvName::parse("AWS_SECRET").unwrap()),
1959            site: Some(Box::new(root_site("//:app"))),
1960            ceiling: Box::new(ceiling()),
1961        };
1962        assert_eq!(
1963            err.to_string(),
1964            "build.lua: //:app: environment variable AWS_SECRET is outside the ceiling \
1965             (env.read allows: HOME, PATH)"
1966        );
1967    }
1968
1969    #[test]
1970    fn a_refused_input_names_the_site_and_where_inputs_may_lie() {
1971        let err = Error::Refused {
1972            want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
1973            site: Some(Box::new(DeclarationSite {
1974                label: label("//lib:text"),
1975                provenance: lib_file(),
1976                origin: Origin::BuildFile,
1977            })),
1978            ceiling: Box::new(ceiling()),
1979        };
1980        assert_eq!(
1981            err.to_string(),
1982            "lib/build.lua: //lib:text: input lib/key.pem is outside the ceiling \
1983             (fs.read allows: src)"
1984        );
1985    }
1986
1987    #[test]
1988    fn a_refused_directory_has_no_site_and_an_empty_list_allows_nothing() {
1989        let err = Error::Refused {
1990            want: Want::Write(Directory::parse("out").unwrap()),
1991            site: None,
1992            ceiling: Box::new(ceiling()),
1993        };
1994        assert_eq!(
1995            err.to_string(),
1996            "directory out is outside the ceiling (fs.write allows: nothing)"
1997        );
1998    }
1999
2000    #[test]
2001    fn a_refused_network_reads_as_network() {
2002        let err = Error::Refused {
2003            want: Want::Network(Label::parse("//:fetch").unwrap()),
2004            site: None,
2005            ceiling: Box::new(ceiling()),
2006        };
2007        assert_eq!(
2008            err.to_string(),
2009            "network of //:fetch is outside the ceiling (network allows: nothing)"
2010        );
2011    }
2012
2013    #[test]
2014    fn the_workspace_root_renders_as_a_dot_in_a_refusal() {
2015        let mut allows_root = ceiling();
2016        allows_root.read = BTreeSet::from([Directory::root(), Directory::parse("src").unwrap()]);
2017        allows_root.write = BTreeSet::from([Directory::parse("out").unwrap()]);
2018        let read = Error::Refused {
2019            want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
2020            site: Some(Box::new(root_site("//:app"))),
2021            ceiling: Box::new(allows_root.clone()),
2022        };
2023        assert_eq!(
2024            read.to_string(),
2025            "build.lua: //:app: input lib/key.pem is outside the ceiling (fs.read allows: ., src)"
2026        );
2027        let write = Error::Refused {
2028            want: Want::Write(Directory::root()),
2029            site: None,
2030            ceiling: Box::new(allows_root),
2031        };
2032        assert_eq!(
2033            write.to_string(),
2034            "directory . is outside the ceiling (fs.write allows: out)"
2035        );
2036    }
2037
2038    #[test]
2039    fn unknown_override_names_the_setting() {
2040        let err = Error::UnknownOverride {
2041            name: SettingName::parse("test_fliter").unwrap(),
2042        };
2043        assert_eq!(
2044            err.to_string(),
2045            "setting test_fliter is overridden but not declared"
2046        );
2047    }
2048
2049    #[test]
2050    fn unknown_target_names_the_label_and_the_nearest_one() {
2051        let err = Error::UnknownTarget {
2052            label: label("//:libs"),
2053            suggestion: Some(label("//:lib")),
2054        };
2055        assert_eq!(
2056            err.to_string(),
2057            "target //:libs was asked for but is not declared (did you mean //:lib?)"
2058        );
2059    }
2060
2061    #[test]
2062    fn unknown_target_without_a_near_label_offers_nothing() {
2063        let err = Error::UnknownTarget {
2064            label: label("//:nope"),
2065            suggestion: None,
2066        };
2067        assert_eq!(
2068            err.to_string(),
2069            "target //:nope was asked for but is not declared"
2070        );
2071    }
2072
2073    #[test]
2074    fn an_unreadable_token_names_where_it_was_to_come_from() {
2075        let env = Error::RemoteToken {
2076            from: TokenSource::Env(EnvName::parse("CACHE_TOKEN").unwrap()),
2077        };
2078        assert_eq!(
2079            env.to_string(),
2080            "the remote cache token from environment variable CACHE_TOKEN cannot be used: \
2081             it is missing or unreadable, or it holds a character a header cannot carry"
2082        );
2083        let file = Error::RemoteToken {
2084            from: TokenSource::File(HostPath::parse("secrets/token").unwrap()),
2085        };
2086        assert_eq!(
2087            file.to_string(),
2088            "the remote cache token from file secrets/token cannot be used: \
2089             it is missing or unreadable, or it holds a character a header cannot carry"
2090        );
2091    }
2092
2093    #[test]
2094    fn a_bad_switch_names_the_variable_and_what_it_holds() {
2095        let err = Error::RemoteSwitch {
2096            name: RemoteVariable::Upload,
2097            value: "yes".to_owned(),
2098        };
2099        assert_eq!(
2100            err.to_string(),
2101            "BUILDL_REMOTE_UPLOAD is \"yes\", and must be 1 or 0"
2102        );
2103        assert_eq!(RemoteVariable::Strict.to_string(), "BUILDL_REMOTE_STRICT");
2104        assert_eq!(RemoteVariable::Execute.to_string(), "BUILDL_REMOTE_EXECUTE");
2105    }
2106
2107    #[test]
2108    fn refused_flags_say_why() {
2109        let combined = Error::RemoteFlags {
2110            conflict: RemoteFlagConflict::NoRemoteWithSwitch,
2111        };
2112        let unnamed = Error::RemoteFlags {
2113            conflict: RemoteFlagConflict::SwitchWithoutRemote,
2114        };
2115        assert_eq!(
2116            combined.to_string(),
2117            "--no-remote cannot be combined with --remote-upload or --remote-strict"
2118        );
2119        assert_eq!(
2120            unnamed.to_string(),
2121            "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
2122             and this workspace has none"
2123        );
2124    }
2125
2126    #[test]
2127    fn refused_execution_flags_name_the_flags() {
2128        let text = |conflict| Error::RemoteFlags { conflict }.to_string();
2129        assert_eq!(
2130            text(RemoteFlagConflict::NoRemoteWithExecute),
2131            "--no-remote cannot be combined with --remote-execute"
2132        );
2133        assert_eq!(
2134            text(RemoteFlagConflict::ExecuteBothWays),
2135            "--remote-execute cannot be combined with --no-remote-execute"
2136        );
2137        assert_eq!(
2138            text(RemoteFlagConflict::ExecutionWithoutRemote),
2139            "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
2140             in buildl.toml, and this workspace has none"
2141        );
2142        assert_eq!(
2143            text(RemoteFlagConflict::JobsWithoutExecution),
2144            "--remote-jobs needs remote execution, and it is off in this run"
2145        );
2146    }
2147
2148    #[test]
2149    fn an_unsandboxed_upload_says_how_to_sandbox_or_stop_uploading() {
2150        assert_eq!(
2151            Error::UploadUnsandboxed {
2152                which: UnsandboxedRemote::Upload
2153            }
2154            .to_string(),
2155            "uploading to the remote cache needs actions to run in the input sandbox, \
2156             but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
2157             unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
2158        );
2159    }
2160
2161    #[test]
2162    fn an_unsandboxed_execution_says_how_to_sandbox_or_stop_executing() {
2163        assert_eq!(
2164            Error::UploadUnsandboxed {
2165                which: UnsandboxedRemote::Execute
2166            }
2167            .to_string(),
2168            "executing on the remote needs actions to run in the input sandbox, \
2169             but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
2170             setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
2171             dropping --remote-execute"
2172        );
2173    }
2174
2175    #[test]
2176    fn not_a_test_names_the_target_and_its_file() {
2177        let err = Error::NotATest {
2178            asked: label("//:default"),
2179            declared_with: TargetRole::Build,
2180            site: Box::new(root_site("//:app")),
2181        };
2182        assert_eq!(
2183            err.to_string(),
2184            "target //:default was asked for as a test, but //:app is declared with b.target in build.lua"
2185        );
2186    }
2187
2188    #[test]
2189    fn not_a_test_names_the_function_that_declared_a_discovery_target() {
2190        let err = Error::NotATest {
2191            asked: label("//:pkgs"),
2192            declared_with: TargetRole::Discovery,
2193            site: Box::new(root_site("//:pkgs")),
2194        };
2195        assert_eq!(
2196            err.to_string(),
2197            "target //:pkgs was asked for as a test, but //:pkgs is declared with b.discover in build.lua"
2198        );
2199    }
2200
2201    #[test]
2202    fn not_a_test_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2203        let err = Error::NotATest {
2204            asked: label("//:default"),
2205            declared_with: TargetRole::Build,
2206            site: Box::new(DeclarationSite {
2207                origin: ourgo_chain(),
2208                ..root_site("//:app")
2209            }),
2210        };
2211        assert_eq!(
2212            err.to_string(),
2213            "target //:default was asked for as a test, but //:app is declared with b.target in \
2214             build.lua, plugin ourgo@0.1.0 > go@1.2.0"
2215        );
2216    }
2217
2218    #[test]
2219    fn invalid_query_names_the_query_and_the_two_forms() {
2220        let err = Error::InvalidQuery {
2221            expression: "dep(//:a)".to_owned(),
2222        };
2223        assert_eq!(
2224            err.to_string(),
2225            "query `dep(//:a)` is not deps(<target>) or rdeps(<target>)"
2226        );
2227    }
2228
2229    fn line(number: usize) -> NonZeroUsize {
2230        NonZeroUsize::new(number).unwrap()
2231    }
2232
2233    #[test]
2234    fn no_run_names_the_target_and_a_suggestion() {
2235        let err = Error::NoRun {
2236            label: label("//:ap"),
2237            suggestion: Some(label("//:app")),
2238            damaged: Vec::new(),
2239        };
2240        assert_eq!(
2241            err.to_string(),
2242            "target //:ap has no run in the log (did you mean //:app?)"
2243        );
2244        let without = Error::NoRun {
2245            label: label("//:ap"),
2246            suggestion: None,
2247            damaged: Vec::new(),
2248        };
2249        assert_eq!(without.to_string(), "target //:ap has no run in the log");
2250    }
2251
2252    #[test]
2253    fn no_run_names_the_damaged_lines() {
2254        let two = Error::NoRun {
2255            label: label("//:app"),
2256            suggestion: None,
2257            damaged: vec![line(14), line(90)],
2258        };
2259        assert_eq!(
2260            two.to_string(),
2261            "target //:app has no run in the log; 2 damaged lines were skipped (lines 14, 90)"
2262        );
2263        let one = Error::NoRun {
2264            label: label("//:app"),
2265            suggestion: None,
2266            damaged: vec![line(14)],
2267        };
2268        assert_eq!(
2269            one.to_string(),
2270            "target //:app has no run in the log; 1 damaged line was skipped (line 14)"
2271        );
2272    }
2273
2274    #[test]
2275    fn missing_output_names_the_target() {
2276        let err = Error::MissingOutput {
2277            label: label("//:app"),
2278        };
2279        assert_eq!(
2280            err.to_string(),
2281            "target //:app: the output of its last logged run is no longer in the store"
2282        );
2283    }
2284
2285    #[test]
2286    fn a_foreign_plan_says_the_plan_does_not_belong_to_the_graph() {
2287        assert_eq!(
2288            Error::ForeignPlan.to_string(),
2289            "the plan was not made from this graph"
2290        );
2291    }
2292
2293    #[test]
2294    fn an_output_conflict_names_the_path_and_both_targets_with_their_files() {
2295        let err = Error::OutputConflict {
2296            path: OutputPath::of(
2297                &Directory::parse("out").unwrap(),
2298                &label("//:lib"),
2299                &OutputName::parse("lib").unwrap(),
2300            ),
2301            first: Box::new(root_site("//:lib")),
2302            second: Box::new(DeclarationSite {
2303                label: label("//lib:text"),
2304                provenance: lib_file(),
2305                origin: Origin::BuildFile,
2306            }),
2307        };
2308        assert_eq!(
2309            err.to_string(),
2310            "out/lib: //:lib (build.lua) and //lib:text (lib/build.lua) cannot both write here"
2311        );
2312    }
2313
2314    #[test]
2315    fn an_output_conflict_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2316        let err = Error::OutputConflict {
2317            path: OutputPath::of(
2318                &Directory::parse("out").unwrap(),
2319                &label("//:lib"),
2320                &OutputName::parse("lib").unwrap(),
2321            ),
2322            first: Box::new(DeclarationSite {
2323                origin: ourgo_chain(),
2324                ..root_site("//:lib")
2325            }),
2326            second: Box::new(root_site("//:other")),
2327        };
2328        assert_eq!(
2329            err.to_string(),
2330            "out/lib: //:lib (build.lua, plugin ourgo@0.1.0 > go@1.2.0) and //:other (build.lua) \
2331             cannot both write here"
2332        );
2333    }
2334
2335    #[test]
2336    fn an_output_conflict_inside_one_target_names_that_target_twice() {
2337        let err = Error::OutputConflict {
2338            path: OutputPath::of(
2339                &Directory::parse("out").unwrap(),
2340                &label("//:app"),
2341                &OutputName::parse("app").unwrap(),
2342            ),
2343            first: Box::new(root_site("//:app")),
2344            second: Box::new(root_site("//:app")),
2345        };
2346        assert_eq!(
2347            err.to_string(),
2348            "out/app: //:app (build.lua) and //:app (build.lua) cannot both write here"
2349        );
2350    }
2351
2352    #[test]
2353    fn no_program_names_the_site_of_the_command() {
2354        let err = Error::NoProgram {
2355            site: Box::new(root_site("//:app")),
2356        };
2357        assert_eq!(
2358            err.to_string(),
2359            "build.lua: //:app: the command names no program once expanded"
2360        );
2361    }
2362
2363    #[test]
2364    fn a_program_a_command_names_only_once_expanded_is_refused_like_any_other() {
2365        let err = Error::Refused {
2366            want: Want::Program(Program::parse("out/app").unwrap()),
2367            site: Some(Box::new(root_site("//:app_test"))),
2368            ceiling: Box::new(Ceiling {
2369                unkeyed: BTreeSet::new(),
2370                run: BTreeSet::from([Program::parse("cc").unwrap()]),
2371                env: BTreeSet::new(),
2372                read: BTreeSet::new(),
2373                write: BTreeSet::new(),
2374            }),
2375        };
2376        assert_eq!(
2377            err.to_string(),
2378            "build.lua: //:app_test: program out/app is outside the ceiling (proc.run allows: cc)"
2379        );
2380    }
2381
2382    #[test]
2383    fn adapter_names_the_port_before_the_adapters_own_message() {
2384        let err = Error::Adapter {
2385            port: PortName::StatCache,
2386            diagnostic: Diagnostic::new("statcache.json: permission denied"),
2387        };
2388        assert_eq!(
2389            err.to_string(),
2390            "stat cache: statcache.json: permission denied"
2391        );
2392    }
2393
2394    #[test]
2395    fn a_dispatcher_fault_names_the_dispatcher_and_the_targets_left_without_an_outcome() {
2396        let lost = Error::DispatcherFault {
2397            targets: vec![label("//:a"), label("//lib:b")],
2398        };
2399        assert_eq!(
2400            lost.to_string(),
2401            "dispatcher: returned without an outcome for //:a, //lib:b"
2402        );
2403    }
2404
2405    #[test]
2406    fn lost_build_files_names_each_directory() {
2407        let lost = Error::LostBuildFiles {
2408            directories: vec![Directory::root(), Directory::parse("lib").unwrap()],
2409        };
2410        assert_eq!(
2411            lost.to_string(),
2412            "dispatcher: returned without evaluating the build files of //, //lib"
2413        );
2414    }
2415
2416    #[test]
2417    fn every_port_name_renders_a_human_phrase() {
2418        let cases = [
2419            (PortName::Manifest, "manifest"),
2420            (PortName::Host, "host"),
2421            (PortName::Digester, "digester"),
2422            (PortName::StatCache, "stat cache"),
2423            (PortName::ToolResolver, "tool resolver"),
2424            (PortName::ActionCache, "action cache"),
2425            (PortName::ContentStore, "content store"),
2426            (PortName::EventLog, "event log"),
2427            (PortName::RunHistory, "run history"),
2428            (PortName::ExecStrategy, "exec strategy"),
2429            (PortName::Dispatcher, "dispatcher"),
2430            (PortName::GraphRecord, "graph record"),
2431            (PortName::Sweep, "sweep"),
2432            (PortName::Approver, "approver"),
2433            (PortName::PluginStore, "plugin store"),
2434            (PortName::RemoteCache, "remote cache"),
2435            (PortName::Changes, "file watcher"),
2436        ];
2437        for (port, rendered) in cases {
2438            assert_eq!(port.to_string(), rendered);
2439        }
2440    }
2441
2442    #[test]
2443    fn the_remote_cache_port_is_named_in_errors() {
2444        let err = Error::Adapter {
2445            port: PortName::RemoteCache,
2446            diagnostic: Diagnostic::new("connection refused"),
2447        };
2448        assert_eq!(PortName::RemoteCache.to_string(), "remote cache");
2449        assert_eq!(err.to_string(), "remote cache: connection refused");
2450    }
2451
2452    #[test]
2453    fn name_kind_renders_a_human_phrase() {
2454        assert_eq!(NameKind::Directory.to_string(), "directory");
2455        assert_eq!(NameKind::TargetName.to_string(), "target name");
2456        assert_eq!(NameKind::Label.to_string(), "label");
2457        assert_eq!(NameKind::Digest.to_string(), "digest");
2458        assert_eq!(NameKind::SourcePath.to_string(), "source path");
2459        assert_eq!(NameKind::OutputName.to_string(), "output name");
2460        assert_eq!(NameKind::EnvName.to_string(), "environment variable name");
2461        assert_eq!(NameKind::Argument.to_string(), "argument");
2462        assert_eq!(NameKind::Command.to_string(), "command");
2463        assert_eq!(NameKind::Description.to_string(), "description");
2464        assert_eq!(NameKind::SettingName.to_string(), "setting name");
2465        assert_eq!(NameKind::SettingValue.to_string(), "setting value");
2466        assert_eq!(NameKind::EntryName.to_string(), "entry file name");
2467        assert_eq!(NameKind::FieldName.to_string(), "field name");
2468        assert_eq!(NameKind::Program.to_string(), "program");
2469        assert_eq!(NameKind::EnvValue.to_string(), "environment variable value");
2470        assert_eq!(NameKind::Platform.to_string(), "platform");
2471        assert_eq!(NameKind::Workers.to_string(), "worker count");
2472        assert_eq!(NameKind::Timeout.to_string(), "timeout");
2473        assert_eq!(NameKind::Isolation.to_string(), "execution strategy");
2474        assert_eq!(NameKind::Approver.to_string(), "approver mode");
2475        assert_eq!(NameKind::TreePath.to_string(), "tree path");
2476        assert_eq!(NameKind::EnvMark.to_string(), "environment variable mark");
2477        assert_eq!(NameKind::PluginName.to_string(), "plugin name");
2478        assert_eq!(NameKind::PluginVersion.to_string(), "plugin version");
2479        assert_eq!(NameKind::PluginChain.to_string(), "plugin chain");
2480        assert_eq!(NameKind::RemoteUrl.to_string(), "remote cache URL");
2481        assert_eq!(NameKind::InstanceName.to_string(), "instance name");
2482        assert_eq!(NameKind::HostPath.to_string(), "host path");
2483        assert_eq!(NameKind::HeaderName.to_string(), "header name");
2484        assert_eq!(NameKind::ChangedPath.to_string(), "changed path");
2485        assert_eq!(NameKind::RemoteJobs.to_string(), "remote job count");
2486        assert_eq!(NameKind::RetryCount.to_string(), "retry count");
2487        assert_eq!(
2488            NameKind::PlatformProperty.to_string(),
2489            "platform property name"
2490        );
2491    }
2492
2493    #[test]
2494    fn an_insecure_token_names_the_url_and_the_fix() {
2495        let url = RemoteUrl::parse("grpc://cache:50051").unwrap();
2496        assert_eq!(
2497            Error::InsecureToken { url }.to_string(),
2498            "a token would be sent in clear text to grpc://cache:50051; use a grpcs:// URL"
2499        );
2500    }
2501
2502    #[test]
2503    fn invalid_name_states_what_was_found() {
2504        let err = Error::InvalidName {
2505            kind: NameKind::Label,
2506            value: "//lib".to_owned(),
2507            reason: "must hold ':' and a target name",
2508        };
2509        assert_eq!(
2510            err.to_string(),
2511            r#"invalid label: "//lib" — must hold ':' and a target name"#
2512        );
2513    }
2514
2515    #[test]
2516    fn canonical_json_states_the_value_could_not_be_serialized() {
2517        let Err(source) = serde_json::to_value(u128::MAX) else {
2518            unreachable!("u128::MAX has no JSON number representation")
2519        };
2520        let err = Error::CanonicalJson { source };
2521        assert_eq!(
2522            err.to_string(),
2523            "value could not be serialized as canonical JSON"
2524        );
2525    }
2526
2527    #[test]
2528    fn float_rejected_states_where_the_float_was_found() {
2529        let err = Error::FloatRejected {
2530            path: "$.timings.elapsed".to_owned(),
2531        };
2532        assert_eq!(
2533            err.to_string(),
2534            "floating-point value at $.timings.elapsed cannot appear in canonical JSON"
2535        );
2536    }
2537
2538    #[test]
2539    fn unreadable_json_states_what_could_not_be_read() {
2540        let Err(source) = serde_json::from_slice::<u32>(b"[]") else {
2541            unreachable!("an array is not a number")
2542        };
2543        let err = Error::UnreadableJson { source };
2544        assert_eq!(
2545            err.to_string(),
2546            "canonical JSON could not be read: invalid type: sequence, expected u32 at line 1 \
2547             column 0"
2548        );
2549    }
2550
2551    #[test]
2552    fn non_canonical_json_states_where_the_bytes_differ() {
2553        let err = Error::NonCanonicalJson { offset: 36 };
2554        assert_eq!(
2555            err.to_string(),
2556            "JSON is not in canonical form: it differs from it at byte 36"
2557        );
2558    }
2559
2560    #[test]
2561    fn corrupt_state_names_the_file_and_keeps_the_reading_failure() {
2562        let err = Error::CorruptState {
2563            file: PathBuf::from("/ws/.buildl/cache.json"),
2564            source: Box::new(Error::NonCanonicalJson { offset: 36 }),
2565        };
2566        assert_eq!(
2567            err.to_string(),
2568            "/ws/.buildl/cache.json is not a file buildl wrote: JSON is not in canonical form: \
2569             it differs from it at byte 36"
2570        );
2571        assert_eq!(
2572            std::error::Error::source(&err).unwrap().to_string(),
2573            "JSON is not in canonical form: it differs from it at byte 36"
2574        );
2575        let Error::CorruptState { source, .. } = err else {
2576            unreachable!("built as CorruptState above")
2577        };
2578        assert!(matches!(*source, Error::NonCanonicalJson { offset: 36 }));
2579    }
2580
2581    #[test]
2582    fn evaluation_names_the_file_the_failure_and_the_message() {
2583        let err = Error::Evaluation {
2584            provenance: lib_file(),
2585            failure: EvaluationFailure::Syntax,
2586            diagnostic: Diagnostic::new("unexpected symbol near '}'"),
2587        };
2588        assert_eq!(
2589            err.to_string(),
2590            "lib/build.lua: syntax error: unexpected symbol near '}'"
2591        );
2592    }
2593
2594    #[test]
2595    fn every_evaluation_failure_renders_a_human_phrase() {
2596        let field = || Written::<FieldName>::new("dep");
2597        let cases = [
2598            (EvaluationFailure::Syntax, "syntax error"),
2599            (EvaluationFailure::Runtime, "runtime error"),
2600            (EvaluationFailure::Refused, "operation refused"),
2601            (
2602                EvaluationFailure::LimitReached {
2603                    limit: EvaluationLimit::Instructions,
2604                },
2605                "instruction ceiling reached",
2606            ),
2607            (
2608                EvaluationFailure::LimitReached {
2609                    limit: EvaluationLimit::Memory,
2610                },
2611                "memory ceiling reached",
2612            ),
2613            (
2614                EvaluationFailure::LimitReached {
2615                    limit: EvaluationLimit::Staging,
2616                },
2617                "staging cap reached",
2618            ),
2619            (
2620                EvaluationFailure::LimitReached {
2621                    limit: EvaluationLimit::Walk,
2622                },
2623                "walk cap reached",
2624            ),
2625            (
2626                EvaluationFailure::UnknownField { field: field() },
2627                r#"unknown field "dep""#,
2628            ),
2629            (
2630                EvaluationFailure::WrongFieldType { field: field() },
2631                r#"field "dep" has the wrong type"#,
2632            ),
2633        ];
2634        for (failure, rendered) in cases {
2635            assert_eq!(failure.to_string(), rendered);
2636        }
2637    }
2638
2639    #[test]
2640    fn missing_build_file_names_the_root_or_the_requester() {
2641        let root = Error::MissingBuildFile {
2642            directory: Directory::root(),
2643            requested_by: None,
2644        };
2645        assert_eq!(root.to_string(), "no build file in // (the workspace root)");
2646        let requested = Error::MissingBuildFile {
2647            directory: Directory::parse("lib/text").unwrap(),
2648            requested_by: Some(lib_file()),
2649        };
2650        assert_eq!(
2651            requested.to_string(),
2652            "no build file in //lib/text (requested by lib/build.lua)"
2653        );
2654    }
2655
2656    #[test]
2657    fn invalid_declaration_names_the_site_the_field_and_the_grammar() {
2658        let source = TargetName::parse("a/b").unwrap_err();
2659        let source_text = source.to_string();
2660        let err = Error::InvalidDeclaration {
2661            provenance: lib_file(),
2662            origin: Origin::BuildFile,
2663            order: DeclarationOrder::new(2),
2664            field: DeclarationField::Dep,
2665            source: Box::new(source),
2666        };
2667        assert_eq!(
2668            err.to_string(),
2669            r#"lib/build.lua: declaration #2: invalid dep: invalid target name: "a/b" — may hold only ASCII letters, digits, '.', '-' and '_'"#
2670        );
2671        assert_eq!(
2672            std::error::Error::source(&err).unwrap().to_string(),
2673            source_text
2674        );
2675    }
2676
2677    #[test]
2678    fn stdout_outputs_names_the_target_and_the_count() {
2679        let err = Error::StdoutOutputs {
2680            target: "//svc:gen".parse().unwrap(),
2681            outputs: 2,
2682        };
2683        assert_eq!(
2684            err.to_string(),
2685            "target //svc:gen declares 2 outputs; a target whose output is its stdout declares exactly one"
2686        );
2687    }
2688
2689    #[test]
2690    fn not_accepted_states_why_the_declaration_cannot_hold_the_value() {
2691        let err = Error::NotAccepted {
2692            reason: "a discovery target is always cached",
2693        };
2694        assert_eq!(err.to_string(), "a discovery target is always cached");
2695    }
2696
2697    #[test]
2698    fn invalid_declaration_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2699        let err = Error::InvalidDeclaration {
2700            provenance: lib_file(),
2701            origin: ourgo_chain(),
2702            order: DeclarationOrder::new(2),
2703            field: DeclarationField::Dep,
2704            source: Box::new(TargetName::parse("a/b").unwrap_err()),
2705        };
2706        assert!(
2707            err.to_string().starts_with(
2708                "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #2: invalid dep: "
2709            ),
2710            "{err}"
2711        );
2712    }
2713
2714    #[test]
2715    fn every_declaration_field_renders_a_human_phrase() {
2716        let cases = [
2717            (DeclarationField::Name, "name"),
2718            (DeclarationField::Dep, "dep"),
2719            (DeclarationField::Input, "input"),
2720            (DeclarationField::Output, "output"),
2721            (DeclarationField::Env, "env"),
2722            (DeclarationField::Run, "run"),
2723            (DeclarationField::Rule, "rule"),
2724            (DeclarationField::Description, "description"),
2725            (DeclarationField::Target, "target"),
2726            (DeclarationField::SettingName, "setting name"),
2727            (DeclarationField::SettingValue, "setting value"),
2728            (DeclarationField::Freshness, "freshness"),
2729            (DeclarationField::Stdout, "stdout"),
2730            (DeclarationField::Subdir, "subdir"),
2731        ];
2732        for (field, rendered) in cases {
2733            assert_eq!(field.to_string(), rendered);
2734        }
2735    }
2736
2737    #[test]
2738    fn action_conflict_states_what_was_found() {
2739        let both = Error::ActionConflict {
2740            provenance: lib_file(),
2741            origin: Origin::BuildFile,
2742            order: DeclarationOrder::new(0),
2743            found: ActionFound::Both,
2744        };
2745        assert_eq!(
2746            both.to_string(),
2747            "lib/build.lua: declaration #0: a target names both 'rule' and 'run'"
2748        );
2749        let neither = Error::ActionConflict {
2750            provenance: lib_file(),
2751            origin: Origin::BuildFile,
2752            order: DeclarationOrder::new(1),
2753            found: ActionFound::Neither,
2754        };
2755        assert_eq!(
2756            neither.to_string(),
2757            "lib/build.lua: declaration #1: a target names neither 'rule' nor 'run'"
2758        );
2759    }
2760
2761    #[test]
2762    fn action_conflict_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2763        let err = Error::ActionConflict {
2764            provenance: lib_file(),
2765            origin: ourgo_chain(),
2766            order: DeclarationOrder::new(0),
2767            found: ActionFound::Both,
2768        };
2769        assert_eq!(
2770            err.to_string(),
2771            "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #0: a target names both \
2772             'rule' and 'run'"
2773        );
2774    }
2775
2776    #[test]
2777    fn nondeterministic_names_the_file_to_fix() {
2778        let err = Error::Nondeterministic {
2779            provenance: lib_file(),
2780            first_run: None,
2781            second_run: None,
2782        };
2783        assert_eq!(
2784            err.to_string(),
2785            "lib/build.lua: declarations differ between two evaluations"
2786        );
2787    }
2788
2789    #[test]
2790    fn discovery_changed_names_the_target_and_its_file() {
2791        let err = Error::DiscoveryChanged {
2792            label: Label::parse("//lib:pkgs").unwrap(),
2793            provenance: lib_file(),
2794        };
2795        assert_eq!(
2796            err.to_string(),
2797            "lib/build.lua: discovery target //lib:pkgs differs once discovery results are \
2798             read; a discovery target may not depend on a discovery result"
2799        );
2800    }
2801
2802    #[test]
2803    fn an_invalid_tree_says_what_is_wrong_with_the_list() {
2804        let path = TreePath::parse("assets/app.js").unwrap();
2805        for (fault, rendered) in [
2806            (TreeFault::Empty, "not a tree: it holds no file"),
2807            (
2808                TreeFault::Repeated(path.clone()),
2809                "not a tree: assets/app.js is listed twice",
2810            ),
2811            (
2812                TreeFault::Clash(path),
2813                "not a tree: assets/app.js is both a file and a directory",
2814            ),
2815        ] {
2816            assert_eq!(Error::InvalidTree { fault }.to_string(), rendered);
2817        }
2818    }
2819}