dtolnay / reflect

Compile-time reflection API for developing robust procedural macros (proof of concept)

Home Page:https://docs.rs/reflect

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Attribute Macro

cwfitzgerald opened this issue · comments

Are there any plans on supporting attribute macros? I came across this library when writing a macro that needs to rewrite the struct it's run on, and it would be very helpful to have a library like this for that purpose.

I don't plan to support that. The point of reflection as used here is in describing what behavior you want to take place at runtime, and in that sense it's not the right tool for describing compile-time rewriting of syntax.

To make sure I understand what you have in mind, could you give a code example of exactly what code you would like to be able to write if this were possible?

So I hope I'm understanding the purpose of this library right. This is also my first time writing a proc macro at all, so I may be misunderstanding any part of this 😄. This is the operation I want to do:

turn

#[bve_derive::serde_vector_proxy]
pub struct AddVertex {
    pub location: Vector3<f32>,
    pub normal: Vector3<f32>,
}

into

#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(from = "AddVertexSerde")]
pub struct AddVertex {
    pub location: Vector3<f32>,
    pub normal: Vector3<f32>,
}

#[derive(Deserialize)]
struct AddVertexSerde {
    pub location_x: f32,
    pub location_y: f32,
    pub location_z: f32,
    pub normal_x: f32,
    pub normal_y: f32,
    pub normal_z: f32,
}

impl From<AddVertexSerde> for AddVertex {
    #[inline]
    fn from(tmp: AddVertexSerde) -> Self {
        AddVertex {
            location: Vector3::new(tmp.location_x, tmp.location_y, tmp.location_z),
            normal: Vector3::new(tmp.normal_x, tmp.normal_y, tmp.normal_z),
        }
    }
}

From what I can tell, because I need to modify the attributes on the item I am called on, I have to use an attribute macro as opposed to a derive macro, despite the work I'm doing basically 100% suited to derive macros in every other way.

If you're curious, the reason I need to do this is that even with serde(flatten), the csv crate + serde can't figure out how to deserialize 1, 2, 3, 4, 5, 6 correctly.

This kinda thing seems to me like the ideal usecase for this library, introspecting on an input in order to generate sidecar structs/impls.

You should use Quote and Syn -- they are a perfect fit for what you showed.

Alright! Thanks for the help, and sorry for the bother!