Skip to content

New declarative macros, functions and fields not being recognized #91249

Open
@BeastLe9enD

Description

@BeastLe9enD

I ran into some issues with rustc 1.58.0-nightly (b426445 2021-11-24).
I have the following code:

#![feature(decl_macro)]

pub macro generate_class_new($name: ident) {
    pub struct $name {
        x: i32
    }

    impl $name {
        pub fn new(x: i32) -> Self {
            Self { x }
        }
    }
}

generate_class_new!(MyTestClass);

fn main() {
    let instance = MyTestClass::new(3);
}

What I try to do here is creating a macro that just creates a struct with a given identifier as a name.
When I call MyTestClass::new(3), the compiler complains that this function does not exist:

error[E0599]: no function or associated item named `new` found for struct `MyTestClass` in the current scope
  --> src/main.rs:18:33
   |
4  |     pub struct $name {
   |     ---------------- function or associated item `new` not found for this
...
18 |     let instance = MyTestClass::new(3);
   |                                 ^^^ function or associated item not found in `MyTestClass`

running cargo expand produces code that should work in my opinion:

#![feature(prelude_import)]
#![feature(decl_macro)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
pub macro generate_class_new($ name : ident) {
    pub struct $name {
        x: i32,
    }
    impl $name {
        pub fn new(x: i32) -> Self {
            Self { x }
        }
    }
}
pub struct MyTestClass {
    x: i32,
}
impl MyTestClass {
    pub fn new(x: i32) -> Self {
        Self { x }
    }
}
fn main() {
    let instance = MyTestClass::new(3);
}

Not sure if I'm doing something wrong here, but it pretty much looks like a bug for me

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-decl-macros-2-0Area: Declarative macros 2.0 (#39412)A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-discussionCategory: Discussion or questions that doesn't represent real issues.F-decl_macro`#![feature(decl_macro)]`requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions