Reputation: 44807
I would like to use serde in code generation, embedding some complex nested object iterals into generated code.
I'm not expecting to serde produce anything other than something of the form:
const FOO: Foo = Foo {
bar: 0,
baz: Baz {
quux: 1
}
};
(Perhaps with me supplying the const FOO: Foo =
.)
Ron would seem to be the crate to use, but it looks like it doesn't produce the Rust syntax for literal values.
Have I misunderstood its purpose?
Upvotes: 3
Views: 384
Reputation: 602635
To literally do what you asked for you need to write a custom Serde serializer. It will be a bit of work to get all the details right. Most literals (e.g. strings, characters and numbers) can be serialized to valid Rust literals using the Display
implementation of proc_macro2::Literal
, which will take care of escaping special characters, suffixing floating point numbers with .0
if needed and similar details. However, it looks like implementing a serializer for structs will be up to you.
The most common approach to code generation in Rust is writing a proc macro, and using the quote crate to emit the source code. I don't know enough about your use case to be able to tell whether this would be a useful approach for your problem.
Upvotes: 1