#![cfg_attr(all(coverage, test), feature(coverage_attribute))]
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::fold::Fold;
use syn::{Data, DeriveInput, Fields, FnArg, ItemFn, Pat, ReturnType, Type, parse_macro_input};
#[proc_macro]
pub fn contract(input: TokenStream) -> TokenStream {
let tools = parse_macro_input!(input with syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated);
if tools.is_empty() {
return syn::Error::new(
proc_macro2::Span::call_site(),
"contract! takes the #[tool] functions whose contract it generates",
)
.to_compile_error()
.into();
}
let factories = tools.into_iter().map(|mut path| {
if let Some(last) = path.segments.last_mut() {
last.ident = format_ident!("__flow_tool_{}", last.ident, span = last.ident.span());
}
quote! { #path() }
});
quote! {
::flow_toolkit::__bridge::contract_of(
::core::env!("CARGO_MANIFEST_DIR"),
::std::vec![#(#factories),*],
)
}
.into()
}
#[proc_macro_attribute]
pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
let function = parse_macro_input!(item as ItemFn);
match expand_tool(&attr.into(), &function) {
Ok(tokens) => tokens.into(),
Err(error) => error.to_compile_error().into(),
}
}
fn type_parameters(generics: &syn::Generics) -> syn::Result<Vec<syn::Ident>> {
generics.params.iter().map(|param| match param {
syn::GenericParam::Type(param) if param.default.is_none() => Ok(param.ident.clone()),
_ => Err(syn::Error::new_spanned(param, "Flow boundaries accept type parameters without defaults; lifetimes and const parameters are unsupported")),
}).collect()
}
#[derive(Clone, Copy)]
enum Erased {
Metadata,
Runtime,
}
struct Erasure<'n> {
names: &'n [syn::Ident],
into: Erased,
}
impl Fold for Erasure<'_> {
fn fold_type(&mut self, ty: Type) -> Type {
if let Type::Path(path) = &ty
&& path.qself.is_none()
&& path.path.segments.len() == 1
&& let Some(index) = self.names.iter().position(|name| path.path.is_ident(name))
{
return match self.into {
Erased::Metadata => {
syn::parse_quote!(::flow_toolkit::__bridge::wire::Param<#index>)
}
Erased::Runtime => syn::parse_quote!(::flow_toolkit::Encoded),
};
}
syn::fold::fold_type(self, ty)
}
}
fn erased(names: &[syn::Ident], into: Erased, ty: &Type) -> Type {
Erasure { names, into }.fold_type(ty.clone())
}
struct Adapted {
arguments: Vec<proc_macro2::TokenStream>,
decoded: Vec<proc_macro2::TokenStream>,
declared: Vec<proc_macro2::TokenStream>,
}
fn parameter_default(
attrs: &[syn::Attribute],
ty: &Type,
) -> syn::Result<Option<proc_macro2::TokenStream>> {
let mut found = None;
for attr in attrs.iter().filter(|attr| attr.path().is_ident("flow")) {
let expected = || syn::Error::new_spanned(attr, "expected #[flow(default = value)]");
let value = attr
.parse_args::<syn::MetaNameValue>()
.map_err(|_| expected())?;
if !value.path.is_ident("default") {
return Err(expected());
}
if found.is_some() {
return Err(syn::Error::new_spanned(attr, "a parameter has one default"));
}
found = Some(default_value(&value.value, ty)?);
}
Ok(found)
}
fn default_literal(
expr: &syn::Expr,
ty: &proc_macro2::TokenStream,
) -> syn::Result<proc_macro2::TokenStream> {
let span = syn::spanned::Spanned::span(expr);
let refused = || {
syn::Error::new_spanned(
expr,
"a default is an integer, boolean or string literal, `None`, `Some` of a literal, a newtype's constructor applied to one, or a payload-free constructor of the parameter's enum written bare",
)
};
let (negative, lit) = match expr {
syn::Expr::Call(call)
if call.args.len() == 1
&& matches!(&*call.func, syn::Expr::Path(path) if !path.path.is_ident("Some")) =>
{
let constructor = &call.func;
let base = quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultNewtype>::Base };
let inner = default_value(&call.args[0], &syn::parse_quote!(#base))?;
return Ok(quote::quote_spanned! { span =>
{
const _: () = {
::core::assert!(
::flow_toolkit::__bridge::constructor_reachable::<#ty>(::core::module_path!()),
"this default needs a newtype's private constructor from another module, which the contract cannot write; make the newtype's field `pub`, or declare the Tool in the newtype's module",
);
};
<#ty as ::flow_toolkit::__bridge::DefaultNewtype>::wrap(#inner, #constructor)
}
});
}
syn::Expr::Lit(syn::ExprLit { lit, .. }) => (false, lit),
syn::Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(_),
expr: inner,
..
}) => match &**inner {
syn::Expr::Lit(syn::ExprLit {
lit: lit @ syn::Lit::Int(_),
..
}) => (true, lit),
_ => return Err(refused()),
},
_ => return Err(refused()),
};
match lit {
syn::Lit::Int(int) => {
if !int.suffix().is_empty() {
return Err(syn::Error::new_spanned(
int,
"an integer default takes no suffix: its type is the parameter's",
));
}
let digits = int.base10_digits();
let (signed, magnitude) = match digits.strip_prefix('-') {
Some(magnitude) => (!negative, magnitude),
None => (negative, digits),
};
let text = if signed && magnitude.bytes().any(|digit| digit != b'0') {
format!("-{magnitude}")
} else {
magnitude.to_owned()
};
Ok(
quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultInt>::int(#text) },
)
}
syn::Lit::Bool(flag) => {
let flag = flag.value;
Ok(
quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultBool>::bool(#flag) },
)
}
syn::Lit::Str(text) => {
let text = text.value();
Ok(
quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultText>::text(#text) },
)
}
_ => Err(refused()),
}
}
fn default_value(value: &syn::Expr, ty: &Type) -> syn::Result<proc_macro2::TokenStream> {
let span = syn::spanned::Spanned::span(value);
let declared = ty;
let ty = quote! { #ty };
match value {
syn::Expr::Path(path) if path.path.is_ident("None") => Ok(quote::quote_spanned! { span =>
<#ty as ::flow_toolkit::__bridge::DefaultOption>::none()
}),
syn::Expr::Call(call)
if matches!(&*call.func, syn::Expr::Path(path) if path.path.is_ident("Some"))
&& call.args.len() == 1 =>
{
let inner = quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultOption>::Inner };
let literal = default_literal(&call.args[0], &inner)?;
Ok(quote::quote_spanned! { span =>
<#ty as ::flow_toolkit::__bridge::DefaultOption>::some(#literal)
})
}
syn::Expr::Path(path) if constructor_name(path).is_some() => {
constructor_default(path, declared)
}
other => default_literal(other, &ty),
}
}
fn constructor_name(path: &syn::ExprPath) -> Option<&syn::Ident> {
let ident = path.path.get_ident()?;
(path.qself.is_none()
&& path.attrs.is_empty()
&& ident != "None"
&& ident
.to_string()
.starts_with(|c: char| c.is_ascii_uppercase()))
.then_some(ident)
}
fn constructor_default(path: &syn::ExprPath, ty: &Type) -> syn::Result<proc_macro2::TokenStream> {
let ident = constructor_name(path).expect("checked by the caller");
let refused = || {
syn::Error::new_spanned(
path,
"a constructor default is written on a parameter of its enum's type, named by a plain path",
)
};
let Type::Path(syn::TypePath {
qself: None,
path: enum_path,
..
}) = ty
else {
return Err(refused());
};
if enum_path
.segments
.iter()
.any(|segment| !segment.arguments.is_none())
{
return Err(refused());
}
let span = ident.span();
let name = ident.to_string();
Ok(quote::quote_spanned! { span => {
#[allow(unreachable_patterns, reason = "an enum may have this one constructor")]
let _ = |value: #ty| matches!(value, #enum_path::#ident);
::flow_toolkit::__bridge::Constant::Constructor(::std::string::String::from(#name))
}})
}
fn tool_parameters(function: &ItemFn, generic: &[syn::Ident]) -> syn::Result<Adapted> {
let mut arguments = Vec::new();
let mut decoded = Vec::new();
let mut parameters = Vec::new();
let mut context_seen = false;
let mut optional_seen = false;
for argument in &function.sig.inputs {
let FnArg::Typed(argument) = argument else {
return Err(syn::Error::new_spanned(
argument,
"tools cannot have a receiver",
));
};
let Pat::Ident(pattern) = &*argument.pat else {
return Err(syn::Error::new_spanned(
argument,
"tool parameters need simple names",
));
};
let param = pattern
.ident
.to_string()
.trim_start_matches("r#")
.to_owned();
let ty = &erased(generic, Erased::Runtime, &argument.ty);
let metadata = &erased(generic, Erased::Metadata, &argument.ty);
let (context_type, borrowed) = match ty {
Type::Reference(reference) => (&*reference.elem, true),
other => (other, false),
};
if matches!(context_type,Type::Path(path) if path.path.segments.last().is_some_and(|s|s.ident=="Context"))
{
if context_seen {
return Err(syn::Error::new_spanned(
argument,
"a tool accepts at most one invocation Context",
));
}
if argument
.attrs
.iter()
.any(|attr| attr.path().is_ident("flow"))
{
return Err(syn::Error::new_spanned(
argument,
"the invocation Context is no parameter and takes no default",
));
}
context_seen = true;
arguments.push(if borrowed {
quote! { _context }
} else {
quote! { _context.clone() }
});
continue;
}
let flow_type = quote! { types.form(<#metadata as ::flow_toolkit::Shaped>::FORM) };
match parameter_default(&argument.attrs, metadata)? {
Some(default) => {
optional_seen = true;
parameters.push(quote! {
::flow_toolkit::__bridge::Param {
name: #param.to_owned(),
ty: #flow_type,
default: ::core::option::Option::Some(#default),
}
});
}
None if optional_seen => {
return Err(syn::Error::new_spanned(
argument,
"a parameter without a default follows one with a default: optional parameters come last",
));
}
None => parameters.push(quote! {
::flow_toolkit::__bridge::Param {
name: #param.to_owned(),
ty: #flow_type,
default: ::core::option::Option::None,
}
}),
}
let local = format_ident!("__flow_argument_{}", decoded.len());
let take = tried("e! { args.take::<#ty>(#param) });
decoded.push(quote! { let #local = #take; });
arguments.push(quote! { #local });
}
Ok(Adapted {
arguments,
decoded,
declared: parameters,
})
}
enum Missing {
Never,
ToolProblem,
NoAnswer,
Refusal,
}
fn result_type(function: &ItemFn) -> syn::Result<(Type, Missing)> {
let ReturnType::Type(_, result) = &function.sig.output else {
return Ok((syn::parse_quote!(()), Missing::Never));
};
if let Type::Reference(_) = &**result {
return Err(syn::Error::new_spanned(
result,
"a tool returns an owned value: R, Result<R, ToolProblem>, Result<R, NoAnswer> or Result<R, Refusal<E>>",
));
}
if let Type::Path(path) = &**result
&& path.qself.is_none()
&& let Some(segment) = path.path.segments.last()
&& segment.ident == "Result"
&& let syn::PathArguments::AngleBracketed(parts) = &segment.arguments
&& parts.args.len() == 2
&& let syn::GenericArgument::Type(declared) = &parts.args[0]
&& let syn::GenericArgument::Type(Type::Path(error)) = &parts.args[1]
&& error.qself.is_none()
&& let Some(last) = error.path.segments.last()
{
if last.ident == "Refusal" {
if let syn::PathArguments::AngleBracketed(own) = &last.arguments
&& own.args.len() == 1
&& let Some(syn::GenericArgument::Type(own)) = own.args.first()
{
return Ok((
syn::parse_quote!(::core::result::Result<#declared, #own>),
Missing::Refusal,
));
}
return Err(syn::Error::new_spanned(
error,
"Refusal takes the Tool's own error type: Refusal<E>",
));
}
let missing = if last.ident == "ToolProblem" {
Missing::ToolProblem
} else if last.ident == "NoAnswer" {
Missing::NoAnswer
} else {
return Ok(((**result).clone(), Missing::Never));
};
if !last.arguments.is_none() {
return Err(syn::Error::new_spanned(
error,
"ToolProblem and NoAnswer take no type argument: a Tool's own errors are values of its result type R",
));
}
return Ok((declared.clone(), missing));
}
Ok(((**result).clone(), Missing::Never))
}
fn doc_text(attrs: &[syn::Attribute]) -> String {
attrs
.iter()
.filter(|a| a.path().is_ident("doc"))
.filter_map(|a| match &a.meta {
syn::Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
}),
..
}) => Some(s.value().trim().to_owned()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
fn tried(expression: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
quote! {
match #expression {
::core::result::Result::Ok(__flow_value) => __flow_value,
::core::result::Result::Err(__flow_error) => {
return ::core::result::Result::Err(::core::convert::From::from(__flow_error))
}
}
}
}
fn tool_declaration(
decoded: &[proc_macro2::TokenStream],
invoke: &proc_macro2::TokenStream,
result: &Type,
) -> proc_macro2::TokenStream {
let finish = tried("e! { args.finish() });
quote! { ::flow_toolkit::__bridge::typed::<#result, _>(|_context, args| {
#(#decoded)*
#finish;
Ok(#invoke)
}) }
}
fn expand_tool(
attr: &proc_macro2::TokenStream,
function: &ItemFn,
) -> syn::Result<proc_macro2::TokenStream> {
if !attr.is_empty() {
return Err(syn::Error::new_spanned(
function,
"#[tool] takes no arguments",
));
}
if matches!(function.sig.safety, syn::Safety::Unsafe(_)) || function.sig.abi.is_some() {
return Err(syn::Error::new_spanned(
&function.sig,
"tools must be safe Rust functions",
));
}
let generic = type_parameters(&function.sig.generics)?;
let substitutions = generic
.iter()
.map(|_| quote! { ::flow_toolkit::Encoded })
.collect::<Vec<_>>();
if !matches!(function.vis, syn::Visibility::Public(_)) {
return Err(syn::Error::new_spanned(
&function.vis,
"tools must be public",
));
}
let name = &function.sig.ident;
let wire_name = name.to_string().trim_start_matches("r#").to_owned();
let factory = format_ident!("__flow_tool_{}", name);
let Adapted {
arguments,
decoded,
declared: parameters,
} = tool_parameters(function, &generic)?;
let (declared, missing) = result_type(function)?;
let result = erased(&generic, Erased::Runtime, &declared);
let metadata = erased(&generic, Erased::Metadata, &declared);
let invoke = if generic.is_empty() {
quote! { #name(#(#arguments),*) }
} else {
quote! { #name::<#(#substitutions),*>(#(#arguments),*) }
};
let invoke = if function.sig.asyncness.is_some() {
quote! { ::flow_toolkit::__bridge::block_on(#invoke) }
} else {
invoke
};
let invoke = match missing {
Missing::NoAnswer => invoke,
Missing::Refusal => quote! { ::flow_toolkit::__bridge::refused(#invoke) },
Missing::ToolProblem => quote! { #invoke.map_err(::flow_toolkit::NoAnswer::Problem) },
Missing::Never => {
quote! { ::std::result::Result::<_, ::flow_toolkit::NoAnswer>::Ok(#invoke) }
}
};
let declaration = tool_declaration(&decoded, &invoke, &result);
let generic_names = generic.iter().map(ToString::to_string).collect::<Vec<_>>();
let docs = doc_text(&function.attrs);
let origin = quote! {
::flow_toolkit::__bridge::Origin {
module: ::core::module_path!(),
file: ::core::file!(),
line: ::core::line!(),
}
};
let function = without_parameter_attributes(function);
Ok(quote! {
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
#function
#[doc(hidden)]
pub fn #factory() -> ::flow_toolkit::__bridge::Function {
let mut types = ::flow_toolkit::__bridge::Types::default();
types.parameters(&[#(#generic_names),*]);
let params = vec![#(#parameters),*];
let result = types.form(<#metadata as ::flow_toolkit::Shaped>::FORM);
types.end_parameters();
::flow_toolkit::__bridge::function((#wire_name, &[#(#generic_names),*]), #origin, #docs, params, result, types,
|| #declaration)
}
})
}
fn without_parameter_attributes(function: &ItemFn) -> ItemFn {
let mut function = function.clone();
for argument in &mut function.sig.inputs {
if let FnArg::Typed(argument) = argument {
argument.attrs.retain(|attr| !attr.path().is_ident("flow"));
}
}
function
}
#[proc_macro_derive(Flow, attributes(flow))]
pub fn flow(item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as DeriveInput);
match expand_data(&input) {
Ok(tokens) => tokens.into(),
Err(error) => error.to_compile_error().into(),
}
}
#[proc_macro_derive(Handle)]
pub fn handle(item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as DeriveInput);
match expand_handle(&input) {
Ok(tokens) => tokens.into(),
Err(error) => error.to_compile_error().into(),
}
}
fn field_ident(field: &syn::Field) -> syn::Result<&syn::Ident> {
field
.ident
.as_ref()
.ok_or_else(|| syn::Error::new_spanned(field, "expected a named field"))
}
fn field_name(field: &syn::Field) -> syn::Result<String> {
let mut renamed = None;
for attr in field
.attrs
.iter()
.filter(|attr| attr.path().is_ident("flow"))
{
let expected = || syn::Error::new_spanned(attr, "expected #[flow(name = \"...\")]");
let value = attr
.parse_args::<syn::MetaNameValue>()
.map_err(|_| expected())?;
if !value.path.is_ident("name") {
return Err(expected());
}
let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(text),
..
}) = &value.value
else {
return Err(syn::Error::new_spanned(
&value.value,
"`name` takes a string literal",
));
};
if renamed.replace(text.value()).is_some() {
return Err(syn::Error::new_spanned(attr, "a field is renamed once"));
}
}
match renamed {
Some(name) => Ok(name),
None => Ok(field_ident(field)?
.to_string()
.trim_start_matches("r#")
.to_owned()),
}
}
fn public(vis: &syn::Visibility) -> bool {
matches!(vis, syn::Visibility::Public(_))
}
fn std_declaration(attrs: &[syn::Attribute]) -> syn::Result<Option<(String, String)>> {
let mut named = None;
for attr in attrs.iter().filter(|attr| attr.path().is_ident("flow")) {
let expected = || {
syn::Error::new_spanned(
attr,
"expected #[flow(std = \"module.Name\")], naming a std declaration; a host type derives Handle",
)
};
let value = attr
.parse_args::<syn::MetaNameValue>()
.map_err(|_| expected())?;
if !value.path.is_ident("std") {
return Err(expected());
}
let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(text),
..
}) = &value.value
else {
return Err(syn::Error::new_spanned(
&value.value,
"`std` takes a string literal, \"module.Name\"",
));
};
let written = text.value();
let Some((module, name)) = written
.split_once('.')
.filter(|declared| flow_types::STD_TYPES.iter().any(|known| known == declared))
else {
return Err(syn::Error::new_spanned(
text,
format!(
"`{written}` names no std declaration: expected \"module.Name\", such as \"code.Bundle\""
),
));
};
if named
.replace((module.to_owned(), name.to_owned()))
.is_some()
{
return Err(syn::Error::new_spanned(
attr,
"a type names one std declaration",
));
}
}
Ok(named)
}
fn std_data(
input: &DeriveInput,
parameters: &[syn::Ident],
(module, std_name): &(String, String),
) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
let shape = || {
syn::Error::new_spanned(
input,
"a std declaration's Rust type is a tuple struct holding its value in one flow_toolkit::Encoded field, beside any PhantomData",
)
};
let Data::Struct(syn::DataStruct {
fields: Fields::Unnamed(fields),
..
}) = &input.data
else {
return Err(shape());
};
let mut held = fields
.unnamed
.iter()
.enumerate()
.filter(|(_, field)| !phantom(&field.ty));
let (Some((index, field)), None) = (held.next(), held.next()) else {
return Err(shape());
};
if !matches!(&field.ty, Type::Path(path) if path.qself.is_none()
&& path.path.segments.last().is_some_and(|segment| segment.ident == "Encoded"))
{
return Err(syn::Error::new_spanned(
&field.ty,
"a std declaration's value is held in a flow_toolkit::Encoded",
));
}
let at = syn::Index::from(index);
let parts = (0..fields.unnamed.len()).map(|position| {
if position == index {
quote! { value }
} else {
quote! { ::core::marker::PhantomData }
}
});
let mut generics = input.generics.clone();
for parameter in generics.type_params_mut() {
parameter
.bounds
.push(syn::parse_quote!(::flow_toolkit::Shaped));
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
Ok(quote! {
impl #impl_generics ::flow_toolkit::Shaped for #name #ty_generics #where_clause {
const FORM: ::flow_toolkit::__bridge::wire::WireForm = ::flow_toolkit::__bridge::wire::WireForm::Std {
module: #module,
name: #std_name,
args: &[#(::flow_toolkit::__bridge::wire::form_of::<#parameters>),*],
};
fn write_at(
&self,
out: &mut ::flow_toolkit::__bridge::wire::ValueWriter<'_, '_>,
ty: &::flow_toolkit::__bridge::wire::Type,
) -> ::core::result::Result<(), ::flow_toolkit::__bridge::EncodeError> {
::flow_toolkit::Shaped::write_at(&self.#at, out, ty)
}
fn read_at(
input: &mut ::flow_toolkit::__bridge::wire::ValueReader<'_, '_, '_>,
ty: &::flow_toolkit::__bridge::wire::Type,
) -> ::core::result::Result<Self, ::flow_toolkit::DecodeError> {
<::flow_toolkit::Encoded as ::flow_toolkit::Shaped>::read_at(input, ty)
.map(|value| Self(#(#parts),*))
}
}
})
}
#[expect(
clippy::fn_params_excessive_bools,
reason = "whether a member is public is the one flag its note carries"
)]
fn note(
attrs: &[syn::Attribute],
public: bool,
fields: &[proc_macro2::TokenStream],
) -> proc_macro2::TokenStream {
let docs = doc_text(attrs);
quote! {
::flow_toolkit::__bridge::wire::Note { docs: #docs, public: #public, fields: &[#(#fields),*] }
}
}
fn notes(input: &DeriveInput, members: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
let docs = doc_text(&input.attrs);
quote! {
::flow_toolkit::__bridge::wire::Notes {
module: ::core::module_path!(),
file: ::core::file!(),
line: ::core::line!(),
docs: #docs,
members: &[#(#members),*],
}
}
}
fn wire_head(input: &DeriveInput, parameters: &[syn::Ident]) -> proc_macro2::TokenStream {
let name = &input.ident;
let positions = (0..parameters.len()).map(proc_macro2::Literal::usize_unsuffixed);
let mut predicates = input
.generics
.type_params()
.filter(|parameter| !parameter.bounds.is_empty())
.map(|parameter| {
let (ident, bounds) = (¶meter.ident, ¶meter.bounds);
quote! { #ident: #bounds, }
})
.collect::<Vec<_>>();
if let Some(clause) = &input.generics.where_clause {
predicates.extend(
clause
.predicates
.iter()
.map(|predicate| quote! { #predicate, }),
);
}
let bounded = if predicates.is_empty() {
quote! {}
} else {
quote! { where [#(#predicates)*] }
};
quote! { impl #name [#(#parameters = #positions),*] #bounded }
}
fn expand_handle(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
if !input.generics.params.is_empty()
|| !matches!(&input.data, Data::Struct(data) if matches!(&data.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1 && matches!(&fields.unnamed[0].ty, Type::Path(path) if path.path.is_ident("String"))))
{
return Err(syn::Error::new_spanned(
input,
"a host type is a nongeneric tuple struct with one String field",
));
}
let notes = notes(input, &[]);
Ok(quote! {
impl ::flow_toolkit::__bridge::wire::Declared for #name {
const SHAPE: ::flow_toolkit::__bridge::wire::Shape = ::flow_toolkit::__bridge::wire::Shape {
name: ::core::stringify!(#name),
params: &[],
layout: ::flow_toolkit::__bridge::wire::Layout::Host,
notes: ::core::option::Option::Some(&#notes),
};
}
impl ::flow_toolkit::Shaped for #name {
const FORM: ::flow_toolkit::__bridge::wire::WireForm = ::flow_toolkit::__bridge::wire::WireForm::Declared(
<Self as ::flow_toolkit::__bridge::wire::Declared>::shape,
);
fn write_at(
&self,
out: &mut ::flow_toolkit::__bridge::wire::ValueWriter<'_, '_>,
ty: &::flow_toolkit::__bridge::wire::Type,
) -> ::core::result::Result<(), ::flow_toolkit::__bridge::EncodeError> {
out.host(ty, &self.0)
}
fn read_at(
input: &mut ::flow_toolkit::__bridge::wire::ValueReader<'_, '_, '_>,
ty: &::flow_toolkit::__bridge::wire::Type,
) -> ::core::result::Result<Self, ::flow_toolkit::DecodeError> {
input.host(ty).map(|token| Self(token.to_owned()))
}
}
})
}
fn phantom(ty: &Type) -> bool {
matches!(ty, Type::Path(path) if path.qself.is_none()
&& path.path.segments.last().is_some_and(|segment| segment.ident == "PhantomData"))
}
fn newtype_data(
input: &DeriveInput,
parameters: &[syn::Ident],
fields: &syn::FieldsUnnamed,
) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
let mut held = fields
.unnamed
.iter()
.enumerate()
.filter(|(_, field)| !phantom(&field.ty));
let (Some((index, field)), None) = (held.next(), held.next()) else {
return Err(syn::Error::new_spanned(
fields,
"a Flow newtype is a tuple struct with one field beside any PhantomData; a record needs named fields",
));
};
if let Some(attr) = field.attrs.iter().find(|attr| attr.path().is_ident("flow")) {
return Err(syn::Error::new_spanned(
attr,
"a newtype's field has no Flow name to rename",
));
}
let base = &field.ty;
let public = public(&field.vis);
let at = syn::Index::from(index);
let phantoms = (0..fields.unnamed.len())
.filter(|position| *position != index)
.map(syn::Index::from);
let declared = wire_head(input, parameters);
let notes = notes(input, &[note(&[], public, &[])]);
let mut generics = input.generics.clone();
for parameter in generics.type_params_mut() {
parameter
.bounds
.push(syn::parse_quote!(::flow_toolkit::Shaped));
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
Ok(quote! {
::flow_toolkit::__bridge::wire_impl! {
#declared newtype { #at: #base } phantom [#(#phantoms),*] notes #notes
}
impl #impl_generics ::flow_toolkit::__bridge::DefaultNewtype for #name #ty_generics #where_clause {
const PUBLIC: bool = #public;
const MODULE: &'static str = ::core::module_path!();
type Base = #base;
fn written() -> ::flow_toolkit::__bridge::TypeRef<::flow_toolkit::__bridge::Owner> {
::flow_toolkit::__bridge::TypeRef::qualified(
::flow_toolkit::__bridge::Owner::Rust(::core::module_path!()),
::core::stringify!(#name),
)
}
}
})
}
fn record_fields(
fields: &syn::FieldsNamed,
) -> syn::Result<(
Vec<proc_macro2::TokenStream>,
Vec<&syn::Ident>,
Vec<proc_macro2::TokenStream>,
)> {
let mut listed = Vec::new();
let mut phantoms = Vec::new();
let mut members = Vec::new();
for field in &fields.named {
let ident = field_ident(field)?;
if phantom(&field.ty) {
phantoms.push(ident);
continue;
}
let flow = field_name(field)?;
let ty = &field.ty;
listed.push(quote! { #ident #flow: #ty });
members.push(note(&field.attrs, public(&field.vis), &[]));
}
Ok((listed, phantoms, members))
}
fn enum_constructors(
data: &syn::DataEnum,
) -> syn::Result<(Vec<proc_macro2::TokenStream>, Vec<proc_macro2::TokenStream>)> {
let mut listed = Vec::new();
let mut members = Vec::new();
for (number, variant) in data.variants.iter().enumerate() {
let ident = &variant.ident;
let (kind, parts, fields) = match &variant.fields {
Fields::Unit => (quote! { Empty }, Vec::new(), Vec::new()),
Fields::Unnamed(fields) => (
quote! { Positional },
fields
.unnamed
.iter()
.enumerate()
.map(|(at, field)| {
let (member, bind, ty) =
(syn::Index::from(at), format_ident!("p{at}"), &field.ty);
quote! { #member (#bind) "": #ty }
})
.collect(),
Vec::new(),
),
Fields::Named(fields) => {
let mut parts = Vec::new();
let mut notes = Vec::new();
for (at, field) in fields.named.iter().enumerate() {
let (member, bind, ty) =
(field_ident(field)?, format_ident!("p{at}"), &field.ty);
let flow = field_name(field)?;
parts.push(quote! { #member (#bind) #flow: #ty });
notes.push(note(&field.attrs, true, &[]));
}
(quote! { Named }, parts, notes)
}
};
let number = proc_macro2::Literal::usize_unsuffixed(number);
listed.push(quote! { #ident = #number #kind { #(#parts),* } });
members.push(note(&variant.attrs, true, &fields));
}
Ok((listed, members))
}
fn expand_data(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let parameters = type_parameters(&input.generics)?;
if let Some(std) = std_declaration(&input.attrs)? {
return std_data(input, ¶meters, &std);
}
let head = wire_head(input, ¶meters);
match &input.data {
Data::Struct(syn::DataStruct {
fields: Fields::Unnamed(fields),
..
}) => newtype_data(input, ¶meters, fields),
Data::Struct(syn::DataStruct {
fields: Fields::Named(fields),
..
}) => {
let (listed, phantoms, members) = record_fields(fields)?;
let notes = notes(input, &members);
Ok(quote! {
::flow_toolkit::__bridge::wire_impl! {
#head record { #(#listed),* } phantom [#(#phantoms),*] notes #notes
}
})
}
Data::Struct(_) => Err(syn::Error::new_spanned(
input,
"Flow records need named fields",
)),
Data::Enum(data) => {
let (listed, members) = enum_constructors(data)?;
let notes = notes(input, &members);
Ok(quote! {
::flow_toolkit::__bridge::wire_impl! {
#head enum { #(#listed),* } notes #notes
}
})
}
Data::Union(_) => Err(syn::Error::new_spanned(
input,
"Rust unions cannot cross a Tool boundary",
)),
}
}
#[proc_macro_attribute]
pub fn lifespan(attr: TokenStream, item: TokenStream) -> TokenStream {
let function = parse_macro_input!(item as ItemFn);
match expand_lifespan(&attr, &function) {
Ok(tokens) => tokens.into(),
Err(error) => error.to_compile_error().into(),
}
}
fn expand_lifespan(attr: &TokenStream, function: &ItemFn) -> syn::Result<proc_macro2::TokenStream> {
if !attr.is_empty()
|| !function.sig.inputs.is_empty()
|| !function.sig.generics.params.is_empty()
|| matches!(function.sig.safety, syn::Safety::Unsafe(_))
|| function.sig.abi.is_some()
|| !matches!(function.vis, syn::Visibility::Public(_))
{
return Err(syn::Error::new_spanned(
&function.sig,
"#[lifespan] requires a public safe nongeneric zero-argument Rust function",
));
}
let name = &function.sig.ident;
let factory = format_ident!("__flow_lifespan_{}", name);
let invoke = if function.sig.asyncness.is_some() {
quote! { ::flow_toolkit::__bridge::block_on(#name()) }
} else {
quote! { #name() }
};
Ok(quote! {
#function
#[doc(hidden)]
pub fn #factory()->::std::result::Result<::flow_toolkit::__bridge::Lifespan,::flow_toolkit::StartError> {
(#invoke).map(::flow_toolkit::Resource::into_lifespan).map_err(::std::convert::Into::into)
}
})
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
use syn::parse::Parser as _;
use syn::parse_quote;
#[test]
fn lifespan_adapter_preserves_sync_and_async_factories_and_rejects_parameters() {
for function in [
parse_quote!(
pub fn open() -> Result<Resource<Pool>, String> {
unreachable!()
}
),
parse_quote!(
pub async fn open() -> Result<Resource<Pool>, String> {
unreachable!()
}
),
] {
syn::parse2::<syn::File>(expand_lifespan(&TokenStream::new(), &function).unwrap())
.unwrap();
}
for function in [
parse_quote!(
fn hidden() -> Result<Resource<Pool>, String> {
unreachable!()
}
),
parse_quote!(
pub fn with_arg(value: String) -> Result<Resource<Pool>, String> {
unreachable!()
}
),
parse_quote!(
pub fn generic<T>() -> Result<Resource<T>, String> {
unreachable!()
}
),
] {
assert!(
expand_lifespan(&TokenStream::new(), &function)
.unwrap_err()
.to_string()
.contains("zero-argument")
);
}
}
#[test]
fn a_return_type_other_than_result_of_a_problem_or_no_answer_is_declared_whole() {
for (function, declared) in [
(
parse_quote!(
pub fn plain() -> String {
String::new()
}
),
":: std :: result :: Result :: < _ , :: flow_toolkit :: NoAnswer > :: Ok",
),
(
parse_quote!(
pub fn nothing() {}
),
"types . form (< () as :: flow_toolkit :: Shaped > :: FORM)",
),
(
parse_quote!(
pub fn domain() -> Result<String, Declined> {
Ok(String::new())
}
),
"types . form (< Result < String , Declined > as :: flow_toolkit :: Shaped > :: FORM)",
),
(
parse_quote!(
pub fn odd() -> Result<'a, String> {
unreachable!()
}
),
"types . form (< Result < 'a , String > as :: flow_toolkit :: Shaped > :: FORM)",
),
(
parse_quote!(
pub fn problems() -> Result<Result<String, Declined>, flow_toolkit::ToolProblem>
{
Ok(Ok(String::new()))
}
),
"types . form (< Result < String , Declined > as :: flow_toolkit :: Shaped > :: FORM)",
),
(
parse_quote!(
pub fn holds() -> Result<String, NoAnswer> {
Ok(String::new())
}
),
"types . form (< String as :: flow_toolkit :: Shaped > :: FORM)",
),
] {
let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
.expect("any owned return type is a Tool's result")
.to_string();
assert!(source.contains(declared), "{declared} in {source}");
}
}
#[test]
fn a_default_is_written_through_the_trait_of_its_kind_and_checked_by_the_compiler() {
let function: ItemFn = parse_quote!(
pub fn search(
context: &Context,
query: String,
#[flow(default = 20)] limit: Int,
#[flow(default = -3)] offset: Int,
#[flow(default = true)] exact: bool,
#[flow(default = "a \"b\"")] label: String,
#[flow(default = None)] owner: Option<String>,
#[flow(default = Some(5))] page: Option<Int>,
#[flow(default = "x")] tag: Option<String>,
) -> Vec<String> {
Vec::new()
}
);
let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
.expect("defaults of every kind")
.to_string();
for expected in [
"< Int as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"20\")",
"< Int as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"-3\")",
"< bool as :: flow_toolkit :: __bridge :: DefaultBool > :: bool (true)",
"< String as :: flow_toolkit :: __bridge :: DefaultText > :: text (\"a \\\"b\\\"\")",
"< Option < String > as :: flow_toolkit :: __bridge :: DefaultOption > :: none ()",
"< Option < Int > as :: flow_toolkit :: __bridge :: DefaultOption > :: some (< < Option < Int > as :: flow_toolkit :: __bridge :: DefaultOption > :: Inner as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"5\"))",
"< Option < String > as :: flow_toolkit :: __bridge :: DefaultText > :: text (\"x\")",
] {
assert!(source.contains(expected), "{expected} in {source}");
}
assert!(
!source.contains("# [flow"),
"the attribute is read by #[tool] and not left for Rust: {source}"
);
}
#[test]
fn a_constructor_default_is_written_bare_and_checked_as_a_unit_pattern_of_the_enum() {
let function: ItemFn = parse_quote!(
pub fn note(message: String, #[flow(default = Info)] level: Level) {}
);
let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
.expect("a constructor default")
.to_string();
for expected in [
"matches ! (value , Level :: Info)",
":: std :: string :: String :: from (\"Info\")",
] {
assert!(source.contains(expected), "{expected} in {source}");
}
for (function, message) in [
(
parse_quote!(
pub fn f(#[flow(default = Info)] x: Option<Level>) {}
),
"a constructor default is written on a parameter of its enum's type",
),
(
parse_quote!(
pub fn f(#[flow(default = Info)] x: <T as Tr>::Level) {}
),
"a constructor default is written on a parameter of its enum's type",
),
(
parse_quote!(
pub fn f(#[flow(default = Level::Info)] x: Level) {}
),
"or a payload-free constructor of the parameter's enum written bare",
),
(
parse_quote!(
pub fn f(#[flow(default = info)] x: Level) {}
),
"or a payload-free constructor of the parameter's enum written bare",
),
] {
let error = expand_tool(&proc_macro2::TokenStream::new(), &function)
.expect_err("refused before generating code");
assert!(error.to_string().contains(message), "{message}: {error}");
}
}
#[test]
fn a_default_that_no_contract_could_write_is_a_compile_error() {
for (function, message) in [
(
parse_quote!(
pub fn f(#[flow(default = 1.5)] x: Decimal) {}
),
"a default is an integer, boolean or string literal",
),
(
parse_quote!(
pub fn f(#[flow(default = make())] x: Int) {}
),
"a default is an integer, boolean or string literal",
),
(
parse_quote!(
pub fn f(#[flow(default = -true)] x: bool) {}
),
"a default is an integer, boolean or string literal",
),
(
parse_quote!(
pub fn f(#[flow(default = Some(None))] x: Option<Option<Int>>) {}
),
"a default is an integer, boolean or string literal",
),
(
parse_quote!(
pub fn f(#[flow(default = 5u8)] x: Int) {}
),
"takes no suffix",
),
(
parse_quote!(
pub fn f(#[flow(other = 5)] x: Int) {}
),
"expected #[flow(default = value)]",
),
(
parse_quote!(
pub fn f(#[flow(default)] x: Int) {}
),
"expected #[flow(default = value)]",
),
(
parse_quote!(
pub fn f(
#[flow(default = 1)]
#[flow(default = 2)]
x: Int,
) {
}
),
"a parameter has one default",
),
(
parse_quote!(
pub fn f(#[flow(default = 1)] x: Int, y: Int) {}
),
"optional parameters come last",
),
(
parse_quote!(
pub fn f(#[flow(default = 1)] context: &Context) {}
),
"takes no default",
),
] {
let error = expand_tool(&proc_macro2::TokenStream::new(), &function)
.expect_err("refused before generating code");
assert!(error.to_string().contains(message), "{message}: {error}");
}
let zero: ItemFn = parse_quote!(
pub fn f(#[flow(default = -0)] x: Int) {}
);
let source = expand_tool(&proc_macro2::TokenStream::new(), &zero)
.unwrap()
.to_string();
assert!(
source.contains("int (\"0\")"),
"negative zero is zero: {source}"
);
}
#[test]
fn nontext_doc_attributes_get_deliberate_handling() {
for function in [
parse_quote!(
#[doc = 1]
pub fn docs() -> Result<String, String> {
unreachable!()
}
),
parse_quote!(
#[doc=call()]
pub fn docs() -> Result<String, String> {
unreachable!()
}
),
parse_quote!(
#[doc(hidden)]
pub fn docs() -> Result<String, String> {
unreachable!()
}
),
] {
assert!(expand_tool(&proc_macro2::TokenStream::new(), &function).is_ok());
}
}
#[test]
fn a_tool_attribute_with_arguments_is_refused() {
let function: ItemFn = parse_quote!(
pub fn echo() -> Result<(), String> {
Ok(())
}
);
let error = expand_tool("e!(unexpected), &function).unwrap_err();
assert_eq!(error.to_string(), "#[tool] takes no arguments");
}
#[test]
fn function_adapters_reject_unrepresentable_signatures_before_generating_code() {
for (function, message) in [
(
parse_quote!(
fn hidden() -> Result<(), String> {
Ok(())
}
),
"public",
),
(
parse_quote!(
pub unsafe fn dangerous() -> Result<(), String> {
Ok(())
}
),
"safe",
),
(
parse_quote!(
pub fn generic<const N: usize>() -> Result<(), String> {
Ok(())
}
),
"type parameters",
),
(
parse_quote!(
pub extern "C" fn foreign() -> Result<(), String> {
Ok(())
}
),
"Rust functions",
),
(
parse_quote!(
pub fn method(&self) -> Result<(), String> {
Ok(())
}
),
"receiver",
),
(
parse_quote!(
pub fn pattern((a, b): (String, String)) -> Result<(), String> {
Ok(())
}
),
"simple names",
),
(
parse_quote!(
pub fn reference() -> &str {
""
}
),
"an owned value",
),
(
parse_quote!(
pub fn generic_problem() -> Result<String, ToolProblem<String>> {
Ok(String::new())
}
),
"ToolProblem and NoAnswer take no type argument",
),
(
parse_quote!(
pub fn two(a: Context, b: &Context) -> Result<(), String> {
Ok(())
}
),
"at most one",
),
] {
let error = expand_tool(&proc_macro2::TokenStream::new(), &function).unwrap_err();
assert!(error.to_string().contains(message), "{error}");
}
}
#[test]
fn sync_and_async_adapters_keep_the_original_function_and_inject_context() {
let sync: ItemFn = parse_quote!(
#[doc = "Searches documents."]
pub fn search(context: &Context, query: String) -> Result<String, ToolProblem> {
Ok(query)
}
);
let tokens = expand_tool(&proc_macro2::TokenStream::new(), &sync).unwrap();
syn::parse2::<syn::File>(tokens.clone()).unwrap();
let source = tokens.to_string();
assert!(source.contains("pub fn search"));
assert!(source.contains("__flow_tool_search"));
assert!(source.contains("Searches documents."));
let decoded = source
.find("let __flow_argument_0 = match args . take :: < String > (\"query\")")
.expect("the argument is decoded");
let finished = source
.find("args . finish ()")
.expect("leftover bytes are refused");
let invoked = source
.find("search (_context , __flow_argument_0)")
.expect("the author's function is called with the decoded argument");
assert!(decoded < finished && finished < invoked, "{source}");
let asynchronous: ItemFn = parse_quote!(
pub async fn wait(context: Context) -> Result<String, String> {
Ok(String::new())
}
);
let source = expand_tool(&proc_macro2::TokenStream::new(), &asynchronous)
.unwrap()
.to_string();
assert!(source.contains("block_on"));
assert!(source.contains("_context . clone"));
assert!(
source.contains("Result :: < _ , :: flow_toolkit :: NoAnswer > :: Ok"),
"a return type other than Result<R, ToolProblem> or Result<R, NoAnswer> is always a value: {source}"
);
}
#[test]
fn a_host_type_is_a_nongeneric_tuple_struct_holding_one_string() {
let message = "a host type is a nongeneric tuple struct with one String field";
for source in [
"pub struct Session<T>(T);",
"pub struct Session { handle: String }",
"pub struct Session(u64);",
"pub struct Session(String, String);",
"pub enum Session { Open(String) }",
] {
let input = syn::parse_str::<DeriveInput>(source).unwrap();
let error = expand_handle(&input).unwrap_err();
assert_eq!(error.to_string(), message, "{source}");
assert!(error.to_compile_error().to_string().contains(message));
}
let input = syn::parse_str::<DeriveInput>("pub struct Session(String);").unwrap();
syn::parse2::<syn::File>(expand_handle(&input).unwrap()).unwrap();
}
#[test]
fn a_flow_attribute_on_a_type_names_a_std_declaration_or_points_to_the_handle_derive() {
let message = "expected #[flow(std = \"module.Name\")], naming a std declaration; a host type derives Handle";
for source in [
"#[flow(other)] pub struct Session(String);",
"#[flow(opaque)] pub struct Session(String);",
"#[flow(name = \"code.Bundle\")] pub struct Bundle(Encoded);",
] {
let input = syn::parse_str::<DeriveInput>(source).unwrap();
assert_eq!(
expand_data(&input).unwrap_err().to_string(),
message,
"{source}"
);
}
}
#[test]
fn a_std_declaration_is_named_as_module_dot_name() {
for (source, message) in [
(
"#[flow(std = \"Bundle\")] pub struct Bundle(Encoded);",
"`Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = \"code.bundle\")] pub struct Bundle(Encoded);",
"`code.bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = \"Code.Bundle\")] pub struct Bundle(Encoded);",
"`Code.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = \"code.Bundel\")] pub struct Bundle(Encoded);",
"`code.Bundel` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = \"cod.Bundle\")] pub struct Bundle(Encoded);",
"`cod.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = \"std@v1/code.Bundle\")] pub struct Bundle(Encoded);",
"`std@v1/code.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
),
(
"#[flow(std = code.Bundle)] pub struct Bundle(Encoded);",
"`std` takes a string literal, \"module.Name\"",
),
(
"#[flow(std = \"code.Bundle\")] #[flow(std = \"code.Checked\")] pub struct Bundle(Encoded);",
"a type names one std declaration",
),
] {
let input = syn::parse_str::<DeriveInput>(source).unwrap();
assert_eq!(
expand_data(&input).unwrap_err().to_string(),
message,
"{source}"
);
}
}
#[test]
fn a_std_declarations_rust_type_holds_its_value_in_one_std_value() {
let shape = "a std declaration's Rust type is a tuple struct holding its value in one flow_toolkit::Encoded field, beside any PhantomData";
for (source, message) in [
(
"#[flow(std = \"code.Bundle\")] pub struct Bundle { value: Encoded }",
shape,
),
(
"#[flow(std = \"code.Bundle\")] pub enum Bundle { Value(Encoded) }",
shape,
),
(
"#[flow(std = \"code.Bundle\")] pub struct Bundle(Encoded, Encoded);",
shape,
),
(
"#[flow(std = \"code.Bundle\")] pub struct Bundle(String);",
"a std declaration's value is held in a flow_toolkit::Encoded",
),
] {
let input = syn::parse_str::<DeriveInput>(source).unwrap();
assert_eq!(
expand_data(&input).unwrap_err().to_string(),
message,
"{source}"
);
}
for source in [
"#[flow(std = \"code.Bundle\")] pub struct Bundle(pub flow_toolkit::Encoded);",
"#[flow(std = \"code.LocalRef\")] pub struct LocalRef<T>(Encoded, PhantomData<T>);",
] {
let input = syn::parse_str::<DeriveInput>(source).unwrap();
syn::parse2::<syn::File>(expand_data(&input).unwrap()).unwrap();
}
}
#[test]
fn record_and_enum_derives_reject_rust_shapes_without_flow_data_correspondence() {
for input in [
parse_quote!(
struct Pair(String, String);
),
parse_quote!(
struct Nothing(PhantomData<String>);
),
parse_quote!(
struct Unit;
),
parse_quote!(union Bits { bits:u64, number:f64 }),
] {
assert!(expand_data(&input).is_err());
}
let input: DeriveInput = parse_quote!(
pub enum Choice {
Empty,
One(String),
Pair(String, String),
Named { note: Option<String> },
}
);
syn::parse2::<syn::File>(expand_data(&input).unwrap()).unwrap();
}
#[test]
fn a_one_field_tuple_struct_is_a_newtype_beside_any_phantom_data() {
for input in [
parse_quote!(
pub struct UserId(pub String);
),
parse_quote!(
pub struct Labeled<T>(pub Vec<T>);
),
parse_quote!(
pub struct Id<T>(pub String, PhantomData<T>);
),
parse_quote!(
pub struct Tagged<T>(::core::marker::PhantomData<T>, pub String);
),
] {
let input: DeriveInput = input;
let expanded = expand_data(&input).unwrap();
assert!(
expanded.to_string().contains("newtype {")
&& expanded.to_string().contains("public : true"),
"{expanded}"
);
syn::parse2::<syn::File>(expanded).unwrap();
}
let renamed: DeriveInput = parse_quote!(
pub struct UserId(#[flow(name = "id")] pub String);
);
assert_eq!(
expand_data(&renamed).unwrap_err().to_string(),
"a newtype's field has no Flow name to rename"
);
}
#[test]
fn a_field_attribute_other_than_a_string_name_is_a_compile_error() {
for (input, expected) in [
(
parse_quote!(
pub struct Record {
#[flow(rename = "x")]
value: String,
}
),
"expected #[flow(name = \"...\")]",
),
(
parse_quote!(
pub struct Record {
#[flow(skip)]
value: String,
}
),
"expected #[flow(name = \"...\")]",
),
(
parse_quote!(
pub struct Record {
#[flow(name = x)]
value: String,
}
),
"`name` takes a string literal",
),
(
parse_quote!(
pub struct Record {
#[flow(name = "a")]
#[flow(name = "b")]
value: String,
}
),
"a field is renamed once",
),
(
parse_quote!(
pub enum Choice {
Named {
#[flow(nme = "x")]
value: String,
},
}
),
"expected #[flow(name = \"...\")]",
),
] {
let input: DeriveInput = input;
let error = expand_data(&input).expect_err("a malformed field attribute is refused");
assert_eq!(
error.to_string(),
expected,
"the refusal names the accepted form"
);
}
let renamed: DeriveInput = parse_quote!(
pub struct Record {
#[flow(name = "wire")]
r#value: String,
}
);
let tokens = expand_data(&renamed)
.expect("a string name is accepted")
.to_string();
assert!(
tokens.contains("\"wire\"") && !tokens.contains("\"value\""),
"the field crosses under its declared name: {tokens}"
);
let field: syn::Field = syn::Field::parse_unnamed
.parse2(quote! { String })
.expect("an unnamed field parses");
assert!(
field_name(&field).is_err() && field_ident(&field).is_err(),
"an unnamed field has no wire name"
);
}
}