Skip to content

Macros attempting to expand to multiple items silently only expand to the first one #8012

Closed

Description

@paulstansifer

Users who want a macro that expands to a collection items are required to wrap the RHS in {} in order to get them to expand to a whole block. However, if they fail to do so, they unexpectedly just get the first item of the block, rather than an error message.

macro_rules! print_if_nonzero(
    ($msg:expr, $($field:ident),*) => ( /*{*/
        $(
            if t.$field != 0 {
                println($msg);
            }
        )*
    /*}*/ )
)

struct T { x: int, y: int }

fn main() {
    let t = T { x: 0, y: 0 };
    print_if_nonzero!("hello", x, y);
}

...expands to...

fn main() { let t = T{x: 0, y: 0,}; if t.x != 0 { println("hello"); }; }

Activity

  1. paulstansifer commented on Jul 23, 2013

    @paulstansifer
    ContributorAuthor

    Thanks to kmc on IRC for reporting this.

  2. bstrie commented on Jul 24, 2013

    @bstrie
    Contributor

    Perhaps this is really just another plaintive cry for someone to tackle #4375.

  3. huonw commented on Aug 5, 2013

    @huonw
    Contributor

    Smaller testcase:

    rusti> macro_rules! t( () => { println("hi"); println("oops"); }) t!()
    hi
    ()
  4. nejucomo commented on Sep 29, 2013

    @nejucomo

    I don't understand how this is different than #4375. If not justification for the distinction is given, can we mark this as a duplicate?

  5. paulstansifer commented on Sep 29, 2013

    @paulstansifer
    ContributorAuthor

    This source of this problem probably isn't specific to items. I'm worried
    that there's a lurking (if minor) usability problem in the lack of erroring
    out in this case.

  6. kmcallister commented on Oct 2, 2013

    @kmcallister
    Contributor

    Yeah, jason_ on IRC provided this example using tuples:

    macro_rules! omg(($n:expr) => ($n,$n+1))
    omg!(100) // => 100, not (100, 101)
    
  7. added a commit that references this issue on Oct 2, 2013
    8284df9
  8. added a commit that references this issue on Oct 2, 2013
    d616603
  9. added a commit that references this issue on Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-syntaxextArea: Syntax extensions

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions