z-jxy / rpkl

Pkl bindings for Rust
MIT License
3 stars 2 forks source link

Codegen Flexibility/Improvements #6

Open z-jxy opened 1 week ago

z-jxy commented 1 week ago

Currently, the codegen feature doesn't provide much flexibility with how the structs are generated. For instance, you can't specify that a struct should derive a specific attribute, like Debug, Clone, or some other custom attribute.

As a more robust solution, I wanted to experiment with using a build feature/crate to generate the rust structs from pkl modules as part of the build. This would be similar to how prost-build handles codegen for gRPC. The idea is to run the codegen during build and output it to the target directory, then include the generated file using a macro.

Example use would be something along these lines

helloworld.pkl:

Hello {
  message = "World"
}

build.rs:

fn main() -> std::io::Result<()> {
    pkl_rs::build::configure()
      .derive("helloworld.Hello", "Clone") // add `Clone` to the `Hello` object in the `helloworld` module
      .derive(".", "Debug") // derive `Debug` for all structures
      .generate(&["./helloworld.pkl"], &["./"])?;
    Ok(())
}

main.rs:

pub mod hello_world {
    pkl_rs::include_pkl!("helloworld");
}

let hello: hello_world::Hello = pkl_rs::from_config("./helloworld.pkl")?;

Pros

Cons

Sir-NoChill commented 6 days ago

Just as I get a feel for your repo I'm writing some test cases and documentation. I would like to know where you are at on parsing additional primitive/non-primitive types for the codegen so that we don't duplicate work :melting_face:

Also in terms of contribution workflow, I'm currently working on my own fork and will send a PR from there. Anything specific you want from that?

z-jxy commented 6 days ago

@Sir-NoChill Originally I was using serde_json to deserialize the PklMod members, so any datatypes that couldn't be represented as json got thrown under this todo.

Since it's not relying on json compatibility now though, I think we could represent some of these types using the type system, like Duration.