Code-generation hooks
Niche feature. Hooks are aimed at users who need to attach extra
implblocks to generated code: serde, custom validation, company-internal traits. Most workflows don’t need them; skip this section unless you recognise your use case.Hooks append tokens after each generated item; they cannot add a
#[derive(...)]to the item itself (that attribute would have to precede thestruct/enum). Emit the traitimpldirectly instead; that is what a derive would expand to anyway.
Hooks let you append arbitrary Rust tokens after each generated item (enum, set,
composite, message decoder/encoder, group entry decoder, domain struct). The
closure receives an
ItemContext
with structured field/variant/choice metadata, plus a schema reference for
full IR access.
Example: add serde Serialize + Deserialize to every enum and set:
// build.rs
use ergo_sbe::{GenerationConfig, ItemContext};
use quote::quote;
fn serde_hook(ctx: &ItemContext) -> Vec<proc_macro2::TokenStream> {
match ctx {
ItemContext::Enum { name, variants, .. } => {
let ident = quote::format_ident!("{name}");
let labels: Vec<_> = variants.iter().map(|v| v.label.clone()).collect();
let names: Vec<_> = variants.iter().map(|v| quote::format_ident!("{}", v.name)).collect();
let from_labels: Vec<_> = variants.iter().map(|v| quote::format_ident!("{}", v.name)).collect();
vec![quote::quote! {
impl serde::Serialize for #ident {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(match self {
#(Self::#names => #labels,)*
_ => "NullVal",
})
}
}
impl<'de> serde::Deserialize<'de> for #ident {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = <&str>::deserialize(d)?;
match s {
#(#labels => Ok(Self::#from_labels),)*
"NullVal" => Ok(Self::NullVal),
// Reject unknown values; fallback is app policy,
// not codec behaviour.
other => Err(serde::de::Error::unknown_variant(
other, &[#(#labels,)* "NullVal"])),
}
}
}
}]
}
ItemContext::Set { name, choices, .. } => {
let ident = quote::format_ident!("{name}");
let is: Vec<_> = choices.iter().map(|c| quote::format_ident!("is_{}", c.snake_name)).collect();
let labels: Vec<_> = choices.iter().map(|c| c.label.clone()).collect();
let froms: Vec<_> = choices.iter().map(|c| quote::format_ident!("{}", c.snake_name)).collect();
vec![quote::quote! {
impl serde::Serialize for #ident {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut names = Vec::new();
#(if self.#is() { names.push(#labels); })*
names.serialize(s)
}
}
impl<'de> serde::Deserialize<'de> for #ident {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let names: Vec<&str> = <Vec<&str>>::deserialize(d)?;
let mut val = Self::default();
for n in &names {
match *n {
#(#labels => { val.#froms(true); })*
// Reject unknown labels; don't silently drop.
other => return Err(serde::de::Error::unknown_variant(
other, &[#(#labels),*])),
}
}
Ok(val)
}
}
}]
}
_ => vec![],
}
}
let config = GenerationConfig::new("msgs").with_hook(serde_hook);
Each ItemContext variant carries the fields, variants, or choices defined in
the schema; use them to build custom impl blocks or trait implementations.
Hooks fire in registration order; the returned tokens are appended after the
generated item (so they extend it with impls, not with derives).
Contexts
| Context | Fires | Names |
|---|---|---|
Enum / Set / Composite | after the type | name, variants / choices / fields |
MessageDecoder | after the message decoder | name (QuoteDecoder), fields, schema_marker (the {Name}Schema type, renamed when a schema type takes the plain name) |
GroupEntryDecoder | once per group entry type, nested groups included, depth-first straight after its message decoder | name (QuoteLegsEntryDecoder), group_decoder (QuoteLegsDecoder), fields, enclosing (the message, then each parent entry, as BlockInfo { decoder, fields }) |
MessageEncoder | after the encoder | name, fields |
DomainStruct | after each DTO, message and entry | name, fields |
Type names are the generated ones: the message prefix in a multi-message
schema and the parent-group prefix of a nested group are already applied.
Decoder contexts list fixed fields (constants included, presence == "constant"), then groups, then var-data. Each FieldInfo
carries:
| Field | Value |
|---|---|
name / schema_name | snake_case Rust name / the name as the schema spells it (qtyExponent) |
kind, rust_type, offset, presence, since_version, … | schema metadata |
accessor | decoder contexts only: the decoder method returning the field (price, price_wire under a conversion, type_ for a keyword, wrap_field for a reserved name, the domain getter under a domain type) |
accessor_type | its exact return type as Rust source (i64, Option<u32>, [u8; 16], Result<QuoteLegsDecoder<'a>, sbe_rt::DecodeError>), read from the generated decoder; may name the decoder’s lifetime 'a, so emit into impl<'a> Decoder<'a> |
extensions | the element’s extension marks |
Hooks that can fail
with_try_hook registers a hook returning Result<Vec<TokenStream>, String>.
An Err(reason) stops generation with GenerateError::Hook { item, reason },
where item is the context’s kind and generated type name
("GroupEntryDecoder QuoteLegsEntryDecoder"). Plain and try hooks run
together in registration order.
#![allow(unused)]
fn main() {
use ergo_sbe::{FieldKind, GenerationConfig, ItemContext};
let config = GenerationConfig::new("msgs").with_try_hook(|ctx: &ItemContext| {
let ItemContext::GroupEntryDecoder { name, fields, .. } = ctx else {
return Ok(vec![]);
};
if fields.iter().any(|f| f.kind() == FieldKind::Data) {
return Err(format!("{name}: var-data in a group is not supported here"));
}
Ok(vec![])
});
}
Full runnable example with serde + serde_json round-trip:
hook_serde_test.
Extension XML on hook contexts
Every ItemContext variant carries the schema extension content of the
element it was generated from: namespaced attributes and foreign-namespace
child elements that the SBE grammar does not own.
| Context | Carries |
|---|---|
Enum / Set / Composite | that <enum> / <set> / <composite> element’s own marks |
MessageDecoder / MessageEncoder | the <message> element’s marks, foreign children included |
GroupEntryDecoder | the <group> element’s marks |
DomainStruct | the <message> (message DTO) or <group> (entry DTO) element’s marks |
EnumVariantInfo / SetChoiceInfo | that <validValue> / <choice> element’s marks |
FieldInfo | that <field> / <group> / <data> element’s marks |
Look marks up by local name — any prefix works: extensions.attr("jsonValue"),
extensions.child("meta"), extensions.is_empty(). Marks on <data>,
<group> elements and type-level declarations reach hooks but are invisible
to ConversionSelector::ExtensionAttr,
which selects message and group fields only.
Example: emit a JSON label from a jsonValue mark on each variant:
/// Emit `json_label()` for enums whose validValues all carry a `jsonValue`
/// extension mark; enums with partial or no coverage are left untouched, so
/// schemas without marks generate byte-identical code.
fn json_label_hook(ctx: &ergo_sbe::ItemContext) -> Vec<proc_macro2::TokenStream> {
let ergo_sbe::ItemContext::Enum { name, variants, .. } = ctx else {
return Vec::new();
};
let mut arms = Vec::new();
for v in variants {
let Some(label) = v.extensions.attr("jsonValue") else {
return Vec::new(); // partial coverage: skip the whole enum
};
let var = quote::format_ident!("{}", v.name);
arms.push(quote::quote! { Self::#var => #label, });
}
if arms.is_empty() {
return Vec::new();
}
let ident = quote::format_ident!("{name}");
// Generated enums carry a `NullVal` variant, hence the wildcard arm.
vec![quote::quote! {
impl #ident {
pub fn json_label(&self) -> &'static str {
match self { #(#arms)* _ => "UNKNOWN" }
}
}
}]
}
The exchange sample applies exactly this hook to its venue schema — exchange example.
Capture rules, the consts switch, the example label and field-pair hooks
and ExtensionAttr selectors: Extension XML.