Skip to content

Commit 1b45dad

Browse files
authored
Rollup merge of rust-lang#135397 - lqd:compiletest-enums, r=jieyouxu
compiletest: add erroneous variant to `string_enum`s conversions error As requested in rust-lang#135392, this adds which variant caused the string conversion failure. r? jieyouxu fixes rust-lang#135392
2 parents b532396 + 33ce74f commit 1b45dad

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

Diff for: src/tools/compiletest/src/common.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -39,18 +39,22 @@ macro_rules! string_enum {
3939
}
4040

4141
impl FromStr for $name {
42-
type Err = ();
42+
type Err = String;
4343

44-
fn from_str(s: &str) -> Result<Self, ()> {
44+
fn from_str(s: &str) -> Result<Self, Self::Err> {
4545
match s {
4646
$($repr => Ok(Self::$variant),)*
47-
_ => Err(()),
47+
_ => Err(format!(concat!("unknown `", stringify!($name), "` variant: `{}`"), s)),
4848
}
4949
}
5050
}
5151
}
5252
}
5353

54+
// Make the macro visible outside of this module, for tests.
55+
#[cfg(test)]
56+
pub(crate) use string_enum;
57+
5458
string_enum! {
5559
#[derive(Clone, Copy, PartialEq, Debug)]
5660
pub enum Mode {

Diff for: src/tools/compiletest/src/tests.rs

+27
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,30 @@ fn is_test_test() {
6666
assert!(!is_test(&OsString::from("#a_dog_gif")));
6767
assert!(!is_test(&OsString::from("~a_temp_file")));
6868
}
69+
70+
#[test]
71+
fn string_enums() {
72+
// These imports are needed for the macro-generated code
73+
use std::fmt;
74+
use std::str::FromStr;
75+
76+
crate::common::string_enum! {
77+
#[derive(Clone, Copy, Debug, PartialEq)]
78+
enum Animal {
79+
Cat => "meow",
80+
Dog => "woof",
81+
}
82+
}
83+
84+
// General assertions, mostly to silence the dead code warnings
85+
assert_eq!(Animal::VARIANTS.len(), 2);
86+
assert_eq!(Animal::STR_VARIANTS.len(), 2);
87+
88+
// Correct string conversions
89+
assert_eq!(Animal::Cat, "meow".parse().unwrap());
90+
assert_eq!(Animal::Dog, "woof".parse().unwrap());
91+
92+
// Invalid conversions
93+
let animal = "nya".parse::<Animal>();
94+
assert_eq!("unknown `Animal` variant: `nya`", animal.unwrap_err());
95+
}

0 commit comments

Comments
 (0)