Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Code-generation hooks

Niche feature. Hooks are aimed at users who need to attach extra impl blocks 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 the struct/enum). Emit the trait impl directly 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

ContextFiresNames
Enum / Set / Compositeafter the typename, variants / choices / fields
MessageDecoderafter the message decodername (QuoteDecoder), fields, schema_marker (the {Name}Schema type, renamed when a schema type takes the plain name)
GroupEntryDecoderonce per group entry type, nested groups included, depth-first straight after its message decodername (QuoteLegsEntryDecoder), group_decoder (QuoteLegsDecoder), fields, enclosing (the message, then each parent entry, as BlockInfo { decoder, fields })
MessageEncoderafter the encodername, fields
DomainStructafter each DTO, message and entryname, 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:

FieldValue
name / schema_namesnake_case Rust name / the name as the schema spells it (qtyExponent)
kind, rust_type, offset, presence, since_version, …schema metadata
accessordecoder 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_typeits 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>
extensionsthe 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.

ContextCarries
Enum / Set / Compositethat <enum> / <set> / <composite> element’s own marks
MessageDecoder / MessageEncoderthe <message> element’s marks, foreign children included
GroupEntryDecoderthe <group> element’s marks
DomainStructthe <message> (message DTO) or <group> (entry DTO) element’s marks
EnumVariantInfo / SetChoiceInfothat <validValue> / <choice> element’s marks
FieldInfothat <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.