diff --git a/FEATURES.md b/FEATURES.md
new file mode 100644
index 0000000..4e9e17e
--- /dev/null
+++ b/FEATURES.md
@@ -0,0 +1,37 @@
+# Generator features
+
+
+
+What the rust generator implements, and the conformance fixtures that prove it. A claim is checked, not trusted: a supported feature has a fixture that generates and matches its golden, an ignored one generates exactly what it would without the feature, and an unsupported one is refused with an error naming every use.
+
+| Feature | rust ≥ 1.85.0 |
+|---|---|
+| structs `structs` | ✅ supported proven by `primitives`, `optional_and_arrays`, `type_refs` +17 more |
+| enums `enums` | ✅ supported proven by `enum_basic` |
+| optional fields `optional-fields` | ✅ supported proven by `optional_and_arrays`, `type_refs`, `shapes` +4 more |
+| arrays `arrays` | ✅ supported proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more |
+| fixed-length arrays `fixed-arrays` | ✅ supported proven by `shapes` |
+| fixed arrays over 32 elements, nested `large-fixed-arrays-nested` | ❌ unsupported: a fixed array over 32 elements renders only as a struct or error field's own, non-optional type (serde's derive stops at 32) proven by `large_fixed_arrays_nested` |
+| unions `unions` | ❌ unsupported: Rust has no anonymous sum type to render one as proven by `unions` |
+| type aliases `type-aliases` | ✅ supported proven by `validators`, `validators_on_decode`, `bounds` |
+| constants `constants` | ✅ supported proven by `constant`, `shapes`, `validators` +1 more |
+| protocols `protocols` | ✅ supported proven by `protocol`, `error_shapes`, `validators` +15 more |
+| errors `errors` | ✅ supported proven by `protocol`, `error_shapes`, `lockstep` +2 more |
+| functions that throw `throws` | ✅ supported proven by `protocol`, `error_shapes`, `lockstep` +2 more |
+| validators `validators` | ✅ supported proven by `validators`, `validators_on_decode` |
+| imports between schemas `imports` | ✅ supported proven by `cross_schema`, `import_alias`, `import_glob` +6 more |
+| nested namespaces `nested-namespaces` | ✅ supported proven by `nested_namespace`, `external_std`, `validators` +4 more |
+| `lib` mode `lib-mode` | ✅ supported proven by `nested_namespace`, `external_std` |
+| `external_std` `external-std` | ✅ supported proven by `external_std` |
+| `validate_on_decode` `validate-on-decode` | ✅ supported proven by `validators_on_decode` |
+| JSON-RPC framing `framing-jsonrpc` | ✅ supported proven by `framing_jsonrpc`, `connections_jsonrpc` |
+| no handshake `handshake-none` | ✅ supported proven by `handshake_none` |
+| `datagram@3` framing `framing-datagram3` | ✅ supported proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +3 more |
+| `comline@2` handshake `handshake-comline2` | ✅ supported proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +2 more |
+| connections `connections` | ✅ supported proven by `protocol`, `error_shapes`, `validators` +13 more |
+| `async` `async` | ✅ supported proven by `connections_async` |
+| the `packed@1` format `format-packed` | ✅ supported proven by `protocol`, `error_shapes`, `validators` +11 more |
+| the `json@1` format `format-json` | ✅ supported proven by `format_json` |
+| the `msgpack@1` format `format-msgpack` | ✅ supported proven by `format_msgpack` |
+| bounds `bounds` | ✅ supported proven by `bounds` |
+| single characters `chars` | ✅ supported proven by `chars` |
diff --git a/README.md b/README.md
index 49afca8..02bd259 100644
--- a/README.md
+++ b/README.md
@@ -34,12 +34,14 @@ rewrite, not a port.
## Features
What this generator implements, feature by feature. Each claim is checked by
-the conformance suite in [`ComlineProject/generation`](https://github.com/ComlineProject/generation):
+`codegen/tests/conformance.rs`, which runs the conformance corpus of
+[`ComlineProject/generation`](https://github.com/ComlineProject/generation)
+over this generator, against the goldens in `codegen/tests/golden/`:
a supported feature has a fixture that generates and matches its golden output,
an ignored one generates exactly what it would without the feature, and an
unsupported one is refused with an error naming every use. The full matrix,
-with the fixtures that prove each claim, is in
-[`FEATURES.md`](https://github.com/ComlineProject/generation/blob/master/FEATURES.md).
+with the fixtures that prove each claim, is in [`FEATURES.md`](FEATURES.md)
+(also as [`features.json`](features.json)), which that run writes.
diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml
index a0fc43a..7450d1e 100644
--- a/codegen/Cargo.toml
+++ b/codegen/Cargo.toml
@@ -9,7 +9,7 @@ license = "GPL-3.0-only"
# repository structure — no crates.io publishing at this stage). Pinned to the
# same generation rev `comline-typescript` uses, so a CLI build has one
# `comline-codegen`. Local iteration: add a `[patch]` onto a sibling checkout.
-comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "e900919375429591d73c906380f1d354d636ab22" }
+comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "31e808ff05632acbfa4f48d208b8d5a2fbca3b0e" }
comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922", default-features = false }
eyre = "0.6.8"
@@ -21,9 +21,10 @@ name = "comline-gen-rust"
path = "src/bin/comline-gen-rust.rs"
[dev-dependencies]
-# The conformance corpus: every fixture is a whole package. Same generation
-# rev as `comline-codegen` above, so the corpus and the generator share one
-# `comline-codegen`.
-comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "e900919375429591d73c906380f1d354d636ab22" }
+# The conformance corpus and the harness that runs this generator over it
+# (`tests/conformance.rs`, against `tests/golden/`): every fixture is a whole
+# package. Same generation rev as `comline-codegen` above, so the corpus and
+# the generator share one `comline-codegen`.
+comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "31e808ff05632acbfa4f48d208b8d5a2fbca3b0e" }
# The tests compile schemas, so they need core's compiler.
comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922" }
diff --git a/codegen/tests/conformance.rs b/codegen/tests/conformance.rs
new file mode 100644
index 0000000..bd36bd9
--- /dev/null
+++ b/codegen/tests/conformance.rs
@@ -0,0 +1,46 @@
+//! The conformance corpus (`comline-conformance`, in ComlineProject/generation)
+//! run over this generator: its output for every fixture, at each of its
+//! version boundaries, against the goldens under `tests/golden/`; the
+//! generator protocol round trip; and the proof of every claim in `SUPPORT`,
+//! with the report `FEATURES.md` and `features.json` at the repository root.
+//! Regenerate the goldens and the report with:
+//!
+//! ```text
+//! CONFORMANCE_BLESS=1 cargo test -p comline-codegen-rust --test conformance
+//! ```
+//!
+//! A blessed golden is a snapshot of what the generator does now: a diff in
+//! one is a change to what it emits, to be read as one.
+
+use std::path::Path;
+
+use comline_conformance::harness::{self, Generator};
+
+const GENERATOR: Generator = Generator {
+ language: "rust",
+ generate: comline_codegen_rust::generate_rust,
+ register: comline_codegen_rust::register,
+ support: comline_codegen_rust::SUPPORT,
+ versions: comline_codegen_rust::VERSIONS,
+};
+
+#[test]
+fn the_protocol_generates_what_the_generator_does() {
+ harness::the_protocol_generates_what_the_generator_does(&GENERATOR);
+}
+
+#[test]
+fn corpus_matches_golden() {
+ harness::corpus_matches_golden(
+ &GENERATOR,
+ &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"),
+ );
+}
+
+#[test]
+fn support_is_proven() {
+ harness::support_is_proven(
+ &GENERATOR,
+ &Path::new(env!("CARGO_MANIFEST_DIR")).join(".."),
+ );
+}
diff --git a/codegen/tests/golden/bounds/rust/conformance.rs b/codegen/tests/golden/bounds/rust/conformance.rs
new file mode 100644
index 0000000..6360569
--- /dev/null
+++ b/codegen/tests/golden/bounds/rust/conformance.rs
@@ -0,0 +1,188 @@
+// This file uses `comline_runtime` - add it to your Cargo.toml:
+// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51" }
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+
+pub type Name = String;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Customer {
+ #[serde(
+ deserialize_with = "comline_runtime::bounds::decode::string::<_, 32>",
+ serialize_with = "comline_runtime::bounds::encode::string::<_, 32>"
+ )]
+ pub name: Name,
+ #[serde(with = "__comline_bounds::chars_2")]
+ pub country: String,
+ #[serde(default)]
+ #[serde(with = "__comline_bounds::option_of_chars_max_254")]
+ pub email: Option,
+ #[serde(with = "__comline_bounds::items_max_8_of_chars_max_16")]
+ pub tags: Vec,
+ #[serde(
+ deserialize_with = "comline_runtime::bounds::decode::vec::<_, _, 10>",
+ serialize_with = "comline_runtime::bounds::encode::vec::<_, _, 10>"
+ )]
+ pub scores: Vec,
+}
+
+#[derive(Debug, Clone)]
+pub struct Node {
+ pub label: String,
+ pub children: Vec,
+}
+
+/// [`Node`]'s fields as serde reads and writes them; its own impls
+/// count how deep it nests, at most 16 levels (`@max_depth`).
+#[doc(hidden)]
+#[allow(dead_code, non_camel_case_types)]
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "Node")]
+struct __NodeDepth {
+ #[serde(
+ deserialize_with = "comline_runtime::bounds::decode::string::<_, 64>",
+ serialize_with = "comline_runtime::bounds::encode::string::<_, 64>"
+ )]
+ pub label: String,
+ #[serde(
+ deserialize_with = "comline_runtime::bounds::decode::vec::<_, _, 4>",
+ serialize_with = "comline_runtime::bounds::encode::vec::<_, _, 4>"
+ )]
+ pub children: Vec,
+}
+
+impl __NodeDepth {
+ fn depth(f: impl FnOnce(&mut comline_runtime::bounds::Depth) -> R) -> R {
+ ::std::thread_local! {
+ static DEPTH: ::core::cell::Cell =
+ const { ::core::cell::Cell::new(comline_runtime::bounds::Depth::new(16)) };
+ }
+ DEPTH.with(|cell| {
+ let mut depth = cell.get();
+ let r = f(&mut depth);
+ cell.set(depth);
+ r
+ })
+ }
+}
+
+impl Serialize for Node {
+ fn serialize(&self, s: S) -> Result {
+ __NodeDepth::depth(|d| d.enter()).map_err(comline_runtime::bounds::ser_error)?;
+ let r = __NodeDepth::serialize(self, s);
+ __NodeDepth::depth(|d| d.leave());
+ r
+ }
+}
+
+impl<'de> Deserialize<'de> for Node {
+ fn deserialize>(d: D) -> Result {
+ __NodeDepth::depth(|d| d.enter()).map_err(comline_runtime::bounds::de_error)?;
+ let r = __NodeDepth::deserialize(d);
+ __NodeDepth::depth(|d| d.leave());
+ r
+ }
+}
+
+/// How this file's bounded values decode and encode (core#98): each
+/// module is a `#[serde(with)]` for one shape of bounds.
+#[doc(hidden)]
+#[allow(dead_code, unused_imports)]
+mod __comline_bounds {
+ /// A string of exactly `.0` characters: more is refused before
+ /// it's allocated, as a maximum is.
+ #[derive(Clone, Copy)]
+ pub struct Exact(pub u32);
+
+ impl<'de> serde::de::DeserializeSeed<'de> for Exact {
+ type Value = String;
+
+ fn deserialize>(self, d: D) -> Result {
+ let s: String = serde::de::DeserializeSeed::deserialize(comline_runtime::bounds::CharsSeed::::new(self.0), d)?;
+ if s.chars().count() != self.0 as usize {
+ return Err(serde::de::Error::custom(::core::format_args!("a string of exactly {} characters", self.0)));
+ }
+ Ok(s)
+ }
+ }
+
+ /// An optional value, decoded through the seed `.0` when present.
+ #[derive(Clone, Copy)]
+ pub struct Opt(pub S);
+
+ impl<'de, S: serde::de::DeserializeSeed<'de>> serde::de::DeserializeSeed<'de> for Opt {
+ type Value = Option;
+
+ fn deserialize>(self, d: D) -> Result {
+ d.deserialize_option(self)
+ }
+ }
+
+ impl<'de, S: serde::de::DeserializeSeed<'de>> serde::de::Visitor<'de> for Opt {
+ type Value = Option;
+
+ fn expecting(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
+ f.write_str("an optional value")
+ }
+
+ fn visit_none(self) -> Result {
+ Ok(None)
+ }
+
+ fn visit_unit(self) -> Result {
+ Ok(None)
+ }
+
+ fn visit_some>(self, d: D) -> Result {
+ self.0.deserialize(d).map(Some)
+ }
+ }
+
+ pub mod chars_2 {
+ use super::*;
+
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result {
+ serde::de::DeserializeSeed::deserialize(Exact(2), d)
+ }
+
+ pub fn serialize(value: &String, s: S) -> Result {
+ if value.chars().count() != 2 {
+ return Err(serde::ser::Error::custom("a string of exactly 2 characters"));
+ }
+ serde::Serialize::serialize(value, s)
+ }
+ }
+
+ pub mod items_max_8_of_chars_max_16 {
+ use super::*;
+
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> {
+ serde::de::DeserializeSeed::deserialize(comline_runtime::bounds::ItemsSeed::<_, Vec>::new(comline_runtime::bounds::CharsSeed::::new(16), 8), d)
+ }
+
+ pub fn serialize(value: &Vec, s: S) -> Result {
+ comline_runtime::bounds::check_items(value.len(), 8).map_err(comline_runtime::bounds::ser_error)?;
+ for item12 in value.iter() {
+ comline_runtime::bounds::check_chars(item12, 16).map_err(comline_runtime::bounds::ser_error)?;
+ }
+ serde::Serialize::serialize(value, s)
+ }
+ }
+
+ pub mod option_of_chars_max_254 {
+ use super::*;
+
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> {
+ serde::de::DeserializeSeed::deserialize(Opt(comline_runtime::bounds::CharsSeed::::new(254)), d)
+ }
+
+ pub fn serialize(value: &Option, s: S) -> Result {
+ if let Some(inner12) = value {
+ comline_runtime::bounds::check_chars(inner12, 254).map_err(comline_runtime::bounds::ser_error)?;
+ }
+ serde::Serialize::serialize(value, s)
+ }
+ }
+}
+
diff --git a/codegen/tests/golden/chars/rust/conformance.rs b/codegen/tests/golden/chars/rust/conformance.rs
new file mode 100644
index 0000000..346a355
--- /dev/null
+++ b/codegen/tests/golden/chars/rust/conformance.rs
@@ -0,0 +1,9 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Grade {
+ pub letter: char,
+}
+
diff --git a/codegen/tests/golden/connections/rust/conformance.rs b/codegen/tests/golden/connections/rust/conformance.rs
new file mode 100644
index 0000000..b5e3fc2
--- /dev/null
+++ b/codegen/tests/golden/connections/rust/conformance.rs
@@ -0,0 +1,250 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+use comline_runtime::connection::Connection;
+use comline_runtime::contract::{
+ Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat,
+};
+use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber};
+use comline_runtime::transport::Transport;
+
+/// Canonical digest of the frozen IR this file was generated from — the
+/// two ends of a connection must agree on it, and the handshake checks.
+pub const IR_HASH: u64 = 0xb97e34b203ec1425;
+
+#[doc(hidden)]
+pub use crate::connection::{CONNECTION_IR_HASH, Format};
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatSendParams {
+ pub n: u32,
+}
+
+pub type ChatSendError = ::core::convert::Infallible;
+
+pub type ChatError = ::core::convert::Infallible;
+
+pub trait Chat {
+ fn send(&self, peer: &mut impl Peer, n: u32) -> Result>;
+}
+
+#[doc(hidden)]
+pub const CHAT_CALLS: &[&str] = &["send"];
+
+#[doc(hidden)]
+pub struct ChatDispatcher(pub S);
+
+impl Dispatch for ChatDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ CHAT_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: ChatSendParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.send(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl ChatDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Chat` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct ChatSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> ChatSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn send(&mut self, n: u32) -> Result> {
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EventsShownParams {
+ pub n: u32,
+}
+
+pub type EventsShownError = ::core::convert::Infallible;
+
+pub type EventsError = ::core::convert::Infallible;
+
+pub trait Events {
+ fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>;
+ fn ping(&self, peer: &mut impl Peer);
+}
+
+#[doc(hidden)]
+pub const EVENTS_CALLS: &[&str] = &["shown", "ping"];
+
+#[doc(hidden)]
+pub struct EventsDispatcher(pub S);
+
+impl Dispatch for EventsDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ EVENTS_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: EventsShownParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.shown(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ 1 => {
+ let _: () = match peer.format().decode(params) {
+ Ok(unit) => unit,
+ Err(_) => return Ok(()),
+ };
+ self.0.ping(peer);
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl EventsDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `Connection::connect(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Events` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct EventsSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> EventsSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn shown(&mut self, n: u32) -> Result> {
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "shown"), &EventsShownParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+
+ pub fn ping(&mut self) -> Result<(), RuntimeError> {
+ self.0.notify(Self::PROTOCOL, Call::new(1, "ping"), &())
+ }
+}
+
diff --git a/codegen/tests/golden/connections/rust/connection.rs b/codegen/tests/golden/connections/rust/connection.rs
new file mode 100644
index 0000000..071340b
--- /dev/null
+++ b/codegen/tests/golden/connections/rust/connection.rs
@@ -0,0 +1,76 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it:
+//!
+//! - Implement the trait of each protocol the server provides: `conformance::Chat`.
+//! - Implement the trait of each protocol the client provides: `conformance::Events`.
+//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time.
+//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`.
+//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`.
+//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`.
+//!
+//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format.
+
+use comline_runtime::contract::RuntimeError;
+use comline_runtime::transport::Transport;
+
+/// The package's wire format (`wire.format`).
+pub type Format = comline_runtime::format::Packed;
+
+/// Digest of every schema in the package — what a connection's handshake
+/// checks, so both ends agree on each protocol's number.
+pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425;
+
+/// The package's connection over the transport `T`: what [`accept`] and [`connect`]
+/// return, written `Connection`: [`Format`] over the default framing.
+pub type Connection = comline_runtime::connection::Connection;
+
+/// What the accepting side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct Services {
+ pub chat: Chat,
+}
+
+impl Services {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::ChatDispatcher(self.chat).provide_on(conn);
+ }
+}
+
+/// What the dialling side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct ClientServices {
+ pub events: Events,
+}
+
+impl ClientServices {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::EventsDispatcher(self.events).provide_on(conn);
+ }
+}
+
+/// Accept a connection over `transport`: run the handshake, then provide
+/// every protocol in `services` on it. The connection comes back not yet
+/// served, for a server that calls the client first, or serves one call at
+/// a time.
+pub fn accept(transport: T, services: Services) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
+
+/// [`accept`], then serve every call until the peer leaves.
+pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> {
+ accept(transport, services)?.serve()
+}
+
+/// Dial over `transport`: run the handshake, then provide every protocol in
+/// `services`, which the server calls. Call the server's protocols through
+/// their senders.
+pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
diff --git a/codegen/tests/golden/connections_async/rust/conformance.rs b/codegen/tests/golden/connections_async/rust/conformance.rs
new file mode 100644
index 0000000..11b4f9b
--- /dev/null
+++ b/codegen/tests/golden/connections_async/rust/conformance.rs
@@ -0,0 +1,216 @@
+// This file uses `comline_runtime`'s async driver - enable its feature in your Cargo.toml:
+// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51", features = ["async"] }
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+use comline_runtime::connection::{Answer, AsyncConnection, AsyncDispatch, AsyncPeer};
+use comline_runtime::transport::AsyncTransport;
+use comline_runtime::contract::{Call, CallError, Envelope, Fault, Kind, RuntimeError, WireFormat};
+use comline_runtime::contract::{ConnectionFraming, ProtocolNumber};
+
+/// Canonical digest of the frozen IR this file was generated from — the
+/// two ends of a connection must agree on it, and the handshake checks.
+pub const IR_HASH: u64 = 0xb97e34b203ec1425;
+
+#[doc(hidden)]
+pub use crate::connection::{CONNECTION_IR_HASH, Format};
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatSendParams {
+ pub n: u32,
+}
+
+pub type ChatSendError = ::core::convert::Infallible;
+
+pub type ChatError = ::core::convert::Infallible;
+
+pub trait Chat: Send + Sync + 'static {
+ fn send(&self, peer: &impl AsyncPeer, n: u32) -> impl ::core::future::Future>> + Send;
+}
+
+#[doc(hidden)]
+pub const CHAT_CALLS: &[&str] = &["send"];
+
+#[doc(hidden)]
+pub struct ChatAsyncDispatcher(pub S);
+
+impl AsyncDispatch for ChatAsyncDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ CHAT_CALLS
+ }
+
+ async fn dispatch<'a, P: AsyncPeer>(
+ &'a self,
+ call: Kind,
+ params: &'a [u8],
+ peer: &'a P,
+ ) -> Result {
+ match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: ChatSendParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => return Ok(Answer::fault()),
+ };
+ match self.0.send(peer, p.n).await {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ Ok(Answer::ok(body))
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => Ok(Answer::fault()),
+ }
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl ChatAsyncDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `AsyncConnection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(self, conn: &mut AsyncConnection)
+ where
+ T: AsyncTransport,
+ W: WireFormat + Send + Sync + 'static,
+ F: ConnectionFraming + Send + Sync + 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Chat` on the other end of a connection: the peer an
+/// `AsyncConnection`'s handle reaches, or the one a handler was given.
+pub struct ChatAsyncSender<'p, P: AsyncPeer>(pub &'p P);
+
+impl<'p, P: AsyncPeer> ChatAsyncSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ pub fn new(peer: &'p P) -> Self {
+ Self(peer)
+ }
+
+ pub async fn send(&self, n: u32) -> Result> {
+ let reply = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n }).await?;
+ let fmt = self.0.format();
+ match reply.envelope() {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EventsShownParams {
+ pub n: u32,
+}
+
+pub type EventsShownError = ::core::convert::Infallible;
+
+pub type EventsError = ::core::convert::Infallible;
+
+pub trait Events: Send + Sync + 'static {
+ fn shown(&self, peer: &impl AsyncPeer, n: u32) -> impl ::core::future::Future>> + Send;
+ fn ping(&self, peer: &impl AsyncPeer) -> impl ::core::future::Future + Send;
+}
+
+#[doc(hidden)]
+pub const EVENTS_CALLS: &[&str] = &["shown", "ping"];
+
+#[doc(hidden)]
+pub struct EventsAsyncDispatcher(pub S);
+
+impl AsyncDispatch for EventsAsyncDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ EVENTS_CALLS
+ }
+
+ async fn dispatch<'a, P: AsyncPeer>(
+ &'a self,
+ call: Kind,
+ params: &'a [u8],
+ peer: &'a P,
+ ) -> Result {
+ match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: EventsShownParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => return Ok(Answer::fault()),
+ };
+ match self.0.shown(peer, p.n).await {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ Ok(Answer::ok(body))
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => Ok(Answer::fault()),
+ }
+ }
+ 1 => {
+ let _: () = match peer.format().decode(params) {
+ Ok(unit) => unit,
+ Err(_) => return Ok(Answer::none()),
+ };
+ self.0.ping(peer).await;
+ Ok(Answer::none())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl EventsAsyncDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `AsyncConnection::connect(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(self, conn: &mut AsyncConnection)
+ where
+ T: AsyncTransport,
+ W: WireFormat + Send + Sync + 'static,
+ F: ConnectionFraming + Send + Sync + 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Events` on the other end of a connection: the peer an
+/// `AsyncConnection`'s handle reaches, or the one a handler was given.
+pub struct EventsAsyncSender<'p, P: AsyncPeer>(pub &'p P);
+
+impl<'p, P: AsyncPeer> EventsAsyncSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ pub fn new(peer: &'p P) -> Self {
+ Self(peer)
+ }
+
+ pub async fn shown(&self, n: u32) -> Result> {
+ let reply = self.0.call(Self::PROTOCOL, Call::new(0, "shown"), &EventsShownParams { n }).await?;
+ let fmt = self.0.format();
+ match reply.envelope() {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+
+ pub fn ping(&self) -> Result<(), RuntimeError> {
+ self.0.notify(Self::PROTOCOL, Call::new(1, "ping"), &())
+ }
+}
+
diff --git a/codegen/tests/golden/connections_async/rust/connection.rs b/codegen/tests/golden/connections_async/rust/connection.rs
new file mode 100644
index 0000000..f130cbd
--- /dev/null
+++ b/codegen/tests/golden/connections_async/rust/connection.rs
@@ -0,0 +1,76 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it:
+//!
+//! - Implement the trait of each protocol the server provides: `conformance::Chat`.
+//! - Implement the trait of each protocol the client provides: `conformance::Events`.
+//! - Serve with [`serve`]`(transport, Services { chat: .. }).await`, which runs until the peer leaves. [`accept`] hands the connection back first, not yet running: take its `handle()` to call the client, then `run().await` it.
+//! - Dial with [`connect`]`(transport, ClientServices { events: .. }).await`, then `run().await` the connection it returns.
+//! - Call the server from the dialling side: `ChatAsyncSender::new(&conn.handle()).send(..).await`.
+//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsAsyncSender::new(&conn.handle()).shown(..).await`.
+//!
+//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format.
+
+use comline_runtime::contract::RuntimeError;
+use comline_runtime::transport::AsyncTransport;
+
+/// The package's wire format (`wire.format`).
+pub type Format = comline_runtime::format::Packed;
+
+/// Digest of every schema in the package — what a connection's handshake
+/// checks, so both ends agree on each protocol's number.
+pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425;
+
+/// The package's connection over the transport `T`: what [`accept`] and [`connect`]
+/// return, written `Connection`: [`Format`] over the default framing.
+pub type Connection = comline_runtime::connection::AsyncConnection;
+
+/// What the accepting side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct Services {
+ pub chat: Chat,
+}
+
+impl Services {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::ChatAsyncDispatcher(self.chat).provide_on(conn);
+ }
+}
+
+/// What the dialling side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct ClientServices {
+ pub events: Events,
+}
+
+impl ClientServices {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::EventsAsyncDispatcher(self.events).provide_on(conn);
+ }
+}
+
+/// Accept a connection over `transport`: run the handshake, then provide
+/// every protocol in `services` on it. The connection comes back not yet
+/// running, so the caller can take a `handle()` to call the client with
+/// before it runs.
+pub async fn accept(transport: T, services: Services) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::AsyncConnection::accept(transport, Format::default(), CONNECTION_IR_HASH).await?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
+
+/// [`accept`], then serve every call until the peer leaves.
+pub async fn serve(transport: T, services: Services) -> Result<(), RuntimeError> {
+ accept(transport, services).await?.run().await
+}
+
+/// Dial over `transport`: run the handshake, then provide every protocol in
+/// `services`, which the server calls. Call the server's protocols through
+/// their senders.
+pub async fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::AsyncConnection::connect(transport, Format::default(), CONNECTION_IR_HASH).await?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
diff --git a/codegen/tests/golden/connections_default/rust/conformance.rs b/codegen/tests/golden/connections_default/rust/conformance.rs
new file mode 100644
index 0000000..a6aa6f7
--- /dev/null
+++ b/codegen/tests/golden/connections_default/rust/conformance.rs
@@ -0,0 +1,261 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+use comline_runtime::connection::Connection;
+use comline_runtime::contract::{
+ Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat,
+};
+use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber};
+use comline_runtime::transport::Transport;
+
+/// Canonical digest of the frozen IR this file was generated from — the
+/// two ends of a connection must agree on it, and the handshake checks.
+pub const IR_HASH: u64 = 0x1ad273c98d4e98fb;
+
+#[doc(hidden)]
+pub use crate::connection::{CONNECTION_IR_HASH, Format};
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatSendParams {
+ pub n: u32,
+}
+
+pub type ChatSendError = ::core::convert::Infallible;
+
+pub type ChatError = ::core::convert::Infallible;
+
+pub trait Chat {
+ fn send(&self, peer: &mut impl Peer, n: u32) -> Result>;
+}
+
+#[doc(hidden)]
+pub const CHAT_CALLS: &[&str] = &["send"];
+
+#[doc(hidden)]
+pub struct ChatDispatcher(pub S);
+
+impl Dispatch for ChatDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ CHAT_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ let number = match call {
+ Kind::Id(number) => number,
+ Kind::Named(_) => return Err(RuntimeError::UnknownCall),
+ };
+ match number {
+ 0 => {
+ let p: ChatSendParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.send(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl ChatDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Chat` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct ChatSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> ChatSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn send(&mut self, n: u32) -> Result> {
+ crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Chat", "send")?;
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EventsShownParams {
+ pub n: u32,
+}
+
+pub type EventsShownError = ::core::convert::Infallible;
+
+pub type EventsError = ::core::convert::Infallible;
+
+pub trait Events {
+ fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>;
+ fn ping(&self, peer: &mut impl Peer);
+}
+
+#[doc(hidden)]
+pub const EVENTS_CALLS: &[&str] = &["shown", "ping"];
+
+#[doc(hidden)]
+pub struct EventsDispatcher(pub S);
+
+impl Dispatch for EventsDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ EVENTS_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ let number = match call {
+ Kind::Id(number) => number,
+ Kind::Named(_) => return Err(RuntimeError::UnknownCall),
+ };
+ match number {
+ 1 => {
+ let p: EventsShownParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.shown(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ 0 => {
+ let _: () = match peer.format().decode(params) {
+ Ok(unit) => unit,
+ Err(_) => return Ok(()),
+ };
+ self.0.ping(peer);
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl EventsDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Events` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct EventsSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> EventsSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn shown(&mut self, n: u32) -> Result> {
+ crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::Events", "shown")?;
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "shown"), &EventsShownParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+
+ pub fn ping(&mut self) -> Result<(), RuntimeError> {
+ crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Events", "ping")?;
+ self.0.notify(Self::PROTOCOL, Call::new(0, "ping"), &())
+ }
+}
+
diff --git a/codegen/tests/golden/connections_default/rust/connection.rs b/codegen/tests/golden/connections_default/rust/connection.rs
new file mode 100644
index 0000000..0550366
--- /dev/null
+++ b/codegen/tests/golden/connections_default/rust/connection.rs
@@ -0,0 +1,209 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it:
+//!
+//! - Implement the trait of each protocol the server provides: `conformance::Chat`.
+//! - Implement the trait of each protocol the client provides: `conformance::Events`.
+//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time.
+//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`.
+//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`.
+//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`.
+//!
+//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format.
+
+use comline_runtime::contract::{Peer, Reason, RuntimeError};
+use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated};
+use comline_runtime::transport::Transport;
+
+/// The package's wire format (`wire.format`).
+pub type Format = comline_runtime::format::Packed;
+
+/// Digest of every schema in the package — what a connection's handshake
+/// checks, so both ends agree on each protocol's number.
+pub const CONNECTION_IR_HASH: u64 = 0x1ad273c98d4e98fb;
+
+/// The framing the package's connection runs on (`datagram@3`).
+pub type Framing = comline_runtime::contract::Datagram3Framing;
+
+/// The package's connection over the transport `T`: what [`accept`] and [`connect`]
+/// return, written `Connection`: [`Format`] over [`Framing`].
+pub type Connection = comline_runtime::connection::Connection;
+
+/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its
+/// history records it. Its protocols, by wire number:
+///
+/// - 0 `conformance::Chat`, line 0.1.0: `send` 0
+/// - 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0
+#[doc(hidden)]
+pub const HELLO: &[u8] = &[
+ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd,
+ 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00,
+ 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02,
+ 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c,
+ 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2,
+ 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1,
+ 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x02, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a,
+ 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,
+ 0x5a, 0x5a, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a,
+ 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,
+ 0x02, 0x00, 0x01,
+];
+
+/// The `comline@2` handshake, with [`HELLO`] and the parameters the package
+/// states: `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`.
+#[doc(hidden)]
+pub fn handshake() -> Comline2Handshake {
+ use comline_runtime::handshake::comline2 as c2;
+ let hello = match c2::Message::decode(HELLO) {
+ Ok(c2::Message::Hello(hello)) => hello,
+ _ => unreachable!("HELLO is a Hello message"),
+ };
+ let params = c2::Params {
+ scope: c2::Scope::Protocol,
+ newer_consumer: c2::NewerConsumer::Degrade,
+ same_version_differs: c2::SameVersionDiffers::Refuse,
+ exchange: c2::Exchange::Offer,
+ };
+ c2::Comline2Handshake::new(params, hello)
+}
+
+/// The package's protocols on the connection, by wire number.
+const PROTOCOLS: &[(u16, &str)] = &[(0, "conformance::Chat"), (1, "conformance::Events")];
+
+fn protocol_path(number: u16) -> &'static str {
+ PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path)
+}
+
+/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in
+/// the connection's extensions.
+#[derive(Debug, Clone)]
+pub struct Negotiation {
+ pub negotiated: Negotiated,
+ /// The last call that wasn't made because the peer can't take it.
+ pub unavailable: Option,
+}
+
+/// A call that wasn't sent because the peer can't take it: which, and why.
+/// The call itself fails with `RuntimeError::Unavailable`, which carries no
+/// detail; [`unavailable`] gives this.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Unavailable {
+ /// `namespace::Protocol`.
+ pub protocol: &'static str,
+ pub function: &'static str,
+ /// Why the peer refused the protocol, or `None` when the peer lacks the
+ /// function (`newer_consumer = degrade`).
+ pub refused: Option,
+}
+
+impl ::core::fmt::Display for Unavailable {
+ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
+ match self.refused {
+ Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol),
+ None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function),
+ }
+ }
+}
+
+impl ::core::error::Error for Unavailable {}
+
+/// What the connection's `comline@2` handshake agreed, if `accept` / `connect`
+/// opened it.
+pub fn negotiated(peer: &mut P) -> Option {
+ let extensions = peer.extensions();
+ extensions.get::().map(|n| n.negotiated.clone())
+}
+
+/// The protocols that connected although their wire shape differs from the
+/// peer's at the same version (`same_version_differs = warn`), by path.
+pub fn warnings(peer: &mut P) -> Vec<&'static str> {
+ let extensions = peer.extensions();
+ match extensions.get::() {
+ Some(n) => n.negotiated.warnings.iter().map(|p| protocol_path(*p)).collect(),
+ None => Vec::new(),
+ }
+}
+
+/// The last call on this connection that failed with `Unavailable`: which
+/// function, and why.
+pub fn unavailable(peer: &mut P) -> Option {
+ let extensions = peer.extensions();
+ extensions.get::().and_then(|n| n.unavailable)
+}
+
+/// Whether `function` of `protocol` may be called: what each sender runs
+/// before it writes a request. A connection opened some other way than
+/// `accept` / `connect` has nothing to check against, and every call goes.
+#[doc(hidden)]
+pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'static str, name: &'static str) -> Result<(), RuntimeError> {
+ let extensions = peer.extensions();
+ let Some(n) = extensions.get_mut::() else {
+ return Ok(());
+ };
+ let error = match n.negotiated.check_call(protocol, function) {
+ Ok(()) => return Ok(()),
+ Err(error) => error,
+ };
+ let refused = n.negotiated.protocols.iter().find(|p| p.number == protocol).and_then(|p| match p.state {
+ comline_runtime::handshake::comline2::ProtocolState::Refused { reason } => Some(reason),
+ _ => None,
+ });
+ // A protocol this end doesn't have isn't refused by the peer: it's unknown.
+ let refused = refused.or_else(|| (!n.negotiated.protocols.iter().any(|p| p.number == protocol)).then_some(Reason::UnknownProtocol));
+ n.unavailable = Some(Unavailable { protocol: path, function: name, refused });
+ Err(error)
+}
+
+/// What the accepting side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct Services {
+ pub chat: Chat,
+}
+
+impl Services {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::ChatDispatcher(self.chat).provide_on(conn);
+ }
+}
+
+/// What the dialling side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct ClientServices {
+ pub events: Events,
+}
+
+impl ClientServices {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::EventsDispatcher(self.events).provide_on(conn);
+ }
+}
+
+/// Accept a connection over `transport`: run the handshake, then provide
+/// every protocol in `services` on it. The connection comes back not yet
+/// served, for a server that calls the client first, or serves one call at
+/// a time.
+pub fn accept(transport: T, services: Services) -> Result, RuntimeError> {
+ let mut handshake = handshake();
+ let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?;
+ Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None });
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
+
+/// [`accept`], then serve every call until the peer leaves.
+pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> {
+ accept(transport, services)?.serve()
+}
+
+/// Dial over `transport`: run the handshake, then provide every protocol in
+/// `services`, which the server calls. Call the server's protocols through
+/// their senders.
+pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> {
+ let mut handshake = handshake();
+ let mut conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?;
+ Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None });
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
diff --git a/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs b/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs
new file mode 100644
index 0000000..a9f2e75
--- /dev/null
+++ b/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs
@@ -0,0 +1,250 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+use comline_runtime::connection::Connection;
+use comline_runtime::contract::{
+ Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat,
+};
+use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber};
+use comline_runtime::transport::Transport;
+
+/// Canonical digest of the frozen IR this file was generated from — the
+/// two ends of a connection must agree on it, and the handshake checks.
+pub const IR_HASH: u64 = 0x30c29bde2ae397d9;
+
+#[doc(hidden)]
+pub use crate::connection::CONNECTION_IR_HASH;
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatSendParams {
+ pub n: u32,
+}
+
+pub type ChatSendError = ::core::convert::Infallible;
+
+pub type ChatError = ::core::convert::Infallible;
+
+pub trait Chat {
+ fn send(&self, peer: &mut impl Peer, n: u32) -> Result>;
+}
+
+#[doc(hidden)]
+pub const CHAT_CALLS: &[&str] = &["send"];
+
+#[doc(hidden)]
+pub struct ChatDispatcher(pub S);
+
+impl Dispatch for ChatDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ CHAT_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: ChatSendParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.send(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl ChatDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `Connection::accept_with(transport, format, comline_runtime::framing::JsonRpcFraming, &mut ComlineHandshake, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Chat` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct ChatSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> ChatSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn send(&mut self, n: u32) -> Result> {
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EventsShownParams {
+ pub n: u32,
+}
+
+pub type EventsShownError = ::core::convert::Infallible;
+
+pub type EventsError = ::core::convert::Infallible;
+
+pub trait Events {
+ fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>;
+ fn ping(&self, peer: &mut impl Peer);
+}
+
+#[doc(hidden)]
+pub const EVENTS_CALLS: &[&str] = &["conformance.Events/shown", "conformance.Events/ping"];
+
+#[doc(hidden)]
+pub struct EventsDispatcher(pub S);
+
+impl Dispatch for EventsDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ EVENTS_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? {
+ 0 => {
+ let p: EventsShownParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.shown(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ 1 => {
+ let _: () = match peer.format().decode(params) {
+ Ok(unit) => unit,
+ Err(_) => return Ok(()),
+ };
+ self.0.ping(peer);
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl EventsDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with `Connection::connect_with(transport, format, comline_runtime::framing::JsonRpcFraming, &mut ComlineHandshake, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Events` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct EventsSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> EventsSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 1;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn shown(&mut self, n: u32) -> Result> {
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "conformance.Events/shown"), &EventsShownParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+
+ pub fn ping(&mut self) -> Result<(), RuntimeError> {
+ self.0.notify(Self::PROTOCOL, Call::new(1, "conformance.Events/ping"), &())
+ }
+}
+
diff --git a/codegen/tests/golden/connections_jsonrpc/rust/connection.rs b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs
new file mode 100644
index 0000000..3c96bb7
--- /dev/null
+++ b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs
@@ -0,0 +1,79 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+//! The package's protocols share one connection: `jsonrpc` framing, the `comline@1` handshake. To use it:
+//!
+//! - Implement the trait of each protocol the server provides: `conformance::Chat`.
+//! - Implement the trait of each protocol the client provides: `conformance::Events`.
+//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time.
+//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`.
+//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`.
+//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`.
+//!
+//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format.
+
+use comline_runtime::contract::RuntimeError;
+use comline_runtime::transport::Transport;
+
+/// The package's wire format (`wire.format`).
+pub type Format = comline_runtime::format::Packed;
+
+/// Digest of every schema in the package — what a connection's handshake
+/// checks, so both ends agree on each protocol's number.
+pub const CONNECTION_IR_HASH: u64 = 0x30c29bde2ae397d9;
+
+/// The framing the package's connection runs on (`jsonrpc`).
+pub type Framing = comline_runtime::framing::JsonRpcFraming;
+
+/// The package's connection over the transport `T`: what [`accept`] and [`connect`]
+/// return, written `Connection`: JSON over [`Framing`].
+pub type Connection = comline_runtime::connection::Connection;
+
+/// What the accepting side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct Services {
+ pub chat: Chat,
+}
+
+impl Services {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::ChatDispatcher(self.chat).provide_on(conn);
+ }
+}
+
+/// What the dialling side provides: one field per protocol, so leaving one out
+/// doesn't compile.
+pub struct ClientServices {
+ pub events: Events,
+}
+
+impl ClientServices {
+ /// Provide every protocol on `conn`: the peer's calls to them come here.
+ pub fn provide_on(self, conn: &mut Connection) {
+ crate::conformance::EventsDispatcher(self.events).provide_on(conn);
+ }
+}
+
+/// Accept a connection over `transport`: run the handshake, then provide
+/// every protocol in `services` on it. The connection comes back not yet
+/// served, for a server that calls the client first, or serves one call at
+/// a time.
+pub fn accept(transport: T, services: Services) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::Connection::accept_with(transport, comline_runtime::format::Json::default(), comline_runtime::framing::JsonRpcFraming, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
+
+/// [`accept`], then serve every call until the peer leaves.
+pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> {
+ accept(transport, services)?.serve()
+}
+
+/// Dial over `transport`: run the handshake, then provide every protocol in
+/// `services`, which the server calls. Call the server's protocols through
+/// their senders.
+pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> {
+ let mut conn = comline_runtime::connection::Connection::connect_with(transport, comline_runtime::format::Json::default(), comline_runtime::framing::JsonRpcFraming, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?;
+ services.provide_on(&mut conn);
+ Ok(conn)
+}
diff --git a/codegen/tests/golden/constant/rust/conformance.rs b/codegen/tests/golden/constant/rust/conformance.rs
new file mode 100644
index 0000000..9381954
--- /dev/null
+++ b/codegen/tests/golden/constant/rust/conformance.rs
@@ -0,0 +1,5 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+
+pub const MAX_RETRIES: u8 = 5;
+
diff --git a/codegen/tests/golden/cross_schema/rust/api.rs b/codegen/tests/golden/cross_schema/rust/api.rs
new file mode 100644
index 0000000..140cb68
--- /dev/null
+++ b/codegen/tests/golden/cross_schema/rust/api.rs
@@ -0,0 +1,11 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Holder {
+ pub one: crate::shared::Shared,
+ pub maybe: Option,
+ pub list: Vec,
+}
+
diff --git a/codegen/tests/golden/cross_schema/rust/shared.rs b/codegen/tests/golden/cross_schema/rust/shared.rs
new file mode 100644
index 0000000..598eca1
--- /dev/null
+++ b/codegen/tests/golden/cross_schema/rust/shared.rs
@@ -0,0 +1,9 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Shared {
+ pub value: i32,
+}
+
diff --git a/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs
new file mode 100644
index 0000000..80d4d08
--- /dev/null
+++ b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs
@@ -0,0 +1,137 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+use serde::{Deserialize, Serialize};
+use comline_runtime::connection::Connection;
+use comline_runtime::contract::{
+ Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat,
+};
+use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber};
+use comline_runtime::transport::Transport;
+
+/// Canonical digest of the frozen IR this file was generated from — the
+/// two ends of a connection must agree on it, and the handshake checks.
+pub const IR_HASH: u64 = 0x25f4c4d936e7aa90;
+
+#[doc(hidden)]
+pub use crate::connection::{CONNECTION_IR_HASH, Format};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Message {
+ pub greeting: crate::localdeps::greeting::Greeting,
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatGreetParams {
+ pub n: u32,
+}
+
+pub type ChatGreetError = ::core::convert::Infallible;
+
+pub type ChatError = ::core::convert::Infallible;
+
+pub trait Chat {
+ fn greet(&self, peer: &mut impl Peer, n: u32) -> Result>;
+}
+
+#[doc(hidden)]
+pub const CHAT_CALLS: &[&str] = &["greet"];
+
+#[doc(hidden)]
+pub struct ChatDispatcher(pub S);
+
+impl Dispatch for ChatDispatcher {
+ fn calls(&self) -> &'static [&'static str] {
+ CHAT_CALLS
+ }
+
+ /// Only served on a connection, whose handlers are given the peer:
+ /// anywhere else the caller hears a fault.
+ fn dispatch(
+ &self,
+ _call: Kind,
+ _params: &[u8],
+ _fmt: &W,
+ reply: &mut Reply,
+ ) -> Result<(), RuntimeError> {
+ reply.fault();
+ Ok(())
+ }
+
+ fn dispatch_with(
+ &self,
+ call: Kind,
+ params: &[u8],
+ reply: &mut Reply,
+ peer: &mut P,
+ ) -> Result<(), RuntimeError> {
+ let number = match call {
+ Kind::Id(number) => number,
+ Kind::Named(_) => return Err(RuntimeError::UnknownCall),
+ };
+ match number {
+ 0 => {
+ let p: ChatGreetParams = match peer.format().decode(params) {
+ Ok(p) => p,
+ Err(_) => {
+ reply.fault();
+ return Ok(());
+ }
+ };
+ match self.0.greet(peer, p.n) {
+ Ok(value) => {
+ let mut body = Vec::new();
+ peer.format().encode(&value, &mut body)?;
+ reply.ok(&body);
+ }
+ Err(Fault::App(never)) => match never {},
+ Err(Fault::Internal) => reply.fault(),
+ }
+ Ok(())
+ }
+ _ => Err(RuntimeError::UnknownCall),
+ }
+ }
+}
+
+impl ChatDispatcher {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ /// Provide this protocol on `conn`: the peer's calls to it come here.
+ /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts.
+ pub fn provide_on(
+ self,
+ conn: &mut Connection,
+ ) where
+ S: 'static,
+ {
+ conn.provide(Self::PROTOCOL, self)
+ }
+}
+
+/// Calls protocol `Chat` on the other end of a connection: the peer a
+/// `Connection` reaches, or the one a handler was given.
+pub struct ChatSender<'p, P: Peer>(pub &'p mut P);
+
+impl<'p, P: Peer> ChatSender<'p, P> {
+ /// This protocol's number on a connection.
+ #[doc(hidden)]
+ pub const PROTOCOL: ProtocolNumber = 0;
+
+ pub fn new(peer: &'p mut P) -> Self {
+ Self(peer)
+ }
+
+ pub fn greet(&mut self, n: u32) -> Result> {
+ crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "api::Chat", "greet")?;
+ let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "greet"), &ChatGreetParams { n })?;
+ match reply {
+ Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime),
+ Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })),
+ Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)),
+ }
+ }
+}
+
diff --git a/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs
new file mode 100644
index 0000000..bbeb477
--- /dev/null
+++ b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs
@@ -0,0 +1,189 @@
+// Generated by Comline
+// For Rust 1.85.0 or later; verified up to 1.99.
+//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it:
+//!
+//! - Implement the trait of each protocol the server provides: `api::Chat`.
+//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time.
+//! - Dial with [`connect`]`(transport)`.
+//! - Call the server from the dialling side: `ChatSender::new(&mut conn).greet(..)`.
+//!
+//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format.
+
+use comline_runtime::contract::{Peer, Reason, RuntimeError};
+use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated};
+use comline_runtime::transport::Transport;
+
+/// The package's wire format (`wire.format`).
+pub type Format = comline_runtime::format::Packed;
+
+/// Digest of every schema in the package — what a connection's handshake
+/// checks, so both ends agree on each protocol's number.
+pub const CONNECTION_IR_HASH: u64 = 0x55e3b94344a9c775;
+
+/// The framing the package's connection runs on (`datagram@3`).
+pub type Framing = comline_runtime::contract::Datagram3Framing;
+
+/// The package's connection over the transport `T`: what [`accept`] and [`connect`]
+/// return, written `Connection`: [`Format`] over [`Framing`].
+pub type Connection = comline_runtime::connection::Connection;
+
+/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its
+/// history records it. Its protocols, by wire number:
+///
+/// - 0 `api::Chat`, line 0.1.0: `greet` 0
+#[doc(hidden)]
+pub const HELLO: &[u8] = &[
+ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd,
+ 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00,
+ 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02,
+ 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c,
+ 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2,
+ 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1,
+ 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a,
+ 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,
+ 0x5a, 0x5a, 0x01, 0x00,
+];
+
+/// The `comline@2` handshake, with [`HELLO`] and the parameters the package
+/// states: `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`.
+#[doc(hidden)]
+pub fn handshake() -> Comline2Handshake {
+ use comline_runtime::handshake::comline2 as c2;
+ let hello = match c2::Message::decode(HELLO) {
+ Ok(c2::Message::Hello(hello)) => hello,
+ _ => unreachable!("HELLO is a Hello message"),
+ };
+ let params = c2::Params {
+ scope: c2::Scope::Protocol,
+ newer_consumer: c2::NewerConsumer::Degrade,
+ same_version_differs: c2::SameVersionDiffers::Refuse,
+ exchange: c2::Exchange::Offer,
+ };
+ c2::Comline2Handshake::new(params, hello)
+}
+
+/// The package's protocols on the connection, by wire number.
+const PROTOCOLS: &[(u16, &str)] = &[(0, "api::Chat")];
+
+fn protocol_path(number: u16) -> &'static str {
+ PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path)
+}
+
+/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in
+/// the connection's extensions.
+#[derive(Debug, Clone)]
+pub struct Negotiation {
+ pub negotiated: Negotiated,
+ /// The last call that wasn't made because the peer can't take it.
+ pub unavailable: Option,
+}
+
+/// A call that wasn't sent because the peer can't take it: which, and why.
+/// The call itself fails with `RuntimeError::Unavailable`, which carries no
+/// detail; [`unavailable`] gives this.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Unavailable {
+ /// `namespace::Protocol`.
+ pub protocol: &'static str,
+ pub function: &'static str,
+ /// Why the peer refused the protocol, or `None` when the peer lacks the
+ /// function (`newer_consumer = degrade`).
+ pub refused: Option,
+}
+
+impl ::core::fmt::Display for Unavailable {
+ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
+ match self.refused {
+ Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol),
+ None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function),
+ }
+ }
+}
+
+impl ::core::error::Error for Unavailable {}
+
+/// What the connection's `comline@2` handshake agreed, if `accept` / `connect`
+/// opened it.
+pub fn negotiated(peer: &mut P) -> Option {
+ let extensions = peer.extensions();
+ extensions.get::