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:
2026-09-28 23:11:17 +09:00
parent 6b6e96c303
commit 18ac8844b0
32 changed files with 2991 additions and 1 deletions
+157
View File
@@ -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");
}
+218
View File
@@ -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`