Crates.io | sourcegen |
lib.rs | sourcegen |
version | 0.3.0 |
source | src |
created_at | 2019-07-30 22:57:21.537718 |
updated_at | 2019-08-14 17:19:47.215262 |
description | This crate contains a procedural macro to work together with "sourcegen-cli" crate. |
homepage | |
repository | https://github.com/commure/sourcegen |
max_upload_size | |
id | 153089 |
size | 6,270 |
Source generator
Sourcegen is a toolkit for in-place source code generation in Rust.
In-place source code generation is like a procedural macro in Rust, but with a difference that it is expanded before Rust code is compiled. For example, one use-case could be generating data types based on an external definition.
You start with the following code:
#[sourcegen::sourcegen(generator = "json-schema", schema = "widget.json")]
struct Widget;
Then, you run a special tool that is built on top of the sourcegen-cli
crate:
cargo run --package json-schema-sourcegen
Which expands the code above into something like (this assumes that widget.json
schema defines a data type with
two fields, name
and weight
:
#[sourcegen::sourcegen(generator = "json-schema", schema = "widget.json")]
struct Widget {
/// Name of the widget
name: String,
/// Weight of the widget
weight: usize,
}
Next time you run the tool, it would not change the code as it is already in it's correct form.
In the current form, you build your own tool on top of the sourcegen_cli::run_tool
entry point. This function takes
a number of input parameters and a list of source generators implementations.
Source generators are similar to procedural macros, they take syntax as an input and return token stream as an output.
Input to source generators use syn
crate for representing syntax trees. Returned tokens are
rendered by generators into the source code and formatted via rustfmt
.
What are the benefits of generating source code this way compared to using procedural macros or generating code during
the build via build.rs
?
Advantages over procedural macros:
Advantages over build.rs
source generation:
include!
or other means (build.rs
cannot write to sources).However, there are also some disadvantages: