Skip to main content

buildl_core/
error.rs

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