Real generated output
This page shows representative output produced by the current repository build from the committed
examples/single contract. The
repository commits these files and CI runs every generator with --check, so the linked files are
executable examples rather than illustrative pseudocode.
witforge rust --config examples/single/witforge.tomlwitforge proto --config examples/single/witforge.tomlwitforge schema --config examples/single/witforge.tomlwitforge glue --config examples/single/witforge.tomlThe source WIT defines an item record, an enum, flags, a variant, and one interface function.
Its wire.lock
assigns the field, case, parameter, and method numbers shown below. Every fenced generated-output
excerpt is checked line-for-line against the linked committed file; generated comments,
unrelated definitions, and surrounding module context may be omitted.
Plain Rust
Section titled “Plain Rust”The Rust emitter writes owned values and one trait per WIT interface that declares functions. WIT names become Rust identifiers; no Wasm runtime types appear in this output.
pub mod types { #[derive(Debug, Clone, PartialEq)] pub struct Item { pub id: u64, pub name: ::std::string::String, pub tags: ::std::vec::Vec<::std::string::String>, pub note: ::std::option::Option<::std::string::String>, }
#[derive(Debug, Clone, PartialEq)] pub enum Status { Accepted, Rejected, }
#[derive(Debug, Clone, PartialEq)] pub enum Event { Started, Item(Item), Finished(Status), }}
pub mod ingest { pub type Item = super::types::Item; pub type Event = super::types::Event;
pub trait Ingest { fn submit(&self, item: Item) -> Event; }}Full files: v0_1.rs,
worlds.rs,
and mod.rs.
Opt-in Rust flags enable additional profiles per project: --serde (serde = true) adds plain,
format-independent ::serde::Serialize and ::serde::Deserialize derives using these Rust
identifiers; --no-std (no-std = true) emits #![no_std]-compatible ::alloc::* and
::core::* paths; --eq-hash (eq-hash = true) derives Eq and Hash on float-free types;
and --try-from (try-from = true) emits TryFrom impls in convert.rs. See
JSON projections for the exact Serde JSON keys, reading rules, and
serde_json edge cases.
Protobuf
Section titled “Protobuf”The protobuf emitter uses the numbers in wire.lock. Required scalar and string values use
proto3 optional so generated glue can distinguish absence from a default value. WIT interfaces
produce request and response messages plus a stable method-ID enum, not protobuf services.
message TypesItem { optional uint64 id = 1; optional string name = 2; repeated string tags = 3; optional string note = 4;}
message TypesEvent { oneof witforge_value { Empty started = 1; TypesItem item = 2; TypesStatus finished = 3; }}
message IngestSubmitRequest { TypesItem item = 1;}
message IngestSubmitResponse { TypesEvent result = 1;}
enum IngestMethod { INGEST_METHOD_UNSPECIFIED = 0; INGEST_METHOD_SUBMIT = 1;}Full file: v0.proto.
Generate language-specific protobuf types from this file with the normal toolchain for that
language.
JSON Schema
Section titled “JSON Schema”The schema emitter writes one JSON Schema document per contract version (Draft 7 by default, or
Draft 2020-12 via --draft 2020-12 / draft = "2020-12"). Named WIT types live under
definitions (or $defs in Draft 2020-12); records are closed objects whose properties are all
required. An option<T> value accepts null, but the containing property is still required.
"types/item": {"description":"One item submitted to the ingester.","type":"object","properties":{"id":{"description":"Stable item id.","type":"integer","minimum":0,"maximum":18446744073709551615},"name":{"description":"Human-readable name.","type":"string"},"tags":{"description":"Free-form tags.","type":"array","items":{"type":"string"}},"note":{"description":"Optional note.","anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","tags","note"],"additionalProperties":false},"types/status": {"description":"The result state of an item.","type":"string","enum":["accepted","rejected"]},Full file: v0_1.schema.json.
Read JSON Schema and Rust Serde before treating both projections as one
JSON wire format.
Rust/protobuf glue
Section titled “Rust/protobuf glue”The glue emitter converts borrowed plain Rust values into owned prost values and validates the reverse conversion. Copy values are copied directly, owned values are cloned only when the target must own them, and already-owned identity collections move out of the protobuf value without an extra allocation.
type Plain = crate::generated::rust::v0_1::types::Item;type Proto = crate::generated::proto::v0::TypesItem;
/// Convert `types/item` to its protobuf representation.pub fn to_proto(value: &Plain) -> Proto { Proto { id: ::core::option::Option::Some(value.id), name: ::core::option::Option::Some(::core::clone::Clone::clone(&value.name)), tags: ::core::clone::Clone::clone(&value.tags), note: ::core::clone::Clone::clone(&value.note), }}
/// Convert `types/item` from its protobuf representation.pub fn from_proto(value: Proto) -> ::core::result::Result<Plain, GlueError> { let ::core::option::Option::Some(v0) = value.id else { return ::core::result::Result::Err(GlueError::MissingField { field: "types/item.id", }); }; let ::core::option::Option::Some(v1) = value.name else { return ::core::result::Result::Err(GlueError::MissingField { field: "types/item.name", }); }; ::core::result::Result::Ok(Plain { id: v0, name: v1, tags: value.tags, note: value.note, })}Every line in this excerpt is copied from the generated file. Emitted Rust is produced directly by
witforge (without shelling out to rustfmt) in rustfmt’s default style for both Edition 2021 and
Edition 2024, and passes default Clippy lints and #![deny(missing_docs)]. If your crate sets
non-default rustfmt.toml options, put #[rustfmt::skip] on the module declaration that includes
the generated tree. Full files:
v0.rs and
mod.rs.
Function helpers in the same module map WIT calls to protobuf request and response messages and expose the locked method ID:
type Method = crate::generated::proto::v0::IngestMethod;type Request = crate::generated::proto::v0::IngestSubmitRequest;type Response = crate::generated::proto::v0::IngestSubmitResponse;type Params = crate::generated::rust::v0_1::ingest::Item;type Output = crate::generated::rust::v0_1::ingest::Event;
/// Protobuf method identifier for `ingest#submit`.pub const METHOD: Method = Method::Submit;
/// Encode request parameters for `ingest#submit`.pub fn to_request(item: &crate::generated::rust::v0_1::ingest::Item) -> Request { let v0 = super::super::super::types::item::to_proto(item); Request { item: ::core::option::Option::Some(v0), }}
/// Decode request parameters for `ingest#submit`.pub fn from_request(value: Request) -> ::core::result::Result<Params, GlueError> { let ::core::option::Option::Some(v0) = value.item else { return ::core::result::Result::Err(GlueError::MissingField { field: "ingest#submit.item", }); }; super::super::super::types::item::from_proto(v0)}These are conversion helpers, not a transport or RPC service implementation.
Version adapters
Section titled “Version adapters”With adjacent contract versions, witforge rust also writes convert.rs. The evolved example adds
an optional priority and a list of tags; old values receive their WIT-safe defaults.
/// Convert `types/task` from 0.1.0 to 0.2.0.////// # Errors////// Returns an error when the source value cannot be represented by the target version.pub fn task( value: &super::__witforge_from::types::Task,) -> ::core::result::Result<super::__witforge_to::types::Task, ConversionError> { ::core::result::Result::Ok(super::__witforge_to::types::Task { id: value.id, title: ::core::clone::Clone::clone(&value.title), done: value.done, priority: ::core::option::Option::None, tags: ::std::vec::Vec::new(), })}Full file:
convert.rs.
Polyglot outputs
Section titled “Polyglot outputs”The committed examples/polyglot
project compiles the same example:ingest contract (v0.1 and v0.2, where v0.2 adds
priority: option<u8> to item) into TypeScript, Python, Go, Java 21, and C# 12 plain types,
bidirectional version adapters, and checked protobuf glue in one command:
witforge generate --config examples/polyglot/witforge.toml --checkEvery excerpt below is checked line-for-line against the committed v0.1 output under
examples/polyglot/generated.
TypeScript (ts and ts-glue)
Section titled “TypeScript (ts and ts-glue)”Strict ESM readonly interfaces, string literal unions, discriminated variant unions, and zero
runtime dependencies:
export interface Item { readonly id: bigint; readonly name: string; readonly tags: readonly string[]; readonly note: Option<string>;}
export const Status = { Accepted: "accepted", Rejected: "rejected",} as const;
export type Status = (typeof Status)[keyof typeof Status];
export type Event = | { readonly tag: "started" } | { readonly tag: "item"; readonly value: Item } | { readonly tag: "finished"; readonly value: Status };Full files:
v0_1/types.ts,
convert.ts,
and @bufbuild/protobuf glue
v0/types.ts.
Python 3.11+ (py and py-glue)
Section titled “Python 3.11+ (py and py-glue)”Immutable @dataclass(frozen=True, slots=True) records, StrEnum enums, union variant types,
Protocol interfaces, and a PEP 561 py.typed marker using only the Python standard library:
@dataclass(frozen=True, slots=True)class Item: id: int name: str tags: tuple[str, ...] note: str | None
class Status(StrEnum): ACCEPTED = "accepted" REJECTED = "rejected"
@dataclass(frozen=True, slots=True)class EventStarted: pass
@dataclass(frozen=True, slots=True)class EventItem: value: Item
@dataclass(frozen=True, slots=True)class EventFinished: value: Status
Event: TypeAlias = EventStarted | EventItem | EventFinishedFull files:
v0_1/types.py,
convert.py,
and google.protobuf glue
v0/types.py.
Go 1.22+ (go and go-glue)
Section titled “Go 1.22+ (go and go-glue)”gofmt-formatted Go structs, closed enum constants with Valid() and String() helpers, sealed
variant interfaces, and stdlib-only packages:
type Item struct { Id uint64 Name string Tags []string Note *string}
type Status uint32
const ( StatusAccepted Status = 1 StatusRejected Status = 2)
func (v Status) Valid() bool { switch v { case StatusAccepted, StatusRejected: return true default: return false }}
func (v Status) String() string { switch v { case StatusAccepted: return "accepted" case StatusRejected: return "rejected" default: return "" }}
type Event interface { isEvent()}
type EventStarted struct{}
func (EventStarted) isEvent() {}
type EventItem struct { Value Item}
func (EventItem) isEvent() {}
type EventFinished struct { Value Status}
func (EventFinished) isEvent() {}Full files:
v0_1/types/types.go,
convert/v0_1_to_v0_2/types/convert.go,
and google.golang.org/protobuf glue
v0/types/glue.go.
Java 21+ (java and java-glue)
Section titled “Java 21+ (java and java-glue)”Java 21 record classes with defensive list/optional copies and sealed interface variants with
exhaustive pattern-matching permits clauses:
public record Item( long id, String name, List<String> tags, Optional<String> note) { public Item { Objects.requireNonNull(name, "name"); tags = WitforgeValues.copyList(tags, "tags"); note = WitforgeValues.copyOptional(note, "note"); }}public sealed interface Event permits Event.Started, Event.Item, Event.Finished { record Started() implements Event {}
record Item(com.example.ingest.plain.v0_1.types.Item value) implements Event { public Item { Objects.requireNonNull(value, "value"); } }
record Finished(Status value) implements Event { public Finished { Objects.requireNonNull(value, "value"); } }}Full files:
Item.java,
Event.java,
Convert.java,
and com.google.protobuf glue
TypesGlue.java.
C# 12+ / .NET 8+ (csharp and csharp-glue)
Section titled “C# 12+ / .NET 8+ (csharp and csharp-glue)”Nullable-enabled (#nullable enable) immutable records with defensive copies and structural list
equality, enum wire-name helpers, and closed abstract record variant hierarchies:
public sealed record Item{ private readonly ulong _id; private readonly string _name; private readonly global::System.Collections.Generic.IReadOnlyList<string> _tags; private readonly string? _note;
public Item(ulong id, string name, global::System.Collections.Generic.IReadOnlyList<string> tags, string? note) { _id = id; _name = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(name, "name"); _tags = global::Example.Ingest.Plain.WitforgeValues.CopyNonNullList(tags, "tags"); _note = note; }
public ulong Id { get => _id; init => _id = value; }
public string Name { get => _name; init => _name = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "Name"); }
public global::System.Collections.Generic.IReadOnlyList<string> Tags { get => _tags; init => _tags = global::Example.Ingest.Plain.WitforgeValues.CopyNonNullList(value, "Tags"); }
public string? Note { get => _note; init => _note = value; }
public void Deconstruct(out ulong id, out string name, out global::System.Collections.Generic.IReadOnlyList<string> tags, out string? note) { id = Id; name = Name; tags = Tags; note = Note; }
public bool Equals(Item? other) { if (object.ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } return global::System.Collections.Generic.EqualityComparer<ulong>.Default.Equals(_id, other._id) && global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(_name, other._name) && global::Example.Ingest.Plain.WitforgeValues.ListEquals(_tags, other._tags) && global::System.Collections.Generic.EqualityComparer<string?>.Default.Equals(_note, other._note); }
public override int GetHashCode() { var hash = new global::System.HashCode(); hash.Add(_id); hash.Add(_name); hash.Add(global::Example.Ingest.Plain.WitforgeValues.ListHashCode(_tags)); hash.Add(_note); return hash.ToHashCode(); }
public override string ToString() { return "Item { Id = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_id) + ", Name = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_name) + ", Tags = " + global::Example.Ingest.Plain.WitforgeValues.ListToString(_tags) + ", Note = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_note) + " }"; }}public enum Status{ Accepted = 0, Rejected = 1,}
public static class StatusExtensions{ public static string ToWitName(this global::Example.Ingest.Plain.V0_1.Types.Status value) { return value switch { global::Example.Ingest.Plain.V0_1.Types.Status.Accepted => "accepted", global::Example.Ingest.Plain.V0_1.Types.Status.Rejected => "rejected", _ => throw new global::System.ArgumentOutOfRangeException("value", value, "Unknown Status value."), }; }
public static bool TryParseWitName(string? name, out global::Example.Ingest.Plain.V0_1.Types.Status value) { switch (name) { case "accepted": value = global::Example.Ingest.Plain.V0_1.Types.Status.Accepted; return true; case "rejected": value = global::Example.Ingest.Plain.V0_1.Types.Status.Rejected; return true; default: value = default; return false; } }}
public abstract record Event{ private Event() { }
public sealed record Started : Event { public Started() { } }
public sealed record Item : Event { private readonly global::Example.Ingest.Plain.V0_1.Types.Item _value;
public Item(global::Example.Ingest.Plain.V0_1.Types.Item value) { _value = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "value"); }
public global::Example.Ingest.Plain.V0_1.Types.Item Value { get => _value; init => _value = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "Value"); }
public void Deconstruct(out global::Example.Ingest.Plain.V0_1.Types.Item value) { value = Value; } }
public sealed record Finished : Event { private readonly global::Example.Ingest.Plain.V0_1.Types.Status _value;
public Finished(global::Example.Ingest.Plain.V0_1.Types.Status value) { _value = value; }
public global::Example.Ingest.Plain.V0_1.Types.Status Value { get => _value; init => _value = value; }
public void Deconstruct(out global::Example.Ingest.Plain.V0_1.Types.Status value) { value = Value; } }}Full files:
V0_1/Types.cs,
Convert.cs,
and Google.Protobuf glue
V0/TypesGlue.cs.
To emit deterministic Markdown contract reference pages (index.md and per-version v<major>_<minor>.md)
for your own contract, run witforge doc; to export the deterministic JSON contract IR for tooling,
run witforge inspect --json.