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:
@@ -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