the title is self explanatory
does the input for an attribute proc macro need to be valid rust syntax?
It needs to be syntactically valid, but not necessarily semantically valid.
what's the difference?
For instance, an identifier directly following another identifier is not "real Rust". But it's valid as far as the parser is concerned, because the parser knows how to produce identifier tokens.
ah ok, thank you
that's enough for "bang" style procedural macros, but not for attribute macros.
attribute macros must be applied to an rust item, not arbitrary tokens.
I think what @bjorn3 meant by "not semantically valid", is that it doesn't need to be checked by the compiler, nevertheless, it still must be in a valid syntax form of an item, which an attribute proc-macro can be applied, such as a struct
, a mod
, a trait
, etc.
here's an example of syntactically valid but not semantically valid struct
definition:
#[my_fancy_attribute]
struct Foo<T: NonExistententTrait> {
pub x: NonExistentType<AAA, BBB<AAA, CCC>>,
pub x: <XXYYZZ as X::Y::Z>::AABBCC,
x: AllFieldsAreNamedX,
}
and this is NOT a syntactically valid struct
definition:
// failed to parse
#[my_fancy_attribute]
struct Not::An::Identifier {
x: i32,
y: i32,
}