1use std::error::Error;
7use std::fmt;
8use std::io;
9
10use crate::budget::Budget;
11use crate::path::{PathError, RelPath, SourceAuthorityId};
12
13pub(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 '\'' | '"' => write!(f, "{c}"),
23 _ => write!(f, "{}", c.escape_debug()),
24 })
25 }
26}
27
28#[derive(Debug)]
34#[non_exhaustive]
35pub enum TreeError {
36 RegistrySource {
38 path: String,
40 source: Box<LoadError>,
42 },
43 GitSource {
45 path: String,
47 source: Box<LoadError>,
49 },
50 BackendAuthority {
52 path: String,
54 authority: SourceAuthorityId,
56 },
57 WrongAuthority {
59 path: String,
61 authority: SourceAuthorityId,
63 },
64 NotFound {
66 path: String,
68 },
69 OutsideRoot {
72 path: String,
74 },
75 NotRegular {
78 path: String,
80 },
81 SymlinkLoop {
83 path: String,
85 },
86 TooLarge {
88 path: String,
90 limit: u64,
92 },
93 NotUtf8 {
95 path: String,
97 },
98 NonUtf8Name {
100 path: String,
102 name: String,
104 },
105 DuplicatePath {
108 path: String,
110 },
111 Io {
113 path: String,
115 source: io::Error,
117 },
118}
119
120impl TreeError {
121 #[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 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
155pub(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.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 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#[derive(Debug, Clone, PartialEq, Eq)]
245#[non_exhaustive]
246pub enum Origin {
247 ModDecl {
249 module: String,
251 },
252 PathAttr {
254 module: String,
256 predicate: Option<String>,
258 },
259 ManifestKey {
261 key: String,
263 },
264 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#[derive(Debug)]
293#[non_exhaustive]
294pub enum LoadErrorKind {
295 GitIo {
297 operation: &'static str,
299 source: io::Error,
301 },
302 Storage(purrdf_lex::allocation::StorageError),
304 Locked {
306 field: &'static str,
308 message: String,
310 source: Option<Box<purrdf_toml::TomlError>>,
312 },
313 Graph(purrdf_core::graph::GraphError),
315 Tree(Box<TreeError>),
317 Budget {
319 budget: Budget,
321 limit: usize,
323 },
324 Syntax {
326 message: String,
328 column: usize,
330 },
331 Spawn(io::Error),
334 Registry {
337 first: String,
339 },
340 Manifest {
342 message: String,
344 source: Option<Box<purrdf_toml::TomlError>>,
346 },
347 Target(Box<TargetProblem>),
349 DirSymlink,
351 NoRoots,
353 UnresolvedMod {
355 module: String,
357 },
358 BothModFiles {
360 module: String,
362 first: Box<RelPath>,
364 second: Box<RelPath>,
366 },
367 DuplicatePathAttr {
369 module: String,
371 },
372 ModuleCycle {
374 module: String,
376 again: Box<RelPath>,
378 },
379 CfgParse {
383 message: String,
385 },
386 UnsupportedItem {
388 what: String,
390 },
391 UnresolvedTrait {
393 path: String,
395 },
396 Internal {
399 what: String,
401 },
402 SuperAboveRoot {
404 path: String,
406 },
407}
408
409#[derive(Debug, Clone, PartialEq, Eq)]
411#[non_exhaustive]
412pub enum TargetProblem {
413 MissingFile {
415 path: RelPath,
417 },
418 NoName,
420 SharedRoot {
422 root: RelPath,
424 other: String,
426 },
427 AmbiguousRoot {
429 first: RelPath,
431 second: RelPath,
433 },
434 DuplicateCratePath {
437 crate_path: String,
439 other: String,
441 with: RelPath,
443 },
444 DuplicatePackage {
446 name: String,
448 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#[derive(Debug)]
578#[non_exhaustive]
579pub struct LoadError {
580 pub file: RelPath,
582 pub line: Option<usize>,
584 pub origin: Option<Box<Origin>>,
586 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 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 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 const HOSTILE: &str = "a\u{1b}]0;pwned\u{7}\u{1b}[2J\0\r\nb";
664 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}