Skip to content

macro argument cannot be both expr and pat #9293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
klutzy opened this issue Sep 18, 2013 · 1 comment
Closed

macro argument cannot be both expr and pat #9293

klutzy opened this issue Sep 18, 2013 · 1 comment
Labels
A-syntaxext Area: Syntax extensions

Comments

@klutzy
Copy link
Contributor

klutzy commented Sep 18, 2013

I tried to write a macro which generates enum, FromStr, and ToStr:

macro_rules! some_macro(
    ($mod_name:ident, $enum_name:ident, $($a:ident ~ $b:expr),+) => (
        mod $mod_name {
            #[deriving(Eq)]
            pub enum $enum_name {
                $(
                    $a,
                )+
            }

            impl ToStr for $enum_name {
                fn to_str(&self) -> ~str {
                    match *self {
                        $(
                            $a => $b.to_owned(),
                        )+
                        _ => fail!("to_str failure: %?", self),
                    }
                }
            }

            impl FromStr for $enum_name {
                fn from_str(s: &str) -> Option<$enum_name> {
                    match s {
                        $(
                            $b => Some($a),
                        )+
                        _ => None,
                    }
                }
            }
        }
    )
)

some_macro!(TestMod, Test,
    A ~ "a",
    B ~ "b"
)

(mod $mod_name is due to #4375.)
However this fails to build:

tmp.rs:68:29: 68:30 error: unexpected token: `"a"`
tmp.rs:68                             $b => Some($a),
                                       ^

because $b is expr and not pat. Changing $b:expr to $b:pat gives another error:

tmp.rs:57:35: 57:36 error: unexpected token: `an interpolated pattern`
tmp.rs:57                             $a => $b.to_owned(),
                                             ^

since $b is not expr. As a workaround I had to use classical if-else block.
I'm not sure if this is intended design decision or just unexpected/unimplemented. I think it's good if I can specifiy $b both expr and pat, or there is some other smart way to solve it.

@klutzy
Copy link
Contributor Author

klutzy commented May 28, 2014

I now think this is non-issue since macro can accept $b:tt and invoke other macro which accepts $b:expr or $b:pat.

@klutzy klutzy closed this as completed May 28, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-syntaxext Area: Syntax extensions
Projects
None yet
Development

No branches or pull requests

1 participant