Skip to main content

raf_source/
error.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! The typed errors of the tree backends.
5
6use std::error::Error;
7use std::fmt;
8use std::io;
9
10use crate::budget::Budget;
11use crate::path::{PathError, RelPath, SourceAuthorityId};
12
13/// Text that came from the input, shown with every control character escaped
14/// by [`char::escape_debug`], so that an error message cannot carry a terminal
15/// escape sequence, a line break or a NUL.
16pub(crate) struct Esc<'a>(pub(crate) &'a str);
17
18impl fmt::Display for Esc<'_> {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        self.0.chars().try_for_each(|c| match c {
21            // Quotes are not control characters and stay readable.
22            '\'' | '"' => write!(f, "{c}"),
23            _ => write!(f, "{}", c.escape_debug()),
24        })
25    }
26}
27
28/// Why a [`Tree`](crate::Tree) call failed.
29///
30/// Every variant names the path it concerns. Only [`TreeError::NotFound`]
31/// means that nothing is there; every other variant is a refusal or a failure
32/// and must never be read as absence.
33#[derive(Debug)]
34#[non_exhaustive]
35pub enum TreeError {
36    /// A registry archive refused source, storage or work evidence.
37    RegistrySource {
38        /// The requested relative path.
39        path: String,
40        /// The original verification or resource failure.
41        source: Box<LoadError>,
42    },
43    /// A committed Git host Tree refused source, storage or work evidence.
44    GitSource {
45        /// The requested relative path.
46        path: String,
47        /// The original verification or resource failure.
48        source: Box<LoadError>,
49    },
50    /// A source mount received an already-scoped identity from its backend.
51    BackendAuthority {
52        /// The relative path that was asked for.
53        path: String,
54        /// The backend identity's unexpected authority.
55        authority: SourceAuthorityId,
56    },
57    /// This tree does not provide the path's selected source authority.
58    WrongAuthority {
59        /// The relative path that was asked for.
60        path: String,
61        /// The unavailable authority.
62        authority: SourceAuthorityId,
63    },
64    /// Nothing exists at the path.
65    NotFound {
66        /// The path that was asked for.
67        path: String,
68    },
69    /// The path leads outside the tree root: by an absolute or `..` input, a
70    /// symlink, or a `..` after a directory symlink.
71    OutsideRoot {
72        /// The path that was asked for.
73        path: String,
74    },
75    /// The path is not a regular file where one is needed, or not a real
76    /// directory where one is needed (a FIFO, a device, a directory symlink).
77    NotRegular {
78        /// The path that was asked for.
79        path: String,
80    },
81    /// Resolving the path ran into a symlink loop.
82    SymlinkLoop {
83        /// The path that was asked for.
84        path: String,
85    },
86    /// The file holds more bytes than the caller allowed.
87    TooLarge {
88        /// The path that was asked for.
89        path: String,
90        /// The limit in bytes that was exceeded.
91        limit: u64,
92    },
93    /// The file is not valid UTF-8.
94    NotUtf8 {
95        /// The path that was asked for.
96        path: String,
97    },
98    /// A directory entry has a name that is not valid UTF-8.
99    NonUtf8Name {
100        /// The directory that was listed.
101        path: String,
102        /// The entry name, with invalid bytes replaced for display.
103        name: String,
104    },
105    /// Two keys of a [`MemoryTree`](crate::MemoryTree) name one path once
106    /// normalised.
107    DuplicatePath {
108        /// The key that repeats an earlier path.
109        path: String,
110    },
111    /// The operating system failed the operation for another reason.
112    Io {
113        /// The path that was asked for.
114        path: String,
115        /// The underlying failure.
116        source: io::Error,
117    },
118}
119
120impl TreeError {
121    /// The path the error concerns.
122    #[must_use]
123    pub fn path(&self) -> &str {
124        match self {
125            Self::RegistrySource { path, .. }
126            | Self::GitSource { path, .. }
127            | Self::BackendAuthority { path, .. }
128            | Self::WrongAuthority { path, .. }
129            | Self::NotFound { path }
130            | Self::OutsideRoot { path }
131            | Self::NotRegular { path }
132            | Self::SymlinkLoop { path }
133            | Self::TooLarge { path, .. }
134            | Self::NotUtf8 { path }
135            | Self::NonUtf8Name { path, .. }
136            | Self::DuplicatePath { path }
137            | Self::Io { path, .. } => path,
138        }
139    }
140
141    /// Classify an operating-system failure on `path`.
142    ///
143    /// A missing entry or a missing directory on the way is `NotFound`; a
144    /// symlink loop is `SymlinkLoop`; anything else is `Io`.
145    pub(crate) fn from_io(path: &str, source: io::Error) -> Self {
146        let path = path.to_owned();
147        match source.kind() {
148            io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => Self::NotFound { path },
149            _ if is_symlink_loop(&source) => Self::SymlinkLoop { path },
150            _ => Self::Io { path, source },
151        }
152    }
153}
154
155/// True when the operating system reported too many levels of symbolic links.
156pub(crate) fn is_symlink_loop(error: &io::Error) -> bool {
157    #[cfg(unix)]
158    {
159        error.raw_os_error() == Some(libc::ELOOP)
160    }
161    #[cfg(windows)]
162    {
163        // ERROR_CANT_RESOLVE_FILENAME
164        error.raw_os_error() == Some(1921)
165    }
166    #[cfg(not(any(unix, windows)))]
167    {
168        let _ = error;
169        false
170    }
171}
172
173impl From<PathError> for TreeError {
174    /// A path that is not a [`RelPath`](crate::RelPath) points somewhere the
175    /// root does not contain, so it is `OutsideRoot`.
176    fn from(error: PathError) -> Self {
177        Self::OutsideRoot {
178            path: error.input().to_owned(),
179        }
180    }
181}
182
183impl fmt::Display for TreeError {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        match self {
186            Self::RegistrySource { path, source } | Self::GitSource { path, source } => {
187                write!(f, "{}: {source}", Esc(path))
188            }
189            Self::BackendAuthority { path, authority } => write!(
190                f,
191                "{}: backend returned source authority {}; mounted backend identities must use authority zero",
192                Esc(path),
193                authority.index()
194            ),
195            Self::WrongAuthority { path, authority } => write!(
196                f,
197                "{} belongs to source authority {}, which this tree does not contain",
198                Esc(path),
199                authority.index()
200            ),
201            Self::NotFound { path } => write!(f, "{}: no such file or directory", Esc(path)),
202            Self::OutsideRoot { path } => write!(f, "{} leads outside the root", Esc(path)),
203            Self::NotRegular { path } => {
204                write!(f, "{} is not a regular file or a real directory", Esc(path))
205            }
206            Self::SymlinkLoop { path } => write!(f, "{} runs into a symlink loop", Esc(path)),
207            Self::TooLarge { path, limit } => {
208                write!(f, "{} is larger than the limit of {limit} bytes", Esc(path))
209            }
210            Self::NotUtf8 { path } => write!(f, "{} is not valid UTF-8", Esc(path)),
211            Self::NonUtf8Name { path, name } => write!(
212                f,
213                "directory {} holds an entry whose name is not valid UTF-8: \"{}\"",
214                Esc(path),
215                Esc(name)
216            ),
217            Self::DuplicatePath { path } => {
218                write!(
219                    f,
220                    "{} names a path that an earlier key already holds",
221                    Esc(path)
222                )
223            }
224            Self::Io { path, source } => write!(f, "{}: {source}", Esc(path)),
225        }
226    }
227}
228
229impl Error for TreeError {
230    fn source(&self) -> Option<&(dyn Error + 'static)> {
231        match self {
232            Self::Io { source, .. } => Some(source),
233            Self::RegistrySource { source, .. } | Self::GitSource { source, .. } => Some(source),
234            _ => None,
235        }
236    }
237}
238
239/// Where a failing file was reached from.
240///
241/// A caller that parses a file directly has no origin. A walker that follows
242/// `mod` declarations, `#[path]` attributes and manifests sets one so that the
243/// message names the module, attribute or key that led to the file.
244#[derive(Debug, Clone, PartialEq, Eq)]
245#[non_exhaustive]
246pub enum Origin {
247    /// A `mod name;` declaration.
248    ModDecl {
249        /// The module name as written.
250        module: String,
251    },
252    /// A `#[path = "..."]` attribute on a module.
253    PathAttr {
254        /// The module name as written.
255        module: String,
256        /// The `cfg_attr` predicate that guards the attribute, if any.
257        predicate: Option<String>,
258    },
259    /// A key of a `Cargo.toml`.
260    ManifestKey {
261        /// The key, such as `lib.path`.
262        key: String,
263    },
264    /// Discovery of the packages themselves.
265    Discovery,
266}
267
268impl fmt::Display for Origin {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        match self {
271            Self::ModDecl { module } => write!(f, "`mod {};`", Esc(module)),
272            Self::PathAttr {
273                module,
274                predicate: None,
275            } => write!(f, "the `path` attribute of module `{}`", Esc(module)),
276            Self::PathAttr {
277                module,
278                predicate: Some(predicate),
279            } => write!(
280                f,
281                "the `path` attribute of module `{}` under `{}`",
282                Esc(module),
283                Esc(predicate)
284            ),
285            Self::ManifestKey { key } => write!(f, "manifest key `{}`", Esc(key)),
286            Self::Discovery => f.write_str("package discovery"),
287        }
288    }
289}
290
291/// What went wrong while loading a file.
292#[derive(Debug)]
293#[non_exhaustive]
294pub enum LoadErrorKind {
295    /// Native Git repository or object access failed.
296    GitIo {
297        /// The host operation that failed.
298        operation: &'static str,
299        /// The original operating-system failure.
300        source: io::Error,
301    },
302    /// Native storage refused a physical layout or allocation.
303    Storage(purrdf_lex::allocation::StorageError),
304    /// The locked package/edge profile is malformed, unsupported or ambiguous.
305    Locked {
306        /// The field whose evidence was refused.
307        field: &'static str,
308        /// What is wrong and how to correct it.
309        message: String,
310        /// Native TOML cause for grammar and parser-resource failures.
311        source: Option<Box<purrdf_toml::TomlError>>,
312    },
313    /// A native graph operation refused invalid topology or physical storage.
314    Graph(purrdf_core::graph::GraphError),
315    /// The tree refused or failed the file.
316    Tree(Box<TreeError>),
317    /// The file exceeds a recursion budget of the pre-scan.
318    Budget {
319        /// The budget that was exceeded.
320        budget: Budget,
321        /// The most the budget allows.
322        limit: usize,
323    },
324    /// `syn` could not parse the file.
325    Syntax {
326        /// The parser's message.
327        message: String,
328        /// The 1-based column of the error on its line.
329        column: usize,
330    },
331    /// The thread that parses could not be started (the operating system
332    /// refused the stack or the thread).
333    Spawn(io::Error),
334    /// The parse worker's native source registry was not fresh at entry, so its
335    /// admitted storage bounds do not hold.
336    Registry {
337        /// The file name the registry gave the entry probe instead of the first.
338        first: String,
339    },
340    /// A `Cargo.toml` could not be read as a manifest.
341    Manifest {
342        /// What is wrong with it.
343        message: String,
344        /// Native TOML cause; schema errors have no parser failure.
345        source: Option<Box<purrdf_toml::TomlError>>,
346    },
347    /// A target is wrong in a way the manifest keys explain.
348    Target(Box<TargetProblem>),
349    /// A directory entry that discovery would have entered is a symlink.
350    DirSymlink,
351    /// The load was given no roots, so there is nothing to discover.
352    NoRoots,
353    /// A `mod name;` names no file.
354    UnresolvedMod {
355        /// The module name, without a raw-identifier prefix.
356        module: String,
357    },
358    /// Both `name.rs` and `name/mod.rs` exist for a module.
359    BothModFiles {
360        /// The module name, without a raw-identifier prefix.
361        module: String,
362        /// The `name.rs` file.
363        first: Box<RelPath>,
364        /// The `name/mod.rs` file.
365        second: Box<RelPath>,
366    },
367    /// A module has two `path` attributes that apply unconditionally.
368    DuplicatePathAttr {
369        /// The module name, without a raw-identifier prefix.
370        module: String,
371    },
372    /// A module leads back to a file that is still being followed.
373    ModuleCycle {
374        /// The module name, without a raw-identifier prefix.
375        module: String,
376        /// The file that would be entered a second time.
377        again: Box<RelPath>,
378    },
379    /// A `cfg`, `cfg_attr`, `path` or `test` attribute could not be read: it
380    /// has the wrong shape, its predicate cannot be read, or the value of a
381    /// `path` is not a string literal.
382    CfgParse {
383        /// What is wrong with it.
384        message: String,
385    },
386    /// The file holds an item that the index does not model.
387    UnsupportedItem {
388        /// A description of the item.
389        what: String,
390    },
391    /// The trait of an `impl` block cannot be named by an absolute path.
392    UnresolvedTrait {
393        /// The trait path as written.
394        path: String,
395    },
396    /// An invariant of the index does not hold. This is a bug in the crate,
397    /// reported and not guessed around.
398    Internal {
399        /// What did not hold.
400        what: String,
401    },
402    /// A path climbs above the crate root with `super`.
403    SuperAboveRoot {
404        /// The path as written.
405        path: String,
406    },
407}
408
409/// What is wrong with a package target.
410#[derive(Debug, Clone, PartialEq, Eq)]
411#[non_exhaustive]
412pub enum TargetProblem {
413    /// An explicit target path names no file.
414    MissingFile {
415        /// The path, relative to the tree root.
416        path: RelPath,
417    },
418    /// A target table has no `name`.
419    NoName,
420    /// Two targets of a package have one root file.
421    SharedRoot {
422        /// The shared root file.
423        root: RelPath,
424        /// The Cargo name of the target that holds it first.
425        other: String,
426    },
427    /// A target name could belong to two root files.
428    AmbiguousRoot {
429        /// The first candidate.
430        first: RelPath,
431        /// The second candidate.
432        second: RelPath,
433    },
434    /// Two targets of one package have one crate path, so their items could
435    /// not be told apart.
436    DuplicateCratePath {
437        /// The crate path.
438        crate_path: String,
439        /// The Cargo name of the target that holds it first.
440        other: String,
441        /// The manifest of that target's package.
442        with: RelPath,
443    },
444    /// Two packages have one name.
445    DuplicatePackage {
446        /// The package name.
447        name: String,
448        /// The manifest of the other package.
449        with: RelPath,
450    },
451}
452
453impl fmt::Display for TargetProblem {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        match self {
456            Self::MissingFile { path } => {
457                write!(f, "the target file {} does not exist", Esc(path.as_str()))
458            }
459            Self::NoName => f.write_str("the target has no name"),
460            Self::SharedRoot { root, other } => {
461                write!(
462                    f,
463                    "the root {} already belongs to the target `{}`",
464                    Esc(root.as_str()),
465                    Esc(other)
466                )
467            }
468            Self::AmbiguousRoot { first, second } => {
469                write!(
470                    f,
471                    "both {} and {} could be the root",
472                    Esc(first.as_str()),
473                    Esc(second.as_str())
474                )
475            }
476            Self::DuplicateCratePath {
477                crate_path,
478                other,
479                with,
480            } => write!(
481                f,
482                "the crate path `{}` is already used by the target `{}` of {}",
483                Esc(crate_path),
484                Esc(other),
485                Esc(with.as_str())
486            ),
487            Self::DuplicatePackage { name, with } => {
488                write!(
489                    f,
490                    "package `{}` is also defined by {}",
491                    Esc(name),
492                    Esc(with.as_str())
493                )
494            }
495        }
496    }
497}
498
499impl fmt::Display for LoadErrorKind {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        match self {
502            Self::GitIo { operation, source } => write!(f, "Git {operation} failed: {source}"),
503            Self::Storage(error) => write!(f, "{error}"),
504            Self::Locked { field, message, .. } => {
505                write!(
506                    f,
507                    "invalid locked dependency {}: {}",
508                    Esc(field),
509                    Esc(message)
510                )
511            }
512            Self::Graph(error) => write!(f, "graph operation failed: {error}"),
513            Self::Tree(error) => write!(f, "{error}"),
514            Self::Budget { budget, limit } => {
515                write!(f, "exceeds the budget for {budget} ({limit})")
516            }
517            Self::Syntax { message, column } => {
518                write!(f, "syntax error at column {column}: {}", Esc(message))
519            }
520            Self::Spawn(error) => write!(f, "cannot start the parse thread: {error}"),
521            Self::Registry { first } => write!(
522                f,
523                "the parse thread's native source registry was not empty at entry (its probe \
524                 was numbered `{}`): a thread spawn callback lexed Rust source before the \
525                 worker ran; remove that callback or keep it from lexing source",
526                Esc(first)
527            ),
528            Self::Manifest { message, .. } => write!(f, "invalid manifest: {}", Esc(message)),
529            Self::Target(problem) => write!(f, "{problem}"),
530            Self::DirSymlink => f.write_str("a symlinked directory is not followed"),
531            Self::NoRoots => f.write_str("no roots were given; name at least one, such as `.`"),
532            Self::UnresolvedMod { module } => {
533                write!(f, "module `{}` has no file", Esc(module))
534            }
535            Self::BothModFiles {
536                module,
537                first,
538                second,
539            } => write!(
540                f,
541                "module `{}` has both {} and {}",
542                Esc(module),
543                Esc(first.as_str()),
544                Esc(second.as_str())
545            ),
546            Self::DuplicatePathAttr { module } => {
547                write!(f, "module `{}` has two `path` attributes", Esc(module))
548            }
549            Self::ModuleCycle { module, again } => write!(
550                f,
551                "module `{}` leads back to {}, which is still being followed",
552                Esc(module),
553                Esc(again.as_str())
554            ),
555            Self::CfgParse { message } => write!(f, "cannot read an attribute: {}", Esc(message)),
556            Self::UnsupportedItem { what } => write!(f, "unsupported item: {}", Esc(what)),
557            Self::UnresolvedTrait { path } => {
558                write!(
559                    f,
560                    "the trait `{}` of an impl cannot be named by an absolute path",
561                    Esc(path)
562                )
563            }
564            Self::Internal { what } => write!(f, "internal error: {}", Esc(what)),
565            Self::SuperAboveRoot { path } => {
566                write!(
567                    f,
568                    "`{}` climbs above the crate root with `super`",
569                    Esc(path)
570                )
571            }
572        }
573    }
574}
575
576/// A failure to load one file, naming the file.
577#[derive(Debug)]
578#[non_exhaustive]
579pub struct LoadError {
580    /// The file, relative to the tree root.
581    pub file: RelPath,
582    /// The 1-based line of the failure, when it has one.
583    pub line: Option<usize>,
584    /// What led to the file, when a walker reached it.
585    pub origin: Option<Box<Origin>>,
586    /// What went wrong.
587    pub kind: LoadErrorKind,
588}
589
590impl LoadError {
591    pub(crate) fn new(file: &RelPath, line: Option<usize>, kind: LoadErrorKind) -> Self {
592        Self {
593            file: file.clone(),
594            line,
595            origin: None,
596            kind,
597        }
598    }
599
600    /// The same error, reached by `origin`.
601    pub(crate) fn reached_by(mut self, origin: &Origin) -> Self {
602        if self.origin.is_none() {
603            self.origin = Some(Box::new(origin.clone()));
604        }
605        self
606    }
607
608    /// A tree failure on `file`, reached by `origin`.
609    pub(crate) fn tree(
610        file: &RelPath,
611        line: Option<usize>,
612        origin: &Origin,
613        error: TreeError,
614    ) -> Self {
615        Self::new(file, line, LoadErrorKind::Tree(Box::new(error))).reached_by(origin)
616    }
617}
618
619impl fmt::Display for LoadError {
620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621        write!(f, "{}", Esc(self.file.as_str()))?;
622        if let Some(line) = self.line {
623            write!(f, ":{line}")?;
624        }
625        write!(f, ": {}", self.kind)?;
626        if let Some(origin) = &self.origin {
627            write!(f, " (reached by {origin})")?;
628        }
629        Ok(())
630    }
631}
632
633impl Error for LoadError {
634    fn source(&self) -> Option<&(dyn Error + 'static)> {
635        match &self.kind {
636            LoadErrorKind::Manifest {
637                source: Some(source),
638                ..
639            }
640            | LoadErrorKind::Locked {
641                source: Some(source),
642                ..
643            } => Some(source.as_ref()),
644            LoadErrorKind::Storage(error) => Some(error),
645            LoadErrorKind::GitIo { source, .. } => Some(source),
646            LoadErrorKind::Graph(error) => Some(error),
647            LoadErrorKind::Tree(error) => Some(error),
648            LoadErrorKind::Spawn(error) => Some(error),
649            _ => None,
650        }
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use std::error::Error;
657    use std::io;
658
659    use super::{LoadError, LoadErrorKind, Origin, TargetProblem, TreeError};
660    use crate::RelPath;
661
662    /// Every kind of control character, including a NUL.
663    const HOSTILE: &str = "a\u{1b}]0;pwned\u{7}\u{1b}[2J\0\r\nb";
664    /// The same for a `RelPath`, which refuses a NUL.
665    const HOSTILE_PATH: &str = "a\u{1b}]0;pwned\u{7}\u{1b}[2J\r\nb";
666
667    fn clean(text: &str) {
668        assert!(
669            !text.chars().any(char::is_control),
670            "a control character got through: {text:?}"
671        );
672    }
673
674    #[test]
675    fn control_characters_in_a_path_are_escaped() {
676        let file = RelPath::new(&format!("src/{HOSTILE_PATH}.rs")).expect("a relative path");
677        let text = LoadError::tree(
678            &file,
679            Some(3),
680            &Origin::PathAttr {
681                module: HOSTILE.to_owned(),
682                predicate: Some(HOSTILE.to_owned()),
683            },
684            TreeError::OutsideRoot {
685                path: HOSTILE.to_owned(),
686            },
687        )
688        .to_string();
689        clean(&text);
690        assert!(
691            text.contains(r"a\u{1b}]0;pwned\u{7}\u{1b}[2J\0\r\nb"),
692            "{text}"
693        );
694        assert!(text.starts_with("src/a\\u{1b}"), "{text}");
695    }
696
697    #[test]
698    fn every_user_derived_field_of_every_display_is_escaped() {
699        let file = RelPath::new("x").expect("a relative path");
700        let hostile = || HOSTILE.to_owned();
701        let path = || RelPath::new(&format!("d/{HOSTILE_PATH}")).expect("a relative path");
702        let tree_errors = [
703            TreeError::BackendAuthority {
704                path: hostile(),
705                authority: crate::SourceAuthorityId(1),
706            },
707            TreeError::WrongAuthority {
708                path: hostile(),
709                authority: crate::SourceAuthorityId(1),
710            },
711            TreeError::NotFound { path: hostile() },
712            TreeError::OutsideRoot { path: hostile() },
713            TreeError::NotRegular { path: hostile() },
714            TreeError::SymlinkLoop { path: hostile() },
715            TreeError::TooLarge {
716                path: hostile(),
717                limit: 1,
718            },
719            TreeError::NotUtf8 { path: hostile() },
720            TreeError::NonUtf8Name {
721                path: hostile(),
722                name: hostile(),
723            },
724            TreeError::DuplicatePath { path: hostile() },
725            TreeError::Io {
726                path: hostile(),
727                source: io::Error::other("x"),
728            },
729        ];
730        for error in tree_errors {
731            clean(&error.to_string());
732        }
733        let origins = [
734            Origin::ModDecl { module: hostile() },
735            Origin::ManifestKey { key: hostile() },
736            Origin::PathAttr {
737                module: hostile(),
738                predicate: None,
739            },
740        ];
741        for origin in origins {
742            clean(&origin.to_string());
743        }
744        let problems = [
745            TargetProblem::MissingFile { path: path() },
746            TargetProblem::SharedRoot {
747                root: path(),
748                other: hostile(),
749            },
750            TargetProblem::AmbiguousRoot {
751                first: path(),
752                second: path(),
753            },
754            TargetProblem::DuplicateCratePath {
755                crate_path: hostile(),
756                other: hostile(),
757                with: path(),
758            },
759            TargetProblem::DuplicatePackage {
760                name: hostile(),
761                with: path(),
762            },
763        ];
764        for problem in problems {
765            clean(&problem.to_string());
766        }
767        let kinds = vec![
768            LoadErrorKind::Syntax {
769                message: hostile(),
770                column: 1,
771            },
772            LoadErrorKind::Manifest {
773                message: hostile(),
774                source: None,
775            },
776            LoadErrorKind::UnresolvedMod { module: hostile() },
777            LoadErrorKind::BothModFiles {
778                module: hostile(),
779                first: Box::new(path()),
780                second: Box::new(path()),
781            },
782            LoadErrorKind::DuplicatePathAttr { module: hostile() },
783            LoadErrorKind::ModuleCycle {
784                module: hostile(),
785                again: Box::new(path()),
786            },
787            LoadErrorKind::CfgParse { message: hostile() },
788            LoadErrorKind::UnsupportedItem { what: hostile() },
789            LoadErrorKind::UnresolvedTrait { path: hostile() },
790            LoadErrorKind::Internal { what: hostile() },
791            LoadErrorKind::SuperAboveRoot { path: hostile() },
792        ];
793        for kind in kinds {
794            clean(&LoadError::new(&file, None, kind).to_string());
795        }
796        let hostile_file = RelPath::new(&format!("{HOSTILE_PATH}.rs")).expect("a relative path");
797        clean(&LoadError::new(&hostile_file, None, LoadErrorKind::DirSymlink).to_string());
798    }
799
800    #[test]
801    fn a_spawn_error_displays_the_file_and_carries_its_cause() {
802        let file = RelPath::new("src/lib.rs").expect("a plain path");
803        let error = LoadError::new(
804            &file,
805            None,
806            LoadErrorKind::Spawn(io::Error::other("no threads left")),
807        );
808        assert!(matches!(error.kind, LoadErrorKind::Spawn(_)));
809        let text = error.to_string();
810        assert!(text.starts_with("src/lib.rs: "), "{text}");
811        assert!(text.contains("cannot start the parse thread"), "{text}");
812        let source = error.source().expect("a spawn error has a cause");
813        assert_eq!(source.to_string(), "no threads left");
814    }
815}