Skip to content
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

Macro is not working very well #8178

Closed
recrack opened this issue Aug 1, 2013 · 1 comment
Closed

Macro is not working very well #8178

recrack opened this issue Aug 1, 2013 · 1 comment
Labels
A-syntaxext Area: Syntax extensions

Comments

@recrack
Copy link
Contributor

recrack commented Aug 1, 2013

zz.rs

macro_rules! twice(
    ($a:expr) => ($a + $a);
)

macro_rules! twice_one(
    ($b:expr) => (1 + twice!($b) + 1);
)

fn main() {
    twice_one!(10);
}

result

#rustc --pretty expanded zz.rs

priv use std::prelude::*;
priv extern mod std;


mod __std_macros {
    #[macro_escape];
    #[doc(hidden)];
    priv use std::prelude::*;
    #[cfg(not(debug))]
    #[macro_escape]
    mod debug_macro {
        priv use std::prelude::*;
    }
}
fn main() { 1 + 10 + 10 + 1; }

zz-1.rs

macro_rules! twice(
    ($a:expr) => ($a + $a);
)

macro_rules! twice_one(
    ($b:expr) => (twice!($b) + 1);
)

fn main() {
    twice_one!(10);
}

result

#rustc --pretty expanded zz-1.rs
priv use std::prelude::*;
priv extern mod std;


mod __std_macros {
    #[macro_escape];
    #[doc(hidden)];
    priv use std::prelude::*;
    #[cfg(not(debug))]
    #[macro_escape]
    mod debug_macro {
        priv use std::prelude::*;
    }
}
fn main() { 10 + 10; }

result is different

@huonw
Copy link
Member

huonw commented Aug 1, 2013

Wow, this one appears to be the combination of two separate issues:

  1. if a macro invocation is allowed to expand to a item/statement (rather than an expression), it is assumed to do so (Syntax extensions (and macros) that start a line want to be a whole statement #5941)
  2. a macro expanding to multiple items is silently truncated at the first one (Macros attempting to expand to multiple items silently only expand to the first one #8012)

#5921 means that, in twice!($b) + 1, the twice!($b) gets treated as a statement/item macro, and then #8012 means that the trailing + 1 gets dropped (and so the behaviour is incorrect, and no error is reported).

This can be fixed by forcing the twice!($b) to be evaluated in an expression context (that is what is happening with the 1 + twice!($b) form), which can be done with some parens:

macro_rules! twice_one(
    ($b:expr) => ( (twice!($b) + 1) );
)

(Closing as a dup of those two issues.)

@huonw huonw closed this as completed Aug 1, 2013
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

2 participants