Weird macro stuff

Hi,

Im attempting to write a macro that duplicates a struct in a weird way: assume that A is a struct which has fields f1, f2, ... of types F1, F2, ..., then I want to write a macro #[lora] that duplicates A to ALora and for each of its fields f1, ... fn it either duplicates them exactly as they are or changes their types to F1Lora, F2Lora, ... where we change a field F to FLora if in the definition of F it is decorated with #[lora] as well.

(What I actually want to implement is a macro that rewrites the code of any LLM Model as a LoRA model, duplicating its fields, methods etc and changing the base layers of the model (which can be fields of fields, ..., of the model's field) to be LoRA layers.).

Is such a thing even possible? Specifically, can a macro check if another type has a specific attribute in its definition during compilation? If not, is there a workaround?

Thank you in advance

You can define a derive macro to get the token stream of a struct, use syn to parse it to a DataStruct, whose Field members can carry attributes.

2 Likes

Not exactly, because the macro can only inspect the code that it is decorating. You can write the macro to emit type-system code that does something similar, though:

/// Implemented by all valid field types, possibly via a proc macro
pub trait IntoLora {
    type Lora;
    fn into_lora(self)->Self::IntoLora
}

/// Input to your proc macro...
struct Example {
    f1: F1,
    f2: F2,
    // ...
}

/// Outputs this: ...
struct ExampleLora {
    f1: <F1 as IntoLora>::Lora,
    f2: <F2 as IntoLora>::Lora,
    // ...
}

impl IntoLora for Example {
    type Lora = ExampleLora;
    fn IntoLora(self)->ExampleLora {
        ExampleLora {
            f1: self.f1.into_lora(),
            f2: self.f2.into_lora(),
            // ...
         }
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.