Skip to main content

Crate codespace

Crate codespace 

Source
Expand description

A structured container for generated Rust code.

Code generators that emit raw TokenStreams face a practical problem: a single type definition often requires multiple top-level items–the struct or enum itself, helper functions, impl blocks, and so on. Putting all of those into one TokenStream makes it hard to keep related items together or to route ancillary items (e.g. serde default helpers) into a dedicated module.

codespace provides a scratch space for accumulating and emitting Rust code. A Codespace holds a root Mod; each Mod holds named items (raw TokenStream fragments) and named sub-Mods in separate maps. When code generation is complete, Codespace::into_stream flattens everything into a single TokenStream suitable for writing to a file or handing to a proc-macro output; Codespace::into_files produces output that can be emitted into multiple files (i.e. one mod per file).

§Paths

Codespace::add_item and Mod::add_item accept a "::" delimited path. Each segment except the last names a submodule (and must be a valid Rust identifier). The final segment is an arbitrary sort key that is never emitted as a token; usually this should match the name of the relevant item.

use codespace::Codespace;
use quote::quote;

let mut cs = Codespace::default();
cs.add_item("Status", quote! { pub enum Status { Active, Inactive } });
cs.add_item("defaults::status_default", quote! {
    pub fn status_default() -> Status { Status::Active }
});
// Renders to:
//   pub enum Status { ... }
//   pub mod defaults { pub fn status_default() ... }
let tokens: proc_macro2::TokenStream = cs.into_stream();

§Ordering

Within each Mod, items are emitted in sort-key order and submodules in alphabetical order by name.

Structs§

Codespace
A structured collection of generated Rust items, organized into a tree of modules.
Mod
A node in the Codespace tree.

Enums§

Visibility
Visibility of a Mod, as rendered on its mod block or declaration.