feat(interface): add authoring macros and codecs
Add the wip-interface facade and proc-macro implementation for typed interface descriptors, DTO value codecs, validated dispatch, metadata extraction, and span-aware compile failures.
This commit is contained in:
Generated
+260
@@ -2,6 +2,260 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-tuple"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f"
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
||||
|
||||
[[package]]
|
||||
name = "trybuild"
|
||||
version = "1.0.121"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0cabaa10be1917331a313866bd94526343e03c77bcf69144b62b072ad35d47c"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"target-tuple",
|
||||
"termcolor",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
|
||||
[[package]]
|
||||
name = "wip-interface"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"trybuild",
|
||||
"wip-interface-macros",
|
||||
"wip-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wip-interface-macros"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wip-protocol"
|
||||
version = "0.1.0"
|
||||
@@ -12,3 +266,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"wip-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
+6
-1
@@ -1,5 +1,10 @@
|
||||
[workspace]
|
||||
members = [".", "crates/wip-protocol"]
|
||||
members = [
|
||||
".",
|
||||
"crates/wip-interface",
|
||||
"crates/wip-interface-macros",
|
||||
"crates/wip-protocol",
|
||||
]
|
||||
resolver = "3"
|
||||
|
||||
[package]
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# wip-rs
|
||||
|
||||
Rust building blocks for the Web Interface Protocol (WIP).
|
||||
|
||||
## Interface authoring
|
||||
|
||||
Applications depend on `wip-interface`, normally imported as `wip`:
|
||||
|
||||
```rust
|
||||
use wip_interface as wip;
|
||||
|
||||
#[derive(wip::WipType)]
|
||||
struct Message {
|
||||
/// Message body.
|
||||
text: String,
|
||||
}
|
||||
|
||||
#[wip::interface]
|
||||
pub trait Messenger {
|
||||
/// Sends a message.
|
||||
///
|
||||
/// # Returns
|
||||
/// Whether the application accepted the message.
|
||||
fn send(
|
||||
&self,
|
||||
/// Message to send.
|
||||
message: Message,
|
||||
) -> wip::OperationResult<bool>;
|
||||
}
|
||||
```
|
||||
|
||||
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
||||
users do not import `wip-interface-macros` directly. The generated
|
||||
`MessengerDefinition` constructs an `InterfaceDescriptor`, decodes named
|
||||
arguments, encodes results, validates both boundaries, and provides typed
|
||||
dispatch for any `T: Messenger`.
|
||||
|
||||
### Type mapping
|
||||
|
||||
| Rust | Protocol |
|
||||
| --- | --- |
|
||||
| `()` as an operation result | no returned value |
|
||||
| `bool` | boolean |
|
||||
| integer primitives | JavaScript-lossless integer |
|
||||
| `f32`, `f64` | finite number |
|
||||
| `String` | string |
|
||||
| `wip::Bytes` | bytes |
|
||||
| `wip::wip_protocol::JsonValue` | JSON |
|
||||
| `wip::Entry<K, V>` | entry |
|
||||
| `Vec<T>` | list |
|
||||
| named-field `#[derive(wip::WipType)]` struct | named record |
|
||||
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
||||
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
||||
|
||||
`Option<T>` is accepted only for a direct DTO field or operation parameter and
|
||||
means that the named value may be omitted. It is not protocol null. Domain
|
||||
failures are modeled in the application result (usually a derived union) and
|
||||
returned through `Ok`; `wip::HostError` is only for host/runtime failures.
|
||||
|
||||
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
||||
section documents the return declaration; text before that section documents
|
||||
the operation itself.
|
||||
|
||||
The supported interface slice is deliberately non-generic: public traits,
|
||||
`&self`, named parameters, and `OperationResult<T>`. Generic traits or methods,
|
||||
associated items, custom lifetimes, inheritance, default method bodies, and
|
||||
other receiver forms are rejected at their source spans.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "wip-interface-macros"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Procedural macros for WIP interface declarations and DTO codecs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1"
|
||||
quote = "1"
|
||||
syn = { version = "2", features = ["full", "visit"] }
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "wip-interface"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Public Rust authoring API for WIP interfaces and operation value codecs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
wip-interface-macros = { path = "../wip-interface-macros" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1"
|
||||
@@ -0,0 +1,661 @@
|
||||
//! Public authoring API for Web Interface Protocol (WIP) interfaces.
|
||||
//!
|
||||
//! Add `wip-interface` to an application and import it under the short name
|
||||
//! used by the attribute examples:
|
||||
//!
|
||||
//! ```
|
||||
//! use wip_interface as wip;
|
||||
//!
|
||||
//! #[derive(Debug, PartialEq, wip::WipType)]
|
||||
//! struct Greeting {
|
||||
//! /// Text shown to the recipient.
|
||||
//! message: String,
|
||||
//! }
|
||||
//!
|
||||
//! #[wip::interface]
|
||||
//! pub trait Greeter {
|
||||
//! /// Builds a greeting.
|
||||
//! ///
|
||||
//! /// # Returns
|
||||
//! /// The generated greeting.
|
||||
//! fn greet(&self, /// Person to greet.
|
||||
//! name: String) -> wip::OperationResult<Greeting>;
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! The attribute and derive are re-exported by this facade; applications do
|
||||
//! not depend on the implementation-only `wip-interface-macros` crate.
|
||||
//!
|
||||
//! # Rust to protocol type mapping
|
||||
//!
|
||||
//! | Rust type | Protocol type/value |
|
||||
//! | --- | --- |
|
||||
//! | `()` as an operation result | no return declaration / no value |
|
||||
//! | `bool` | `Boolean` |
|
||||
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
||||
//! | `f32`, `f64` | finite `Number` |
|
||||
//! | `String` | `String` |
|
||||
//! | [`Bytes`] | `Bytes` |
|
||||
//! | [`wip_protocol::JsonValue`] | `Json` |
|
||||
//! | [`Entry<K, V>`] | `Entry<K, V>` |
|
||||
//! | `Vec<T>` | `List<T>` |
|
||||
//! | a named-field struct deriving [`WipType`] | named record |
|
||||
//! | an all-unit enum deriving [`WipType`] | named enum |
|
||||
//! | an all-newtype enum deriving [`WipType`] | named tagged union |
|
||||
//!
|
||||
//! `Option<T>` is supported only directly as a record field or operation
|
||||
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||
//! an application return enum/union and is returned as `Ok(value)`.
|
||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
pub use wip_interface_macros::{WipType, interface};
|
||||
pub use wip_protocol;
|
||||
pub use wip_protocol::{
|
||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
||||
JsonMember, JsonValue, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NamedValue, OperationDeclaration,
|
||||
ParameterDeclaration, RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
||||
UnionDeclaration, UnionVariantDeclaration, ValidationError, Value,
|
||||
};
|
||||
|
||||
/// Converts one Rust application type to and from its protocol representation.
|
||||
///
|
||||
/// Implementations must describe the same shape accepted by [`WipType::decode`]
|
||||
/// and produced by [`WipType::encode`]. Prefer deriving this trait for named
|
||||
/// DTOs. Its declaration-collection method exists for generated interface code
|
||||
/// and normally should not be called by applications.
|
||||
pub trait WipType: Sized {
|
||||
/// Returns the protocol type expression for this Rust type.
|
||||
fn type_expr() -> TypeExpr;
|
||||
|
||||
/// Adds named declarations reachable from this type to `declarations`.
|
||||
///
|
||||
/// Implementations must be cycle-safe and preserve declaration order.
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>);
|
||||
|
||||
/// Encodes this value into the transport-independent protocol value model.
|
||||
fn encode(self) -> Result<Value, CodecError>;
|
||||
|
||||
/// Decodes a previously validated protocol value.
|
||||
fn decode(value: Value) -> Result<Self, CodecError>;
|
||||
}
|
||||
|
||||
/// Static metadata implemented by every companion generated by
|
||||
/// [`interface`].
|
||||
pub trait InterfaceDefinition {
|
||||
/// Builds the interface descriptor solely from its trait declaration.
|
||||
fn descriptor() -> InterfaceDescriptor;
|
||||
}
|
||||
|
||||
/// Result convention required for generated interface operations.
|
||||
///
|
||||
/// `Ok(T)` is an application result, including domain-failure union cases.
|
||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||
pub type OperationResult<T> = Result<T, HostError>;
|
||||
|
||||
/// A host/runtime failure, kept separate from the operation's application
|
||||
/// return type.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostError {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl HostError {
|
||||
/// Creates a host failure with a human-readable diagnostic.
|
||||
#[must_use]
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the diagnostic message.
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for HostError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for HostError {}
|
||||
|
||||
/// A failure while converting between a Rust value and a protocol [`Value`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CodecError {
|
||||
path: Vec<String>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl CodecError {
|
||||
/// Creates a codec failure at the current value.
|
||||
#[must_use]
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
path: Vec::new(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a structural-kind mismatch diagnostic.
|
||||
#[must_use]
|
||||
pub fn expected(expected: &str, actual: &Value) -> Self {
|
||||
Self::new(format!("expected {expected}, found {:?}", actual.kind()))
|
||||
}
|
||||
|
||||
/// Prepends a field, variant, or collection position to the error path.
|
||||
#[must_use]
|
||||
pub fn at(mut self, segment: impl Into<String>) -> Self {
|
||||
self.path.insert(0, segment.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the path from the decoded root to the failing value.
|
||||
#[must_use]
|
||||
pub fn path(&self) -> &[String] {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Returns the human-readable reason for the failure.
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for CodecError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
if self.path.is_empty() {
|
||||
write!(formatter, "WIP codec error: {}", self.message)
|
||||
} else {
|
||||
write!(
|
||||
formatter,
|
||||
"WIP codec error at {}: {}",
|
||||
self.path.join("."),
|
||||
self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CodecError {}
|
||||
|
||||
/// A failure produced by macro-generated typed operation dispatch.
|
||||
#[derive(Debug)]
|
||||
pub enum DispatchError {
|
||||
/// The requested operation is not declared by this interface.
|
||||
UnknownOperation(String),
|
||||
/// Protocol validation rejected the named arguments.
|
||||
InvalidArguments(wip_protocol::ValidationError),
|
||||
/// A validated value could not be decoded to its Rust type.
|
||||
Decode(CodecError),
|
||||
/// The implementation reported a host/runtime failure.
|
||||
Host(HostError),
|
||||
/// The Rust result could not be encoded.
|
||||
Encode(CodecError),
|
||||
/// The encoded result did not match the generated declaration.
|
||||
InvalidResult(wip_protocol::ValidationError),
|
||||
}
|
||||
|
||||
impl Display for DispatchError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::UnknownOperation(operation) => {
|
||||
write!(formatter, "unknown operation `{operation}`")
|
||||
}
|
||||
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
||||
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
||||
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
|
||||
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
||||
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for DispatchError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) => None,
|
||||
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
||||
Self::Decode(error) | Self::Encode(error) => Some(error),
|
||||
Self::Host(error) => Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An explicitly byte-oriented sequence.
|
||||
///
|
||||
/// Use this wrapper when the protocol type must be `Bytes`; `Vec<T>` always
|
||||
/// denotes a protocol list, including `Vec<u8>`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Bytes(pub Vec<u8>);
|
||||
|
||||
impl From<Vec<u8>> for Bytes {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Bytes> for Vec<u8> {
|
||||
fn from(value: Bytes) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed protocol key/value entry.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry<K, V> {
|
||||
/// Entry key.
|
||||
pub key: K,
|
||||
/// Entry value.
|
||||
pub value: V,
|
||||
}
|
||||
|
||||
impl WipType for bool {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Boolean
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Boolean(self))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Boolean(value) => Ok(value),
|
||||
other => Err(CodecError::expected("boolean", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! integer_codec {
|
||||
($($ty:ty),+ $(,)?) => {
|
||||
$(
|
||||
impl WipType for $ty {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Integer
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
let value = i64::try_from(self).map_err(|_| {
|
||||
CodecError::new("integer is outside the protocol i64 range")
|
||||
})?;
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(Value::Integer(value))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::Integer(value) = value else {
|
||||
return Err(CodecError::expected("integer", &value));
|
||||
};
|
||||
ensure_safe_integer(value)?;
|
||||
Self::try_from(value).map_err(|_| {
|
||||
CodecError::new(concat!("integer does not fit Rust `", stringify!($ty), "`"))
|
||||
})
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
integer_codec!(
|
||||
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
|
||||
);
|
||||
|
||||
fn ensure_safe_integer(value: i64) -> Result<(), CodecError> {
|
||||
if (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodecError::new(format!(
|
||||
"integer {value} is outside the JavaScript-lossless protocol range"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for f64 {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Number
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
ensure_finite(self)?;
|
||||
Ok(Value::Number(self))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(value)
|
||||
}
|
||||
other => Err(CodecError::expected("number", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for f32 {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Number
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
let value = f64::from(self);
|
||||
ensure_finite(value)?;
|
||||
Ok(Value::Number(value))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let value = f64::decode(value)?;
|
||||
let narrowed = value as Self;
|
||||
if narrowed.is_finite() {
|
||||
Ok(narrowed)
|
||||
} else {
|
||||
Err(CodecError::new("number does not fit finite Rust `f32`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_finite(value: f64) -> Result<(), CodecError> {
|
||||
if value.is_finite() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodecError::new("protocol numbers must be finite"))
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for String {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::String
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::String(self))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::String(value) => Ok(value),
|
||||
other => Err(CodecError::expected("string", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for Bytes {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Bytes
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Bytes(self.0))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Bytes(value) => Ok(Self(value)),
|
||||
other => Err(CodecError::expected("bytes", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for JsonValue {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Json
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
validate_json(&self)?;
|
||||
Ok(Value::Json(self))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Json(value) => {
|
||||
validate_json(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
other => Err(CodecError::expected("json", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_json(value: &JsonValue) -> Result<(), CodecError> {
|
||||
match value {
|
||||
JsonValue::Integer(value) => ensure_safe_integer(*value),
|
||||
JsonValue::Number(value) => ensure_finite(*value),
|
||||
JsonValue::Array(values) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
validate_json(value).map_err(|error| error.at(index.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
JsonValue::Object(members) => {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for member in members {
|
||||
if !names.insert(member.name.as_str()) {
|
||||
return Err(CodecError::new(format!(
|
||||
"duplicate JSON member `{}`",
|
||||
member.name
|
||||
))
|
||||
.at(member.name.clone()));
|
||||
}
|
||||
validate_json(&member.value).map_err(|error| error.at(member.name.clone()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
JsonValue::Null | JsonValue::Boolean(_) | JsonValue::String(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: WipType> WipType for Vec<T> {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::List(Box::new(T::type_expr()))
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
T::collect_declarations(declarations);
|
||||
}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
self.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| value.encode().map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(Value::List)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::List(values) = value else {
|
||||
return Err(CodecError::expected("list", &value));
|
||||
};
|
||||
values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| T::decode(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Entry {
|
||||
key: Box::new(K::type_expr()),
|
||||
value: Box::new(V::type_expr()),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
K::collect_declarations(declarations);
|
||||
V::collect_declarations(declarations);
|
||||
}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Entry {
|
||||
key: Box::new(self.key.encode().map_err(|error| error.at("key"))?),
|
||||
value: Box::new(self.value.encode().map_err(|error| error.at("value"))?),
|
||||
})
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::Entry { key, value } = value else {
|
||||
return Err(CodecError::expected("entry", &value));
|
||||
};
|
||||
Ok(Self {
|
||||
key: K::decode(*key).map_err(|error| error.at("key"))?,
|
||||
value: V::decode(*value).map_err(|error| error.at("value"))?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation details used by code emitted from the facade's macros.
|
||||
///
|
||||
/// These APIs are public only because macro expansions execute in the
|
||||
/// application crate. They are excluded from normal generated documentation
|
||||
/// and are not intended for direct use.
|
||||
#[doc(hidden)]
|
||||
pub mod __private {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use wip_protocol::{
|
||||
InterfaceDescriptor, NamedValue, ObjectId, OperationCall, OperationTarget, TypeDeclaration,
|
||||
ValidationError, Value,
|
||||
};
|
||||
|
||||
use crate::{CodecError, Documentation, WipType};
|
||||
|
||||
/// Builds optional descriptor documentation from generated string literals.
|
||||
pub fn documentation(summary: &str, details: Option<&str>) -> Option<Documentation> {
|
||||
if summary.is_empty() && details.is_none() {
|
||||
None
|
||||
} else {
|
||||
Some(Documentation {
|
||||
summary: summary.into(),
|
||||
details: details.map(str::to_owned),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers one declaration and reports whether its dependencies should
|
||||
/// be traversed. Identical declarations are deduplicated; a conflicting
|
||||
/// declaration with the same name is retained for protocol validation.
|
||||
pub fn register_declaration(
|
||||
declarations: &mut Vec<TypeDeclaration>,
|
||||
declaration: TypeDeclaration,
|
||||
) -> bool {
|
||||
if declarations.iter().any(|existing| existing == &declaration) {
|
||||
false
|
||||
} else {
|
||||
declarations.push(declaration);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates named arguments against one generated operation declaration.
|
||||
pub fn validate_arguments(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
arguments: &[NamedValue],
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(&OperationCall {
|
||||
target: OperationTarget {
|
||||
object: ObjectId("<typed-dispatch>".into()),
|
||||
interface: descriptor.name.clone(),
|
||||
operation: operation.into(),
|
||||
},
|
||||
arguments: arguments.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds a codec error for a generated structural mismatch.
|
||||
pub fn decode_type_mismatch(expected: &str, actual: Value) -> CodecError {
|
||||
CodecError::expected(expected, &actual)
|
||||
}
|
||||
|
||||
/// Builds a codec error for an unknown generated enum or union variant.
|
||||
pub fn decode_unknown_variant(type_name: &str, variant: String) -> CodecError {
|
||||
CodecError::new(format!(
|
||||
"unknown variant `{variant}` for WIP type `{type_name}`"
|
||||
))
|
||||
.at(variant)
|
||||
}
|
||||
|
||||
/// Decoder for a protocol record or operation's named argument collection.
|
||||
pub struct RecordDecoder {
|
||||
fields: Vec<NamedValue>,
|
||||
seen: HashSet<String>,
|
||||
}
|
||||
|
||||
impl RecordDecoder {
|
||||
/// Starts decoding record fields or named operation arguments and
|
||||
/// rejects duplicate names.
|
||||
pub fn new(fields: Vec<NamedValue>) -> Result<Self, CodecError> {
|
||||
let mut seen = HashSet::new();
|
||||
for field in &fields {
|
||||
if !seen.insert(field.name.clone()) {
|
||||
return Err(CodecError::new(format!("duplicate field `{}`", field.name))
|
||||
.at(field.name.clone()));
|
||||
}
|
||||
}
|
||||
Ok(Self { fields, seen })
|
||||
}
|
||||
|
||||
/// Decodes a required field.
|
||||
pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
|
||||
let value = self.take(name).ok_or_else(|| {
|
||||
CodecError::new(format!("missing required field `{name}`")).at(name)
|
||||
})?;
|
||||
T::decode(value).map_err(|error| error.at(name))
|
||||
}
|
||||
|
||||
/// Decodes an optional field, where absence maps to `None`.
|
||||
pub fn optional<T: WipType>(&mut self, name: &str) -> Result<Option<T>, CodecError> {
|
||||
self.take(name)
|
||||
.map(T::decode)
|
||||
.transpose()
|
||||
.map_err(|error| error.at(name))
|
||||
}
|
||||
|
||||
/// Rejects any fields that were not consumed by generated code.
|
||||
pub fn finish(self) -> Result<(), CodecError> {
|
||||
if let Some(field) = self.fields.first() {
|
||||
Err(CodecError::new(format!("unknown field `{}`", field.name))
|
||||
.at(field.name.clone()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, name: &str) -> Option<Value> {
|
||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
||||
Some(self.fields.remove(index).value)
|
||||
}
|
||||
|
||||
/// Returns the set of names supplied to this decoder.
|
||||
#[allow(dead_code)]
|
||||
pub fn supplied_names(&self) -> &HashSet<String> {
|
||||
&self.seen
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
use wip_interface::wip_protocol::{
|
||||
EnumDeclaration, JsonMember, JsonValue, NamedValue, RecordDeclaration, TypeDeclaration,
|
||||
TypeExpr, UnionDeclaration, Value,
|
||||
};
|
||||
use wip_interface::{Bytes, Entry, WipType};
|
||||
|
||||
/// A request record.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
struct Request {
|
||||
/// Required title.
|
||||
title: String,
|
||||
/// Optional priority.
|
||||
priority: Option<i32>,
|
||||
/// Related entries.
|
||||
related: Vec<Entry<String, bool>>,
|
||||
/// Opaque bytes.
|
||||
body: Bytes,
|
||||
/// Arbitrary metadata.
|
||||
metadata: JsonValue,
|
||||
}
|
||||
|
||||
/// Available colors.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
enum Color {
|
||||
/// Warm red.
|
||||
Red,
|
||||
/// Cool blue.
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// A receipt record.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
struct Receipt {
|
||||
/// Receipt number.
|
||||
number: u32,
|
||||
}
|
||||
|
||||
/// Application-level publication outcome.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
enum PublishOutcome {
|
||||
/// Application success.
|
||||
Published(Receipt),
|
||||
/// Domain rejection, not a host failure.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_values_round_trip() {
|
||||
let request = Request {
|
||||
title: "hello".into(),
|
||||
priority: None,
|
||||
related: vec![Entry {
|
||||
key: "/articles/1".into(),
|
||||
value: true,
|
||||
}],
|
||||
body: Bytes(vec![1, 2, 3]),
|
||||
metadata: JsonValue::Object(vec![JsonMember {
|
||||
name: "source".into(),
|
||||
value: JsonValue::String("test".into()),
|
||||
}]),
|
||||
};
|
||||
|
||||
let encoded = request.clone().encode().unwrap();
|
||||
let Value::Record(fields) = &encoded else {
|
||||
panic!("record derive must encode a protocol record")
|
||||
};
|
||||
assert!(fields.iter().all(|field| field.name != "priority"));
|
||||
assert_eq!(Request::decode(encoded).unwrap(), request);
|
||||
|
||||
for color in [Color::Red, Color::Blue] {
|
||||
let encoded = color.clone().encode().unwrap();
|
||||
let decoded = Color::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, color);
|
||||
}
|
||||
|
||||
for outcome in [
|
||||
PublishOutcome::Published(Receipt { number: 7 }),
|
||||
PublishOutcome::Rejected("policy".into()),
|
||||
] {
|
||||
let encoded = outcome.clone().encode().unwrap();
|
||||
let decoded = PublishOutcome::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, outcome);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_declarations_include_docs_optionality_and_dependencies() {
|
||||
let mut declarations = Vec::new();
|
||||
Request::collect_declarations(&mut declarations);
|
||||
Color::collect_declarations(&mut declarations);
|
||||
PublishOutcome::collect_declarations(&mut declarations);
|
||||
|
||||
let TypeDeclaration::Record(RecordDeclaration {
|
||||
documentation,
|
||||
fields,
|
||||
..
|
||||
}) = &declarations[0]
|
||||
else {
|
||||
panic!("Request must be a record declaration")
|
||||
};
|
||||
assert_eq!(documentation.as_ref().unwrap().summary, "A request record.");
|
||||
assert_eq!(
|
||||
fields[0].documentation.as_ref().unwrap().summary,
|
||||
"Required title."
|
||||
);
|
||||
assert!(!fields[0].optional);
|
||||
assert!(fields[1].optional);
|
||||
assert_eq!(fields[1].ty, TypeExpr::Integer);
|
||||
assert_eq!(
|
||||
fields[2].ty,
|
||||
TypeExpr::List(Box::new(TypeExpr::Entry {
|
||||
key: Box::new(TypeExpr::String),
|
||||
value: Box::new(TypeExpr::Boolean),
|
||||
}))
|
||||
);
|
||||
|
||||
let color = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "Color")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Enum(EnumDeclaration { variants, .. }) = color else {
|
||||
panic!("Color must be an enum declaration")
|
||||
};
|
||||
assert_eq!(
|
||||
variants[0].documentation.as_ref().unwrap().summary,
|
||||
"Warm red."
|
||||
);
|
||||
|
||||
let outcome = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "PublishOutcome")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Union(UnionDeclaration { variants, .. }) = outcome else {
|
||||
panic!("PublishOutcome must be a union declaration")
|
||||
};
|
||||
assert_eq!(variants[0].ty, TypeExpr::Named("Receipt".into()));
|
||||
assert!(
|
||||
declarations
|
||||
.iter()
|
||||
.any(|declaration| declaration.name() == "Receipt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_reject_invalid_boundaries() {
|
||||
assert!(i64::MAX.encode().is_err());
|
||||
assert!(f64::NAN.encode().is_err());
|
||||
assert!(Request::decode(Value::Record(vec![])).is_err());
|
||||
assert!(
|
||||
Request::decode(Value::Record(vec![NamedValue {
|
||||
name: "unknown".into(),
|
||||
value: Value::String("value".into()),
|
||||
}]))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::Enum("Green".into())).is_err());
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#[test]
|
||||
fn rejects_unsupported_interface_and_dto_syntax() {
|
||||
let tests = trybuild::TestCases::new();
|
||||
tests.compile_fail("tests/ui/*.rs");
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
use wip_interface::wip_protocol::{NamedValue, TypeDeclaration, TypeExpr, Value};
|
||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
||||
|
||||
/// Publication request.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
pub struct PublishRequest {
|
||||
/// Item title.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
/// Application outcome, including domain failure.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
pub enum PublishOutcome {
|
||||
/// The item was accepted.
|
||||
Published(bool),
|
||||
/// The application rejected the item.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
/// Catalog editing capability.
|
||||
///
|
||||
/// The shape is implementation-independent.
|
||||
#[interface]
|
||||
pub trait Catalog {
|
||||
/// Publishes one item.
|
||||
///
|
||||
/// This operation can report a domain rejection in its application union.
|
||||
///
|
||||
/// # Returns
|
||||
/// The application publication outcome.
|
||||
fn publish(
|
||||
&self,
|
||||
/// Item to publish.
|
||||
request: PublishRequest,
|
||||
/// Optional audit note.
|
||||
note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome>;
|
||||
|
||||
/// Checks connectivity without returning an application value.
|
||||
fn ping(&self) -> OperationResult<()>;
|
||||
|
||||
/// Demonstrates a host/runtime failure.
|
||||
///
|
||||
/// # Returns
|
||||
/// A value only when the host succeeds.
|
||||
fn host_value(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
struct AcceptingCatalog;
|
||||
|
||||
impl Catalog for AcceptingCatalog {
|
||||
fn publish(
|
||||
&self,
|
||||
request: PublishRequest,
|
||||
note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome> {
|
||||
assert_eq!(request.title, "example");
|
||||
assert_eq!(note.as_deref(), Some("audit"));
|
||||
Ok(PublishOutcome::Published(true))
|
||||
}
|
||||
|
||||
fn ping(&self) -> OperationResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
Err(HostError::new("backend unavailable"))
|
||||
}
|
||||
}
|
||||
|
||||
struct RejectingCatalog;
|
||||
|
||||
impl Catalog for RejectingCatalog {
|
||||
fn publish(
|
||||
&self,
|
||||
_request: PublishRequest,
|
||||
_note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome> {
|
||||
Ok(PublishOutcome::Rejected("policy".into()))
|
||||
}
|
||||
|
||||
fn ping(&self) -> OperationResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
Ok("ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn named(name: &str, value: Value) -> NamedValue {
|
||||
NamedValue {
|
||||
name: name.into(),
|
||||
value,
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_arguments(with_note: bool) -> Vec<NamedValue> {
|
||||
let mut arguments = vec![named(
|
||||
"request",
|
||||
PublishRequest {
|
||||
title: "example".into(),
|
||||
}
|
||||
.encode()
|
||||
.unwrap(),
|
||||
)];
|
||||
if with_note {
|
||||
arguments.push(named("note", Value::String("audit".into())));
|
||||
}
|
||||
arguments
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
let first = CatalogDefinition::descriptor();
|
||||
let second = CatalogDefinition::descriptor();
|
||||
assert_eq!(first, second);
|
||||
first.validate().unwrap();
|
||||
|
||||
assert_eq!(first.name, "Catalog");
|
||||
assert_eq!(
|
||||
first.documentation.as_ref().unwrap().summary,
|
||||
"Catalog editing capability."
|
||||
);
|
||||
assert_eq!(
|
||||
first.documentation.as_ref().unwrap().details.as_deref(),
|
||||
Some("The shape is implementation-independent.")
|
||||
);
|
||||
assert_eq!(first.operations.len(), 3);
|
||||
|
||||
let publish = &first.operations[0];
|
||||
assert_eq!(publish.name, "publish");
|
||||
assert_eq!(publish.parameters[0].name, "request");
|
||||
assert_eq!(
|
||||
publish.parameters[0]
|
||||
.documentation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.summary,
|
||||
"Item to publish."
|
||||
);
|
||||
assert!(!publish.parameters[0].optional);
|
||||
assert!(publish.parameters[1].optional);
|
||||
assert_eq!(
|
||||
publish
|
||||
.returns
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.summary,
|
||||
"The application publication outcome."
|
||||
);
|
||||
assert_eq!(
|
||||
publish.returns.as_ref().unwrap().ty,
|
||||
TypeExpr::Named("PublishOutcome".into())
|
||||
);
|
||||
assert!(first.operations[1].returns.is_none());
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Record(_)))
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Union(_)))
|
||||
);
|
||||
|
||||
// Both implementation types satisfy the same generated dispatch boundary;
|
||||
// neither can affect the descriptor shape.
|
||||
fn accepts_definition<T: Catalog>(_: &T) {}
|
||||
accepts_definition(&AcceptingCatalog);
|
||||
accepts_definition(&RejectingCatalog);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_argument_decoder_and_result_encoder_round_trip() {
|
||||
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
|
||||
assert_eq!(decoded.request.title, "example");
|
||||
assert_eq!(decoded.note, None);
|
||||
|
||||
let encoded = CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(encoded).unwrap(),
|
||||
PublishOutcome::Rejected("domain".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||
let value = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(value).unwrap(),
|
||||
PublishOutcome::Published(true)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", vec![]).unwrap(),
|
||||
None
|
||||
);
|
||||
|
||||
let invalid = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", vec![]).unwrap_err();
|
||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||
|
||||
let host = CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", vec![]).unwrap_err();
|
||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
||||
|
||||
let unknown = CatalogDefinition::dispatch(&AcceptingCatalog, "missing", vec![]).unwrap_err();
|
||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait AssociatedType {
|
||||
type Item;
|
||||
|
||||
fn load(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: associated types are not supported in WIP interfaces
|
||||
--> tests/ui/associated_type.rs:5:5
|
||||
|
|
||||
5 | type Item;
|
||||
| ^^^^^^^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/associated_type.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait BadReceiver {
|
||||
fn load(&mut self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: the only supported receiver is exactly `&self`
|
||||
--> tests/ui/bad_receiver.rs:5:13
|
||||
|
|
||||
5 | fn load(&mut self) -> OperationResult<String>;
|
||||
| ^^^^^^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/bad_receiver.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait BadReturn {
|
||||
fn load(&self) -> String;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: an operation must explicitly return `OperationResult<T>`
|
||||
--> tests/ui/bad_return.rs:5:23
|
||||
|
|
||||
5 | fn load(&self) -> String;
|
||||
| ^^^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/bad_return.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait BorrowedValue<'a> {
|
||||
fn load(&self, value: &'a str) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: generic WIP interface traits are not supported
|
||||
--> tests/ui/custom_lifetime.rs:4:24
|
||||
|
|
||||
4 | pub trait BorrowedValue<'a> {
|
||||
| ^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/custom_lifetime.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,9 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait DuplicateOperation {
|
||||
fn load(&self) -> OperationResult<String>;
|
||||
fn load(&self, other: String) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: duplicate operation name `load`
|
||||
--> tests/ui/duplicate_operation.rs:6:8
|
||||
|
|
||||
6 | fn load(&self, other: String) -> OperationResult<String>;
|
||||
| ^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/duplicate_operation.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait GenericOperation {
|
||||
fn load<T>(&self, value: T) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: generic operations are not supported
|
||||
--> tests/ui/generic_method.rs:5:12
|
||||
|
|
||||
5 | fn load<T>(&self, value: T) -> OperationResult<String>;
|
||||
| ^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/generic_method.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait Inherited: Send {
|
||||
fn load(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,13 @@
|
||||
error: WIP interface trait inheritance is not supported
|
||||
--> tests/ui/inherited_trait.rs:4:22
|
||||
|
|
||||
4 | pub trait Inherited: Send {
|
||||
| ^^^^
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/inherited_trait.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,9 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
enum MixedEnum {
|
||||
Empty,
|
||||
Payload(String),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:4:1
|
||||
|
|
||||
4 | enum MixedEnum {
|
||||
| ^^^^
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
trait PrivateInterface {
|
||||
fn load(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,15 @@
|
||||
error: a WIP interface trait must be public
|
||||
--> tests/ui/private_trait.rs:3:1
|
||||
|
|
||||
3 | #[interface]
|
||||
| ^^^^^^^^^^^^
|
||||
|
|
||||
= note: this error originates in the attribute macro `interface` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
warning: unused import: `OperationResult`
|
||||
--> tests/ui/private_trait.rs:1:21
|
||||
|
|
||||
1 | use wip_interface::{OperationResult, interface};
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
|
||||
@@ -0,0 +1,6 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
struct TupleDto(String, String);
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: `WipType` supports only structs with named fields
|
||||
--> tests/ui/tuple_dto.rs:4:16
|
||||
|
|
||||
4 | struct TupleDto(String, String);
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait UnsupportedType {
|
||||
fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,41 @@
|
||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||
--> tests/ui/unsupported_type.rs:5:26
|
||||
|
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
|
||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||
--> tests/ui/unsupported_type.rs:5:26
|
||||
|
|
||||
3 | #[interface]
|
||||
| ------------ required by a bound introduced by this call
|
||||
4 | pub trait UnsupportedType {
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
|
||||
| ^^^^^^^ required by this bound in `RecordDecoder::required`
|
||||
Reference in New Issue
Block a user