Skip to content

Procedural macro attributes can't be applied to struct fields #53012

Open
@mjbshaw

Description

@mjbshaw

Given the simple program:

#![feature(rust_2018_preview)]
extern crate demo_macros;
use demo_macros::nop;

#[nop]
pub struct Foo {
  #[nop]
  pub foo_field: u32,
}

#[nop]
impl Foo {
  #[nop]
  pub fn foo_fn() {}
}

And the corresponding definition of the #[nop] attribute:

#![feature(rust_2018_preview)]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn nop(_args: TokenStream, input: TokenStream) -> TokenStream {
  return input;
}

Attempting to compile this results in the error:

error[E0658]: The attribute `nop` is currently unknown to the compiler and may have meaning added to it in the future (see issue #29642)
 --> src/lib.rs:7:3
  |
7 |   #[nop]
  |   ^^^^^^
  |
  = help: add #![feature(custom_attribute)] to the crate attributes to enable

error: aborting due to previous error

The problem is the #[nop] attribute on foo_field. If it's removed, the library compiles fine. I believe this is incorrect and that the code should compile as-is. The #[nop] macro can be applied to foo_fn just fine; it seems wrong that it doesn't work with foo_field.

Rust version: rustc --version: rustc 1.29.0-nightly (97085f9fb 2018-08-01)

Please let me know if there's anything I can do to be of assistance.

Here's a bash script that fully reproduces the issue:

#!/bin/bash

cargo +nightly new --lib demo_macros

cat >> demo_macros/Cargo.toml << EOF
[lib]
proc-macro = true
EOF

cat >| demo_macros/src/lib.rs << EOF
#![feature(rust_2018_preview)]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn nop(_args: TokenStream, input: TokenStream) -> TokenStream {
  return input;
}
EOF

cargo +nightly init --lib .

echo 'demo_macros = { path = "demo_macros" }' >> Cargo.toml

cat >| src/lib.rs << EOF
#![feature(rust_2018_preview)]
extern crate demo_macros;
use demo_macros::nop;

#[nop]
pub struct Foo {
  #[nop]
  pub foo_field: u32,
}

#[nop]
impl Foo {
  #[nop]
  pub fn foo_fn() {}
}
EOF

cargo +nightly build

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions