Generating Rust protobuf code with a macro instead of build.rs

261 Views Asked by At

There are several Rust crates to support protobufs, but they all require running code generation during the build.rs stage.

Is it possible to generate protobuf-serialization code without the extra build step? I see two ways:

  • using Serde-like approach with the declared structs and possibly some derive or other macros, where the user actually writes out -- this might not work well for arbitrary protobuf serialization because the .proto file might not match well with the user-written structs.
  • using some magical "macro-based inline compiler", where user writes some magical
    protobuf!(include_str!("my_protobuf.proto"))
    and that generates all the needed code inline, without involving a separate build.rs magic. Is this something not possible at all? Or some negatives to this approach? Or just hasn't been done yet?
1

There are 1 best solutions below

2
bk2204 On

The reason most of the crates don't use the Serde-like approach is that serializing protobufs requires additional data that isn't part of the struct, namely the ID of the field. Because Serde doesn't provide a way to expose this functionality and most people don't want to write general-purpose parsing functionality like Serde already provides, in general this approach isn't effective.

It is in theory possible to use a macro to generate the protobuf code. However, as mentioned in the comments, this is much less efficient because it must be done on every compilation rather than cached. In large projects, Rust can already have slow compile times, so it's preferable to avoid recompiling things when possible.