Debian Codegraph @

third_party/rust/thiserror/tests/test_expr.rs

raw
1 #![allow(clippy::iter_cloned_collect, clippy::uninlined_format_args)]
2
3 use core::fmt::Display;
4 use std::path::PathBuf;
5 use thiserror::Error;
6
7 // Some of the elaborate cases from the rcc codebase, which is a C compiler in
8 // Rust. https://github.com/jyn514/rcc/blob/0.8.0/src/data/error.rs
9 #[derive(Error, Debug)]
10 pub enum CompilerError {
11 #[error("cannot shift {} by {maximum} or more bits (got {current})", if *.is_left { "left" } else { "right" })]
12 TooManyShiftBits {
13 is_left: bool,
14 maximum: u64,
15 current: u64,
16 },
17
18 #[error("#error {}", (.0).iter().copied().collect::<Vec<_>>().join(" "))]
19 User(Vec<&'static str>),
20
21 #[error("overflow while parsing {}integer literal",
22 if let Some(signed) = .is_signed {
23 if *signed { "signed "} else { "unsigned "}
24 } else {
25 ""
26 }
27 )]
28 IntegerOverflow { is_signed: Option<bool> },
29
30 #[error("overflow while parsing {}integer literal", match .is_signed {
31 Some(true) => "signed ",
32 Some(false) => "unsigned ",
33 None => "",
34 })]
35 IntegerOverflow2 { is_signed: Option<bool> },
36 }
37
38 // Examples drawn from Rustup.
39 #[derive(Error, Debug)]
40 pub enum RustupError {
41 #[error(
42 "toolchain '{name}' does not contain component {component}{}",
43 .suggestion
44 .as_ref()
45 .map_or_else(String::new, |s| format!("; did you mean '{}'?", s)),
46 )]
47 UnknownComponent {
48 name: String,
49 component: String,
50 suggestion: Option<String>,
51 },
52 }
53
54 #[track_caller]
55 fn assert<T: Display>(expected: &str, value: T) {
56 assert_eq!(expected, value.to_string());
57 }
58
59 #[test]
60 fn test_rcc() {
61 assert(
62 "cannot shift left by 32 or more bits (got 50)",
63 CompilerError::TooManyShiftBits {
64 is_left: true,
65 maximum: 32,
66 current: 50,
67 },
68 );
69
70 assert("#error A B C", CompilerError::User(vec!["A", "B", "C"]));
71
72 assert(
73 "overflow while parsing signed integer literal",
74 CompilerError::IntegerOverflow {
75 is_signed: Some(true),
76 },
77 );
78 }
79
80 #[test]
81 fn test_rustup() {
82 assert(
83 "toolchain 'nightly' does not contain component clipy; did you mean 'clippy'?",
84 RustupError::UnknownComponent {
85 name: "nightly".to_owned(),
86 component: "clipy".to_owned(),
87 suggestion: Some("clippy".to_owned()),
88 },
89 );
90 }
91
92 // Regression test for https://github.com/dtolnay/thiserror/issues/335
93 #[test]
94 #[allow(non_snake_case)]
95 fn test_assoc_type_equality_constraint() {
96 pub trait Trait<T>: Display {
97 type A;
98 }
99
100 impl<T> Trait<T> for i32 {
101 type A = i32;
102 }
103
104 #[derive(Error, Debug)]
105 #[error("{A} {b}", b = &0 as &dyn Trait<i32, A = i32>)]
106 pub struct Error {
107 pub A: PathBuf,
108 }
109
110 assert(
111 "... 0",
112 Error {
113 A: PathBuf::from("..."),
114 },
115 );
116 }