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