MenuUse / The generator

The generator

fe_codec_gen reads the #[serializable] structs and enums in your modules and writes their Schema, Serialize, Deserialize and Describe impls as ordinary Fe source. With --eip712 it writes static EIP-712 struct hashing instead. It is a native program written in Fe, built with fe alone, and its output depends only on its inputs: the same sources always give the same bytes.

Command line

fe_codec_gen --source src/models.fe --out src/serializers.fe
Option Meaning
--source <path> A top-level module of the ingot that declares models: a file directly in the ingot’s src/, beside its fe.toml. Repeat it for several modules of the same ingot.
--out <path> The module to create or update. It must be a different module in the same src/.
--check With --out: fail if the module is missing or stale, and write nothing. Use it in CI.
--stdout Print the module instead of writing it. This is the mode build systems use; it writes no files.
--eip712 Write EIP-712 struct hashing for #[eip712] structs instead of serializers. See EIP-712.

--out never replaces a file that it didn’t write: a file that doesn’t start with // Generated by fe_codec_gen. Do not edit. is reported as handwritten. A failed run leaves the existing file as it was.

The generated module imports every module you pass with --source and everything those modules import, so field types resolve as they do in your code. The generator copies field types as written and lets the Fe compiler check them.

Diagnostics

Errors are printed as path:line:column: error: message, with the path as given on the command line and the column counted in characters. The exit status is 1. Syntax errors are reported where fe check reports them. Usage errors exit with status 2.

The generator rejects only what the compiler cannot catch:

  • usize and isize, whose width differs per target;
  • Option<Option<T>>, which cannot round-trip;
  • a local type used by a model but not marked #[serializable];
  • an array whose elements would need Copy to be decoded;
  • a list whose elements are not Copy, as a list stores copies of them;
  • a map whose values are not Copy, for the same reason;
  • a map key that can never be a MapKey: a signed integer, bool, BoundedBuffer, Option, an array, a tuple, a list, a map, or a struct or enum in the sources (a key that is a type parameter is left to the compiler, so give it the bound MapKey);
  • an empty array inside another type, including inside a list, map or tuple, which core cannot decode;
  • the unit type (), which has no wire form;
  • duplicate or missing #[codec_id]s, a zero field ID, and IDs that aren’t 64-bit integer literals;
  • a misplaced or malformed #[codec_with]: on a struct, an enum or a variant (it belongs on struct fields and record variant fields), twice on one field, without a value, or with anything but a path such as Hex or ingot::codecs::Hex (generic arguments are rejected);
  • a misplaced or malformed #[codec_skip_unknown]: on a field, a variant, or a struct or enum that isn’t #[serializable], with arguments or a value, or twice on one declaration;
  • an attribute starting with codec that the place doesn’t take, such as the typo #[codec_skip_unkown] on a struct or an enum (structs and enums take codec_skip_unknown, fields codec_id and codec_with, variants codec_id), which is an error on a #[serializable] declaration, its fields and its variants;
  • a tuple variant without elements (A()), and a record variant whose generated type (below) has the name of another type;
  • names longer than 31 bytes, private fields, generic enums, empty enums, where clauses and generic parameters with defaults.
src/models.fe:5:12: error: 'usize' has a different width on each target; use a fixed-width integer

Per-field codecs

#[codec_with = Path] on a field makes the generated Serialize, Deserialize and Describe impls use the FieldCodec at Path for that field. Path is a type path, written as it resolves in the module that declares the struct; the generated module copies it as written. To use a generic codec such as Hex<8>, name it with a type alias, type Hex8 = Hex<8>.

#[serializable]
pub struct Payment {
    #[codec_with = HexAmount]
    pub amount: u64,
    #[codec_with = HexAmount]
    pub tip: Option<u64>,
}
  • The codec owns the field’s representation, so the checks on its type are skipped: it can be usize, a type that isn’t #[serializable], Option<Option<T>>, (), or an array of elements that aren’t Copy. Arrays are handed to the codec whole and are not decoded element by element. What is still checked is everything about the field itself: it is pub, its name is unique and at most 31 bytes, and its #[codec_id] is valid. A type parameter that only codec fields use still gets the Serialize, Deserialize and Describe bounds.
  • For an Option<T> field the codec applies to T. The field stays optional in the schema, keyed formats leave None out, and a present value is written as the format’s marker for one, then the codec’s value. Any other type is passed to the codec whole.
  • IDs, field order and Schema are unchanged.
  • --eip712 rejects a codec_with field in an #[eip712] struct or in a struct one reaches, since the type string comes from the field type. Other structs with codec_with fields are fine in that mode. The generic EIP-712 path uses the codec’s describe.

Enums with payloads

An enum may have tuple variants, A(T0, T1), and record variants, A { pub x: T0, pub y: T1 }, as well as unit ones. The generator checks their types as it does a struct’s fields: a tuple variant’s elements as the elements of a tuple, a record variant’s fields as a struct’s, with the same attributes. #[codec_id] goes on variants and on the fields of record variants, and #[codec_with] on the fields of record variants; the elements of a tuple variant take neither. An enum whose variants all have no payload generates the code it always did.

A record variant needs a schema to name its fields, so the generator writes a type for it, an empty struct Codec_Enum_Variant {} with a Schema impl, in the generated module. A type of yours may not have that name, and neither may two variants; the generator reports it. --eip712 rejects a payload enum that an #[eip712] struct uses, as it does a tuple, because EIP-712 has no union type; a payload enum nothing of the kind reaches is fine.

Skipping unknown fields

#[codec_skip_unknown] on a #[serializable] struct or enum takes no arguments. The generated Schema then returns true from skips_unknown_fields, which JSON and CBOR decoders read to skip a field the struct does not list instead of failing with UnknownField. Nothing else in the generated code changes, and IDs, field order and EIP-712 hashing are the same.

#[serializable]
#[codec_skip_unknown]
pub struct Account { pub owner: u64, pub balance: u64 }

On an enum, each record variant skips; unit and tuple variants have no fields to skip, and an unknown variant is still an error.

Running it from FeMP

FeMP can run the generator as part of every build, so generated files never enter your source tree:

[modules.shared.generate.serializers]
command = ["fe_codec_gen", "--source", "src/models.fe", "--stdout"]
output = "src/serializers.fe"

# Only if you sign #[eip712] structs:
[modules.shared.generate.eip712]
command = ["fe_codec_gen", "--source", "src/models.fe", "--eip712", "--stdout"]
output = "src/eip712.fe"

--stdout is the generator mode of the Fe Source Generator Protocol (FSGP), which FeMP specifies in its docs/source-generators.md: arguments in, Fe source on standard output, diagnostics on standard error. Run femp generate once to give your editor a copy, and ignore that path in Git.

How it is built and tested

The generator lives in tools/: tools/syntax is fe_syntax, a lexer and parser for Fe declarations, tools/codegen is the generator itself, with no I/O, and tools/generator is the executable around it. The same code, compiled to WebAssembly, runs in the site’s playground. Four suites check it without storing any of its output:

  • tests/generator_cases.py covers every diagnostic with its exact position, the command line, and output that compiles;
  • tests/generator_fuzz.py generates random models, compiles and runs their serializers on two backends, compares the bytes with independent reference encoders and the EIP-712 specification, and requires that reformatting a model never changes the output;
  • tests/parser_vs_fe.py checks the parser against fe check on mutated sources;
  • tests/playground_parity.mjs checks that the playground’s WebAssembly build gives the same output and diagnostics as the native one on every single-module case.