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