Pattern to type in macro

I'm trying to get the type name of a certain pattern branch in a macro. I have the current macro that I use for returning errors:

enum Test {

macro_rules! expect {
    ($e:expr, $to_be:pat) => {
        match $e {
            Some($to_be) => {},
            Some(got) => return Err(stringify!($to_be)),
            None => return Err("Unexpected"),

now, the stringify is fine if my pattern is not a tuple (eg: Test1), however it will print the arguments if i call it with a tuple (eg: Test2(_)). Is there a way to get only the type out of a pat in a macro ? It would even be better if it doesn't print the path like: Test::Test1 and instead print onlyTest1.

Note: my enum type implements Into<&str>.

I don't understand based on the description alone what you are looking for. Can you provide specific, demonstrative examples of what results you get and what results you want?

No, I don't think so. You can achieve this with a function-like procedural macro, though. They are much more powerful than declarative macros, allowing you to manipulate the input TokenStream, extracting the information you need with the syn crate.
I can recommend the little book of rust macros very much! It is a great source of knowledge about rust macros, declarative and procedural. There is a section on function-like procedural macros, hope that will help you.

Also, with the structure of your macro, you can't invoke Into<&str> on $to_be, because $to_be is a pattern, not a type. Unfortunately, if you provide $to_be as a type (ty) instead, your macro will fail. Some($to_be) won't work, because it expects a pattern.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.