Why is a negative integer not a valid pattern in a macro?

Consider a simple enumeration implementation with a static method that checks whether a related value matters (implementation efficiency is not considered here):

enum Letter { Alpha = -1, A = 0, B = 1, C = 2, } impl Letter { pub fn in_enum(value: isize) -> bool { match value { -1 => true, 0 => true, 1 => true, 2 => true, _ => false, } } } 

Now we will write a macro to create enumerations using the equivalent in_enum method. The macro below was written with some guidance from Ceard 's guide to enum deserialization as a number , which also compares enumeration option variants.

 macro_rules! my_enum { ($name:ident { $($variant:ident = $value:expr, )* }) => { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum $name { $($variant = $value,)* } impl $name { pub fn in_enum(value: isize) -> bool { match value { $( $value => true, )* _ => false, } } } } } my_enum!(Letter { Alpha = -1, A = 0, B = 1, C = 2, }); 

Playground Now the compiler will not accept the negative integer option.

 error: expected pattern, found `-1` --> src/main.rs:13:24 | 13 | $( $value => true, )* | ^^^^^^ 

This happens regardless of how I write this template in a macro, or use i32 or isize for the parameter of the value method. Changing the fragment specifier from $value to pat also out of the question: the compiler will refuse to create an enumeration, even without negative variant values.

 error: expected expression, found `-1` --> src/main.rs:5:26 | 5 | $($variant = $value,)* | ^^^^^^ 

What is surprising about this is that it works without the use of macros, and also when I drop the Alpha option.

Why is this happening?

+5
source share
1 answer

This is a bug in the compiler and has already been fixed in the night version for today (July 5, 2017).

+5
source

Source: https://habr.com/ru/post/1269486/


All Articles