Provides a builder API to assist in generating Rust code.
This is a fork of the upstream codegen crate (0.3.0). On top
of upstream it emits deterministic, sorted output (see below) and adds a few builder extensions
— import aliases, field/tuple visibility, cfg_attr on items, and scope merging — with no
syn/quote dependency.
To use codegen, first add it as a dependency
cargo add codegen- Create a
Scopeinstance. - Use the builder API to add elements to the scope.
- Call
Scope::to_string()to get the generated code.
use codegen::Scope;
let mut scope = Scope::new();
scope.new_struct("Foo")
.derive("Debug")
.field("one", "usize")
.field("two", "String");
println!("{}", scope.to_string());Top-level items are emitted in a canonical order — sorted by name, then by kind (a struct sorts
ahead of other items sharing its name) — so the order in which you add them does not change the
output. A type and its impl blocks always group together, and generated source stays stable
across unrelated input changes, which makes it well-suited to snapshot testing. Insertion order is
preserved within an item (fields, variants, function bodies).
codegen will not attempt to perform anything beyond basic formatting. For
improved formatting, the generated code can be passed to rustfmt.
This project is licensed under the MIT license.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in codegen by you, shall be licensed as MIT, without any
additional terms or conditions.