1

I am trying to write an attribute macro for a proc-macro that would allow me to remove a field from a struct or completely replace its signature.

Something similar to this:

#[derive(my_macro)]
struct OurStruct{
       a: i32,
       #[my_macro(remove)]
       field_to_remove: i32
}

Which should result in:

struct OurStruct{
       a: i32,
}

I know how to write macros to add to the impl part of the struct but so far I have problem finding any sample on how to modify the part of the code marked by an attribute-macro.

Is that possible? If so, can you please provide a sample?

Reza
  • 1,478
  • 1
  • 15
  • 25
  • you basically asking to explain how to do a proc macro that quite too broad – Stargateur Dec 04 '21 at 09:22
  • 1
    No I am not asking how to do a proc macro. I have already written the rest of the code using darling. This is just the last part of the code and is specifically regarding attribute macros and if they have access to the code span that they are marking. I know how to iterate over each field or its attributes. I know how to write something similar to dervie(default). This is a very specific case. Which I think is not possible with current rust. – Reza Dec 04 '21 at 11:29
  • 1
    AFAIK, you have access to the token tree in the proc macro so you have access to everything, you asking "how to find this in the token tree" that sum up to "how to proc macro", if you already have a working code you probably know more about how to make a proc macro than me in practice, my point is your question look very broad. I recommend you search how serde do it https://serde.rs/field-attrs.html#skip, serde have a lot of attribute on field so you should find a lot of example on how do the thing you ask. – Stargateur Dec 04 '21 at 11:33
  • You need to use attribute proc macro. It accepts all tokens of a struct and returns new tokens to place instead. – Angelicos Phosphoros Dec 04 '21 at 12:34
  • I have already implemented something similar to skip. Skip doesn't; remove the field from the struct, it doesn't implement the serializer. deserializer code. What I need is to completely remove the field while adding some code to the body of the impl section. – Reza Dec 04 '21 at 21:29
  • You can't using a derive macro, but you can using an attribute macro. – Chayim Friedman Dec 05 '21 at 18:54
  • It seems attribute macro inside derive macro is experimental. – Reza Dec 06 '21 at 01:53
  • Not inside, just [attribute macro](https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros) – Chayim Friedman Dec 06 '21 at 10:14

0 Answers0