Skip to content

Creating a trait function with a macro using block designator: error: expected ; or {, found { ... } #54707

Description

@birktj

Given a simple macro:

macro_rules! def_fn{
    ($body:block) => {
        fn test() $body
    };
}

I can use it without problems to define a function:

def_fn!({println!("test"); });

I can also use it to define a struct method without problems:

struct Test {}

impl Test {
    def_fn!({println!("test"); });
}

However when I try to use it to define a default method for a trait it doesn't work:

trait Test {
    def_fn!({println!("test"); });
}

It gives an error message:

error: expected `;` or `{`, found `{ println!("test"); }`
  --> src/main.rs:9:19
   |
9  |         fn test() $body
   |                   ^^^^^ expected `;` or `{`
...
16 |     def_fn!({println!("test"); });
   |     ------------------------------ in this macro invocation
error: aborting due to previous error

If I change the macro to include braces around $body it works:

macro_rules! def_fn{
    ($body:block) => {
        fn test() {$body}
    };
}

I have no idea why this happens but I guess it is some sort of bug in how default trait methods are parsed.

Activity

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-parserArea: The lexing & parsing of Rust source code to an ASTC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions