Skip to main content

flow_toolkit_macros/
lib.rs

1//! Generates function boundary adapters while retaining ordinary callable Rust functions.
2
3#![cfg_attr(all(coverage, test), feature(coverage_attribute))]
4use proc_macro::TokenStream;
5use quote::{format_ident, quote};
6use syn::fold::Fold;
7use syn::{Data, DeriveInput, Fields, FnArg, ItemFn, Pat, ReturnType, Type, parse_macro_input};
8
9/// The generated contract of the listed `#[tool]` functions, for a crate's
10/// own tests: `contract!(parse, encode)` or `contract!(crate::csv::parse)`.
11///
12/// Each Tool is placed in the library module that defines it, and the
13/// library is the crate's: its root is the package's `CARGO_MANIFEST_DIR`.
14/// It expands to a `Result<flow_toolkit::Contract, flow_toolkit::ContractError>`.
15#[proc_macro]
16pub fn contract(input: TokenStream) -> TokenStream {
17    let tools = parse_macro_input!(input with syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated);
18    if tools.is_empty() {
19        return syn::Error::new(
20            proc_macro2::Span::call_site(),
21            "contract! takes the #[tool] functions whose contract it generates",
22        )
23        .to_compile_error()
24        .into();
25    }
26    let factories = tools.into_iter().map(|mut path| {
27        if let Some(last) = path.segments.last_mut() {
28            last.ident = format_ident!("__flow_tool_{}", last.ident, span = last.ident.span());
29        }
30        quote! { #path() }
31    });
32    quote! {
33        ::flow_toolkit::__bridge::contract_of(
34            ::core::env!("CARGO_MANIFEST_DIR"),
35            ::std::vec![#(#factories),*],
36        )
37    }
38    .into()
39}
40
41/// Exports an ordinary function through a generated typed Tool adapter.
42#[proc_macro_attribute]
43pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
44    let function = parse_macro_input!(item as ItemFn);
45    match expand_tool(&attr.into(), &function) {
46        Ok(tokens) => tokens.into(),
47        Err(error) => error.to_compile_error().into(),
48    }
49}
50
51fn type_parameters(generics: &syn::Generics) -> syn::Result<Vec<syn::Ident>> {
52    generics.params.iter().map(|param| match param {
53        syn::GenericParam::Type(param) if param.default.is_none() => Ok(param.ident.clone()),
54        _ => Err(syn::Error::new_spanned(param, "Flow boundaries accept type parameters without defaults; lifetimes and const parameters are unsupported")),
55    }).collect()
56}
57/// What a Tool's type parameters are replaced by in a Rust type.
58#[derive(Clone, Copy)]
59enum Erased {
60    /// The place-holder its declaration's metadata names the parameter by.
61    Metadata,
62    /// The dynamic value a call's argument and answer hold.
63    Runtime,
64}
65
66/// Replaces a Tool's type parameters, `names`, in a Rust type as `into`
67/// says.
68struct Erasure<'n> {
69    names: &'n [syn::Ident],
70    into: Erased,
71}
72impl Fold for Erasure<'_> {
73    fn fold_type(&mut self, ty: Type) -> Type {
74        if let Type::Path(path) = &ty
75            && path.qself.is_none()
76            && path.path.segments.len() == 1
77            && let Some(index) = self.names.iter().position(|name| path.path.is_ident(name))
78        {
79            return match self.into {
80                Erased::Metadata => {
81                    syn::parse_quote!(::flow_toolkit::__bridge::wire::Param<#index>)
82                }
83                Erased::Runtime => syn::parse_quote!(::flow_toolkit::Encoded),
84            };
85        }
86        syn::fold::fold_type(self, ty)
87    }
88}
89
90/// `ty` with the type parameters `names` replaced as `into` says.
91fn erased(names: &[syn::Ident], into: Erased, ty: &Type) -> Type {
92    Erasure { names, into }.fold_type(ty.clone())
93}
94
95/// What a tool's parameters become in its adapter.
96struct Adapted {
97    /// The arguments the adapter calls the function with, in order.
98    arguments: Vec<proc_macro2::TokenStream>,
99    /// The statements reading each typed argument, in declaration order.
100    decoded: Vec<proc_macro2::TokenStream>,
101    /// Each parameter's name and Flow type, for the declaration.
102    declared: Vec<proc_macro2::TokenStream>,
103}
104
105/// A parameter's `#[flow(default = v)]`: the expression building `v` as
106/// the constant its contract writes after `=`, checked against the
107/// parameter's Rust type `ty`.
108fn parameter_default(
109    attrs: &[syn::Attribute],
110    ty: &Type,
111) -> syn::Result<Option<proc_macro2::TokenStream>> {
112    let mut found = None;
113    for attr in attrs.iter().filter(|attr| attr.path().is_ident("flow")) {
114        let expected = || syn::Error::new_spanned(attr, "expected #[flow(default = value)]");
115        let value = attr
116            .parse_args::<syn::MetaNameValue>()
117            .map_err(|_| expected())?;
118        if !value.path.is_ident("default") {
119            return Err(expected());
120        }
121        if found.is_some() {
122            return Err(syn::Error::new_spanned(attr, "a parameter has one default"));
123        }
124        found = Some(default_value(&value.value, ty)?);
125    }
126    Ok(found)
127}
128
129/// The expression building the literal `expr` as a default of the type
130/// `ty`, through the trait of its kind.
131fn default_literal(
132    expr: &syn::Expr,
133    ty: &proc_macro2::TokenStream,
134) -> syn::Result<proc_macro2::TokenStream> {
135    let span = syn::spanned::Spanned::span(expr);
136    let refused = || {
137        syn::Error::new_spanned(
138            expr,
139            "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",
140        )
141    };
142    let (negative, lit) = match expr {
143        // A newtype's constructor applied to a default of its base.
144        syn::Expr::Call(call)
145            if call.args.len() == 1
146                && matches!(&*call.func, syn::Expr::Path(path) if !path.path.is_ident("Some")) =>
147        {
148            let constructor = &call.func;
149            let base = quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultNewtype>::Base };
150            let inner = default_value(&call.args[0], &syn::parse_quote!(#base))?;
151            // A private constructor is written only in its own contract
152            // module, which is its Rust module's (`abi.md`, *Defaults*):
153            // refused here, at the default, otherwise.
154            return Ok(quote::quote_spanned! { span =>
155                {
156                    const _: () = {
157                        ::core::assert!(
158                            ::flow_toolkit::__bridge::constructor_reachable::<#ty>(::core::module_path!()),
159                            "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",
160                        );
161                    };
162                    <#ty as ::flow_toolkit::__bridge::DefaultNewtype>::wrap(#inner, #constructor)
163                }
164            });
165        }
166        syn::Expr::Lit(syn::ExprLit { lit, .. }) => (false, lit),
167        syn::Expr::Unary(syn::ExprUnary {
168            op: syn::UnOp::Neg(_),
169            expr: inner,
170            ..
171        }) => match &**inner {
172            syn::Expr::Lit(syn::ExprLit {
173                lit: lit @ syn::Lit::Int(_),
174                ..
175            }) => (true, lit),
176            _ => return Err(refused()),
177        },
178        _ => return Err(refused()),
179    };
180    match lit {
181        syn::Lit::Int(int) => {
182            if !int.suffix().is_empty() {
183                return Err(syn::Error::new_spanned(
184                    int,
185                    "an integer default takes no suffix: its type is the parameter's",
186                ));
187            }
188            // A literal may carry its own sign, as one written `-5` inside an
189            // attribute is read.
190            let digits = int.base10_digits();
191            let (signed, magnitude) = match digits.strip_prefix('-') {
192                Some(magnitude) => (!negative, magnitude),
193                None => (negative, digits),
194            };
195            let text = if signed && magnitude.bytes().any(|digit| digit != b'0') {
196                format!("-{magnitude}")
197            } else {
198                magnitude.to_owned()
199            };
200            Ok(
201                quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultInt>::int(#text) },
202            )
203        }
204        syn::Lit::Bool(flag) => {
205            let flag = flag.value;
206            Ok(
207                quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultBool>::bool(#flag) },
208            )
209        }
210        syn::Lit::Str(text) => {
211            let text = text.value();
212            Ok(
213                quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultText>::text(#text) },
214            )
215        }
216        _ => Err(refused()),
217    }
218}
219
220/// The expression building the default `value` of a parameter of type
221/// `ty`. Each kind of default names a trait implemented only for the Rust
222/// types it may default, so a default that is no value of the parameter's
223/// type is a compile error at the default.
224fn default_value(value: &syn::Expr, ty: &Type) -> syn::Result<proc_macro2::TokenStream> {
225    let span = syn::spanned::Spanned::span(value);
226    let declared = ty;
227    let ty = quote! { #ty };
228    match value {
229        syn::Expr::Path(path) if path.path.is_ident("None") => Ok(quote::quote_spanned! { span =>
230            <#ty as ::flow_toolkit::__bridge::DefaultOption>::none()
231        }),
232        syn::Expr::Call(call)
233            if matches!(&*call.func, syn::Expr::Path(path) if path.path.is_ident("Some"))
234                && call.args.len() == 1 =>
235        {
236            let inner = quote::quote_spanned! { span => <#ty as ::flow_toolkit::__bridge::DefaultOption>::Inner };
237            let literal = default_literal(&call.args[0], &inner)?;
238            Ok(quote::quote_spanned! { span =>
239                <#ty as ::flow_toolkit::__bridge::DefaultOption>::some(#literal)
240            })
241        }
242        syn::Expr::Path(path) if constructor_name(path).is_some() => {
243            constructor_default(path, declared)
244        }
245        other => default_literal(other, &ty),
246    }
247}
248
249/// The constructor a default names when it is one bare capitalized name,
250/// such as `Info`: never `None`, which is the option's.
251fn constructor_name(path: &syn::ExprPath) -> Option<&syn::Ident> {
252    let ident = path.path.get_ident()?;
253    (path.qself.is_none()
254        && path.attrs.is_empty()
255        && ident != "None"
256        && ident
257            .to_string()
258            .starts_with(|c: char| c.is_ascii_uppercase()))
259    .then_some(ident)
260}
261
262/// The default naming the constructor `path` of the parameter's enum `ty`,
263/// written bare in the contract. The expansion matches a value of `ty`
264/// against the unit pattern `ty::Name`, so a name the enum lacks, or a
265/// constructor with a payload, is a compile error at the attribute.
266fn constructor_default(path: &syn::ExprPath, ty: &Type) -> syn::Result<proc_macro2::TokenStream> {
267    let ident = constructor_name(path).expect("checked by the caller");
268    let refused = || {
269        syn::Error::new_spanned(
270            path,
271            "a constructor default is written on a parameter of its enum's type, named by a plain path",
272        )
273    };
274    let Type::Path(syn::TypePath {
275        qself: None,
276        path: enum_path,
277        ..
278    }) = ty
279    else {
280        return Err(refused());
281    };
282    if enum_path
283        .segments
284        .iter()
285        .any(|segment| !segment.arguments.is_none())
286    {
287        return Err(refused());
288    }
289    let span = ident.span();
290    let name = ident.to_string();
291    Ok(quote::quote_spanned! { span => {
292        #[allow(unreachable_patterns, reason = "an enum may have this one constructor")]
293        let _ = |value: #ty| matches!(value, #enum_path::#ident);
294        ::flow_toolkit::__bridge::Constant::Constructor(::std::string::String::from(#name))
295    }})
296}
297
298fn tool_parameters(function: &ItemFn, generic: &[syn::Ident]) -> syn::Result<Adapted> {
299    let mut arguments = Vec::new();
300    let mut decoded = Vec::new();
301    let mut parameters = Vec::new();
302    let mut context_seen = false;
303    let mut optional_seen = false;
304    for argument in &function.sig.inputs {
305        let FnArg::Typed(argument) = argument else {
306            return Err(syn::Error::new_spanned(
307                argument,
308                "tools cannot have a receiver",
309            ));
310        };
311        let Pat::Ident(pattern) = &*argument.pat else {
312            return Err(syn::Error::new_spanned(
313                argument,
314                "tool parameters need simple names",
315            ));
316        };
317        let param = pattern
318            .ident
319            .to_string()
320            .trim_start_matches("r#")
321            .to_owned();
322        let ty = &erased(generic, Erased::Runtime, &argument.ty);
323        let metadata = &erased(generic, Erased::Metadata, &argument.ty);
324        let (context_type, borrowed) = match ty {
325            Type::Reference(reference) => (&*reference.elem, true),
326            other => (other, false),
327        };
328        if matches!(context_type,Type::Path(path) if path.path.segments.last().is_some_and(|s|s.ident=="Context"))
329        {
330            if context_seen {
331                return Err(syn::Error::new_spanned(
332                    argument,
333                    "a tool accepts at most one invocation Context",
334                ));
335            }
336            if argument
337                .attrs
338                .iter()
339                .any(|attr| attr.path().is_ident("flow"))
340            {
341                return Err(syn::Error::new_spanned(
342                    argument,
343                    "the invocation Context is no parameter and takes no default",
344                ));
345            }
346            context_seen = true;
347            arguments.push(if borrowed {
348                quote! { _context }
349            } else {
350                quote! { _context.clone() }
351            });
352            continue;
353        }
354        let flow_type = quote! { types.form(<#metadata as ::flow_toolkit::Shaped>::FORM) };
355        match parameter_default(&argument.attrs, metadata)? {
356            Some(default) => {
357                optional_seen = true;
358                parameters.push(quote! {
359                    ::flow_toolkit::__bridge::Param {
360                        name: #param.to_owned(),
361                        ty: #flow_type,
362                        default: ::core::option::Option::Some(#default),
363                    }
364                });
365            }
366            None if optional_seen => {
367                return Err(syn::Error::new_spanned(
368                    argument,
369                    "a parameter without a default follows one with a default: optional parameters come last",
370                ));
371            }
372            None => parameters.push(quote! {
373                ::flow_toolkit::__bridge::Param {
374                    name: #param.to_owned(),
375                    ty: #flow_type,
376                    default: ::core::option::Option::None,
377                }
378            }),
379        }
380        let local = format_ident!("__flow_argument_{}", decoded.len());
381        let take = tried(&quote! { args.take::<#ty>(#param) });
382        decoded.push(quote! { let #local = #take; });
383        arguments.push(quote! { #local });
384    }
385    Ok(Adapted {
386        arguments,
387        decoded,
388        declared: parameters,
389    })
390}
391
392/// What a tool returns besides a value of its declared result type `R`.
393enum Missing {
394    /// Nothing: it returns `R` whole.
395    Never,
396    /// `Result<R, ToolProblem>`: a problem.
397    ToolProblem,
398    /// `Result<R, NoAnswer>`: a problem or a hold.
399    NoAnswer,
400    /// `Result<R, Refusal<E>>`: its own error `E`, a problem or a hold.
401    Refusal,
402}
403
404/// A tool's declared result type `R`, and what else it returns: with
405/// `Result<R, ToolProblem>` or `Result<R, NoAnswer>`, `R` is its value's
406/// type and the error its problems and holds, and `Result<R, Refusal<E>>`
407/// declares `Result<R, E>` (`abi.md`, *Extracting a contract*). Any other
408/// return type is `R` whole, and a function with none returns `()`.
409fn result_type(function: &ItemFn) -> syn::Result<(Type, Missing)> {
410    let ReturnType::Type(_, result) = &function.sig.output else {
411        return Ok((syn::parse_quote!(()), Missing::Never));
412    };
413    if let Type::Reference(_) = &**result {
414        return Err(syn::Error::new_spanned(
415            result,
416            "a tool returns an owned value: R, Result<R, ToolProblem>, Result<R, NoAnswer> or Result<R, Refusal<E>>",
417        ));
418    }
419    if let Type::Path(path) = &**result
420        && path.qself.is_none()
421        && let Some(segment) = path.path.segments.last()
422        && segment.ident == "Result"
423        && let syn::PathArguments::AngleBracketed(parts) = &segment.arguments
424        && parts.args.len() == 2
425        && let syn::GenericArgument::Type(declared) = &parts.args[0]
426        && let syn::GenericArgument::Type(Type::Path(error)) = &parts.args[1]
427        && error.qself.is_none()
428        && let Some(last) = error.path.segments.last()
429    {
430        if last.ident == "Refusal" {
431            if let syn::PathArguments::AngleBracketed(own) = &last.arguments
432                && own.args.len() == 1
433                && let Some(syn::GenericArgument::Type(own)) = own.args.first()
434            {
435                return Ok((
436                    syn::parse_quote!(::core::result::Result<#declared, #own>),
437                    Missing::Refusal,
438                ));
439            }
440            return Err(syn::Error::new_spanned(
441                error,
442                "Refusal takes the Tool's own error type: Refusal<E>",
443            ));
444        }
445        let missing = if last.ident == "ToolProblem" {
446            Missing::ToolProblem
447        } else if last.ident == "NoAnswer" {
448            Missing::NoAnswer
449        } else {
450            return Ok(((**result).clone(), Missing::Never));
451        };
452        if !last.arguments.is_none() {
453            return Err(syn::Error::new_spanned(
454                error,
455                "ToolProblem and NoAnswer take no type argument: a Tool's own errors are values of its result type R",
456            ));
457        }
458        return Ok((declared.clone(), missing));
459    }
460    Ok(((**result).clone(), Missing::Never))
461}
462
463/// The text of a function's doc comments, one line each.
464fn doc_text(attrs: &[syn::Attribute]) -> String {
465    attrs
466        .iter()
467        .filter(|a| a.path().is_ident("doc"))
468        .filter_map(|a| match &a.meta {
469            syn::Meta::NameValue(syn::MetaNameValue {
470                value:
471                    syn::Expr::Lit(syn::ExprLit {
472                        lit: syn::Lit::Str(s),
473                        ..
474                    }),
475                ..
476            }) => Some(s.value().trim().to_owned()),
477            _ => None,
478        })
479        .collect::<Vec<_>>()
480        .join("\n")
481}
482
483/// `expression?`, written out. A generated adapter or derived impl is all
484/// macro expansion, so rustc's coverage instrumentation maps it to the
485/// `#[tool]` or `#[derive(Flow)]` attribute; a `?` there leaves a region
486/// counting only the error path, which reads as a line never executed however
487/// often the code runs. Spelled as a `match`, the expansion leaves no region
488/// at all, like the rest of it.
489fn tried(expression: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
490    quote! {
491        match #expression {
492            ::core::result::Result::Ok(__flow_value) => __flow_value,
493            ::core::result::Result::Err(__flow_error) => {
494                return ::core::result::Result::Err(::core::convert::From::from(__flow_error))
495            }
496        }
497    }
498}
499
500/// The adapter's declaration: it reads the arguments at the call's types,
501/// calls the function and writes its answer at the call's result type.
502fn tool_declaration(
503    decoded: &[proc_macro2::TokenStream],
504    invoke: &proc_macro2::TokenStream,
505    result: &Type,
506) -> proc_macro2::TokenStream {
507    let finish = tried(&quote! { args.finish() });
508    quote! { ::flow_toolkit::__bridge::typed::<#result, _>(|_context, args| {
509        #(#decoded)*
510        #finish;
511        Ok(#invoke)
512    }) }
513}
514
515fn expand_tool(
516    attr: &proc_macro2::TokenStream,
517    function: &ItemFn,
518) -> syn::Result<proc_macro2::TokenStream> {
519    if !attr.is_empty() {
520        return Err(syn::Error::new_spanned(
521            function,
522            "#[tool] takes no arguments",
523        ));
524    }
525    if matches!(function.sig.safety, syn::Safety::Unsafe(_)) || function.sig.abi.is_some() {
526        return Err(syn::Error::new_spanned(
527            &function.sig,
528            "tools must be safe Rust functions",
529        ));
530    }
531    let generic = type_parameters(&function.sig.generics)?;
532    let substitutions = generic
533        .iter()
534        .map(|_| quote! { ::flow_toolkit::Encoded })
535        .collect::<Vec<_>>();
536    if !matches!(function.vis, syn::Visibility::Public(_)) {
537        return Err(syn::Error::new_spanned(
538            &function.vis,
539            "tools must be public",
540        ));
541    }
542    let name = &function.sig.ident;
543    let wire_name = name.to_string().trim_start_matches("r#").to_owned();
544    let factory = format_ident!("__flow_tool_{}", name);
545    let Adapted {
546        arguments,
547        decoded,
548        declared: parameters,
549    } = tool_parameters(function, &generic)?;
550    let (declared, missing) = result_type(function)?;
551    let result = erased(&generic, Erased::Runtime, &declared);
552    let metadata = erased(&generic, Erased::Metadata, &declared);
553    let invoke = if generic.is_empty() {
554        quote! { #name(#(#arguments),*) }
555    } else {
556        quote! { #name::<#(#substitutions),*>(#(#arguments),*) }
557    };
558    let invoke = if function.sig.asyncness.is_some() {
559        quote! { ::flow_toolkit::__bridge::block_on(#invoke) }
560    } else {
561        invoke
562    };
563    let invoke = match missing {
564        Missing::NoAnswer => invoke,
565        Missing::Refusal => quote! { ::flow_toolkit::__bridge::refused(#invoke) },
566        Missing::ToolProblem => quote! { #invoke.map_err(::flow_toolkit::NoAnswer::Problem) },
567        Missing::Never => {
568            quote! { ::std::result::Result::<_, ::flow_toolkit::NoAnswer>::Ok(#invoke) }
569        }
570    };
571    let declaration = tool_declaration(&decoded, &invoke, &result);
572    let generic_names = generic.iter().map(ToString::to_string).collect::<Vec<_>>();
573    let docs = doc_text(&function.attrs);
574    // `file!()` and `line!()` name where this attribute is, which orders the
575    // Tool among its module's declarations as the launcher's placement does.
576    let origin = quote! {
577        ::flow_toolkit::__bridge::Origin {
578            module: ::core::module_path!(),
579            file: ::core::file!(),
580            line: ::core::line!(),
581        }
582    };
583    let function = without_parameter_attributes(function);
584    // The boundary decodes every argument as an owned value and a tool may
585    // return `Result<R, ToolProblem>` though it never has a problem, so these
586    // lints would fire on tools whose author could do nothing about either.
587    Ok(quote! {
588        #[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
589        #function
590        #[doc(hidden)]
591        pub fn #factory() -> ::flow_toolkit::__bridge::Function {
592            let mut types = ::flow_toolkit::__bridge::Types::default();
593            types.parameters(&[#(#generic_names),*]);
594            let params = vec![#(#parameters),*];
595            let result = types.form(<#metadata as ::flow_toolkit::Shaped>::FORM);
596            types.end_parameters();
597            ::flow_toolkit::__bridge::function((#wire_name, &[#(#generic_names),*]), #origin, #docs, params, result, types,
598                || #declaration)
599        }
600    })
601}
602
603/// `function` without its parameters' `#[flow(...)]` attributes, which
604/// `#[tool]` reads and Rust would otherwise refuse.
605fn without_parameter_attributes(function: &ItemFn) -> ItemFn {
606    let mut function = function.clone();
607    for argument in &mut function.sig.inputs {
608        if let FnArg::Typed(argument) = argument {
609            argument.attrs.retain(|attr| !attr.path().is_ident("flow"));
610        }
611    }
612    function
613}
614
615/// Derives exact Flow encoding and declaration metadata for records and enums.
616#[proc_macro_derive(Flow, attributes(flow))]
617pub fn flow(item: TokenStream) -> TokenStream {
618    let input = parse_macro_input!(item as DeriveInput);
619    match expand_data(&input) {
620        Ok(tokens) => tokens.into(),
621        Err(error) => error.to_compile_error().into(),
622    }
623}
624
625/// Derives a host type: a one-field tuple struct holding a `String`, the
626/// handle the implementation chose.
627#[proc_macro_derive(Handle)]
628pub fn handle(item: TokenStream) -> TokenStream {
629    let input = parse_macro_input!(item as DeriveInput);
630    match expand_handle(&input) {
631        Ok(tokens) => tokens.into(),
632        Err(error) => error.to_compile_error().into(),
633    }
634}
635
636/// A named field's identifier.
637fn field_ident(field: &syn::Field) -> syn::Result<&syn::Ident> {
638    field
639        .ident
640        .as_ref()
641        .ok_or_else(|| syn::Error::new_spanned(field, "expected a named field"))
642}
643
644/// A named field's wire name: its `#[flow(name = "...")]`, or its Rust
645/// name. Any other `#[flow(...)]` on a field is refused, so a misspelled
646/// attribute cannot silently cross data under the Rust name.
647fn field_name(field: &syn::Field) -> syn::Result<String> {
648    let mut renamed = None;
649    for attr in field
650        .attrs
651        .iter()
652        .filter(|attr| attr.path().is_ident("flow"))
653    {
654        let expected = || syn::Error::new_spanned(attr, "expected #[flow(name = \"...\")]");
655        let value = attr
656            .parse_args::<syn::MetaNameValue>()
657            .map_err(|_| expected())?;
658        if !value.path.is_ident("name") {
659            return Err(expected());
660        }
661        let syn::Expr::Lit(syn::ExprLit {
662            lit: syn::Lit::Str(text),
663            ..
664        }) = &value.value
665        else {
666            return Err(syn::Error::new_spanned(
667                &value.value,
668                "`name` takes a string literal",
669            ));
670        };
671        if renamed.replace(text.value()).is_some() {
672            return Err(syn::Error::new_spanned(attr, "a field is renamed once"));
673        }
674    }
675    match renamed {
676        Some(name) => Ok(name),
677        None => Ok(field_ident(field)?
678            .to_string()
679            .trim_start_matches("r#")
680            .to_owned()),
681    }
682}
683
684/// Whether a member whose Rust visibility is `vis` is public: `pub` is,
685/// and anything narrower is private.
686fn public(vis: &syn::Visibility) -> bool {
687    matches!(vis, syn::Visibility::Public(_))
688}
689
690/// A std declaration a type's `#[flow(std = "module.Name")]` names, one of
691/// std's public types ([`flow_types::STD_TYPES`]), as its module and name,
692/// or `None` when the type has no `#[flow(...)]`. Any other
693/// `#[flow(...)]` on a type is refused.
694fn std_declaration(attrs: &[syn::Attribute]) -> syn::Result<Option<(String, String)>> {
695    let mut named = None;
696    for attr in attrs.iter().filter(|attr| attr.path().is_ident("flow")) {
697        let expected = || {
698            syn::Error::new_spanned(
699                attr,
700                "expected #[flow(std = \"module.Name\")], naming a std declaration; a host type derives Handle",
701            )
702        };
703        let value = attr
704            .parse_args::<syn::MetaNameValue>()
705            .map_err(|_| expected())?;
706        if !value.path.is_ident("std") {
707            return Err(expected());
708        }
709        let syn::Expr::Lit(syn::ExprLit {
710            lit: syn::Lit::Str(text),
711            ..
712        }) = &value.value
713        else {
714            return Err(syn::Error::new_spanned(
715                &value.value,
716                "`std` takes a string literal, \"module.Name\"",
717            ));
718        };
719        let written = text.value();
720        let Some((module, name)) = written
721            .split_once('.')
722            .filter(|declared| flow_types::STD_TYPES.iter().any(|known| known == declared))
723        else {
724            return Err(syn::Error::new_spanned(
725                text,
726                format!(
727                    "`{written}` names no std declaration: expected \"module.Name\", such as \"code.Bundle\""
728                ),
729            ));
730        };
731        if named
732            .replace((module.to_owned(), name.to_owned()))
733            .is_some()
734        {
735            return Err(syn::Error::new_spanned(
736                attr,
737                "a type names one std declaration",
738            ));
739        }
740    }
741    Ok(named)
742}
743
744/// The derive for a type declared as std's `module.Name`: a tuple struct
745/// holding the value in one `Encoded` field, beside any `PhantomData` for
746/// the declaration's type parameters, which are its own in order. The
747/// contract names the std declaration and declares nothing (`abi.md`,
748/// *Generated contracts*).
749fn std_data(
750    input: &DeriveInput,
751    parameters: &[syn::Ident],
752    (module, std_name): &(String, String),
753) -> syn::Result<proc_macro2::TokenStream> {
754    let name = &input.ident;
755    let shape = || {
756        syn::Error::new_spanned(
757            input,
758            "a std declaration's Rust type is a tuple struct holding its value in one flow_toolkit::Encoded field, beside any PhantomData",
759        )
760    };
761    let Data::Struct(syn::DataStruct {
762        fields: Fields::Unnamed(fields),
763        ..
764    }) = &input.data
765    else {
766        return Err(shape());
767    };
768    let mut held = fields
769        .unnamed
770        .iter()
771        .enumerate()
772        .filter(|(_, field)| !phantom(&field.ty));
773    let (Some((index, field)), None) = (held.next(), held.next()) else {
774        return Err(shape());
775    };
776    if !matches!(&field.ty, Type::Path(path) if path.qself.is_none()
777        && path.path.segments.last().is_some_and(|segment| segment.ident == "Encoded"))
778    {
779        return Err(syn::Error::new_spanned(
780            &field.ty,
781            "a std declaration's value is held in a flow_toolkit::Encoded",
782        ));
783    }
784    let at = syn::Index::from(index);
785    let parts = (0..fields.unnamed.len()).map(|position| {
786        if position == index {
787            quote! { value }
788        } else {
789            quote! { ::core::marker::PhantomData }
790        }
791    });
792    let mut generics = input.generics.clone();
793    for parameter in generics.type_params_mut() {
794        parameter
795            .bounds
796            .push(syn::parse_quote!(::flow_toolkit::Shaped));
797    }
798    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
799    Ok(quote! {
800        impl #impl_generics ::flow_toolkit::Shaped for #name #ty_generics #where_clause {
801            const FORM: ::flow_toolkit::__bridge::wire::WireForm = ::flow_toolkit::__bridge::wire::WireForm::Std {
802                module: #module,
803                name: #std_name,
804                args: &[#(::flow_toolkit::__bridge::wire::form_of::<#parameters>),*],
805            };
806            fn write_at(
807                &self,
808                out: &mut ::flow_toolkit::__bridge::wire::ValueWriter<'_, '_>,
809                ty: &::flow_toolkit::__bridge::wire::Type,
810            ) -> ::core::result::Result<(), ::flow_toolkit::__bridge::EncodeError> {
811                ::flow_toolkit::Shaped::write_at(&self.#at, out, ty)
812            }
813            fn read_at(
814                input: &mut ::flow_toolkit::__bridge::wire::ValueReader<'_, '_, '_>,
815                ty: &::flow_toolkit::__bridge::wire::Type,
816            ) -> ::core::result::Result<Self, ::flow_toolkit::DecodeError> {
817                <::flow_toolkit::Encoded as ::flow_toolkit::Shaped>::read_at(input, ty)
818                    .map(|value| Self(#(#parts),*))
819            }
820        }
821    })
822}
823
824/// What a declaration's text says of one member: its doc comment, whether
825/// it is public, and a constructor's named fields.
826#[expect(
827    clippy::fn_params_excessive_bools,
828    reason = "whether a member is public is the one flag its note carries"
829)]
830fn note(
831    attrs: &[syn::Attribute],
832    public: bool,
833    fields: &[proc_macro2::TokenStream],
834) -> proc_macro2::TokenStream {
835    let docs = doc_text(attrs);
836    quote! {
837        ::flow_toolkit::__bridge::wire::Note { docs: #docs, public: #public, fields: &[#(#fields),*] }
838    }
839}
840
841/// What a declaration's text says beside its shape: where the type is
842/// defined, its doc comment and its `members`'.
843fn notes(input: &DeriveInput, members: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
844    let docs = doc_text(&input.attrs);
845    quote! {
846        ::flow_toolkit::__bridge::wire::Notes {
847            module: ::core::module_path!(),
848            file: ::core::file!(),
849            line: ::core::line!(),
850            docs: #docs,
851            members: &[#(#members),*],
852        }
853    }
854}
855
856/// The head `wire_impl!` takes for `input`: its name, its type
857/// parameters with their positions, and the bounds its definition puts on
858/// them.
859fn wire_head(input: &DeriveInput, parameters: &[syn::Ident]) -> proc_macro2::TokenStream {
860    let name = &input.ident;
861    let positions = (0..parameters.len()).map(proc_macro2::Literal::usize_unsuffixed);
862    let mut predicates = input
863        .generics
864        .type_params()
865        .filter(|parameter| !parameter.bounds.is_empty())
866        .map(|parameter| {
867            let (ident, bounds) = (&parameter.ident, &parameter.bounds);
868            quote! { #ident: #bounds, }
869        })
870        .collect::<Vec<_>>();
871    if let Some(clause) = &input.generics.where_clause {
872        predicates.extend(
873            clause
874                .predicates
875                .iter()
876                .map(|predicate| quote! { #predicate, }),
877        );
878    }
879    let bounded = if predicates.is_empty() {
880        quote! {}
881    } else {
882        quote! { where [#(#predicates)*] }
883    };
884    quote! { impl #name [#(#parameters = #positions),*] #bounded }
885}
886
887/// The derive for `Handle`: a host type, carried as its one `String`
888/// handle.
889fn expand_handle(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
890    let name = &input.ident;
891    if !input.generics.params.is_empty()
892        || !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"))))
893    {
894        return Err(syn::Error::new_spanned(
895            input,
896            "a host type is a nongeneric tuple struct with one String field",
897        ));
898    }
899    let notes = notes(input, &[]);
900    Ok(quote! {
901        impl ::flow_toolkit::__bridge::wire::Declared for #name {
902            const SHAPE: ::flow_toolkit::__bridge::wire::Shape = ::flow_toolkit::__bridge::wire::Shape {
903                name: ::core::stringify!(#name),
904                params: &[],
905                layout: ::flow_toolkit::__bridge::wire::Layout::Host,
906                notes: ::core::option::Option::Some(&#notes),
907            };
908        }
909        impl ::flow_toolkit::Shaped for #name {
910            const FORM: ::flow_toolkit::__bridge::wire::WireForm = ::flow_toolkit::__bridge::wire::WireForm::Declared(
911                <Self as ::flow_toolkit::__bridge::wire::Declared>::shape,
912            );
913            fn write_at(
914                &self,
915                out: &mut ::flow_toolkit::__bridge::wire::ValueWriter<'_, '_>,
916                ty: &::flow_toolkit::__bridge::wire::Type,
917            ) -> ::core::result::Result<(), ::flow_toolkit::__bridge::EncodeError> {
918                out.host(ty, &self.0)
919            }
920            fn read_at(
921                input: &mut ::flow_toolkit::__bridge::wire::ValueReader<'_, '_, '_>,
922                ty: &::flow_toolkit::__bridge::wire::Type,
923            ) -> ::core::result::Result<Self, ::flow_toolkit::DecodeError> {
924                input.host(ty).map(|token| Self(token.to_owned()))
925            }
926        }
927    })
928}
929
930/// Whether `ty` is `PhantomData<..>`, a field a newtype skips.
931fn phantom(ty: &Type) -> bool {
932    matches!(ty, Type::Path(path) if path.qself.is_none()
933        && path.path.segments.last().is_some_and(|segment| segment.ident == "PhantomData"))
934}
935
936/// The derive for a one-field tuple struct: a newtype over its field's
937/// type, written and read as that field (`abi.md`, *Extracting a contract*).
938/// A `PhantomData` field is skipped, so its type parameter is a phantom
939/// parameter of the newtype.
940fn newtype_data(
941    input: &DeriveInput,
942    parameters: &[syn::Ident],
943    fields: &syn::FieldsUnnamed,
944) -> syn::Result<proc_macro2::TokenStream> {
945    let name = &input.ident;
946    let mut held = fields
947        .unnamed
948        .iter()
949        .enumerate()
950        .filter(|(_, field)| !phantom(&field.ty));
951    let (Some((index, field)), None) = (held.next(), held.next()) else {
952        return Err(syn::Error::new_spanned(
953            fields,
954            "a Flow newtype is a tuple struct with one field beside any PhantomData; a record needs named fields",
955        ));
956    };
957    if let Some(attr) = field.attrs.iter().find(|attr| attr.path().is_ident("flow")) {
958        return Err(syn::Error::new_spanned(
959            attr,
960            "a newtype's field has no Flow name to rename",
961        ));
962    }
963    let base = &field.ty;
964    // A tuple struct's field that is not `pub` is a private constructor.
965    let public = public(&field.vis);
966    let at = syn::Index::from(index);
967    let phantoms = (0..fields.unnamed.len())
968        .filter(|position| *position != index)
969        .map(syn::Index::from);
970    let declared = wire_head(input, parameters);
971    let notes = notes(input, &[note(&[], public, &[])]);
972    let mut generics = input.generics.clone();
973    for parameter in generics.type_params_mut() {
974        parameter
975            .bounds
976            .push(syn::parse_quote!(::flow_toolkit::Shaped));
977    }
978    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
979    Ok(quote! {
980        ::flow_toolkit::__bridge::wire_impl! {
981            #declared newtype { #at: #base } phantom [#(#phantoms),*] notes #notes
982        }
983        impl #impl_generics ::flow_toolkit::__bridge::DefaultNewtype for #name #ty_generics #where_clause {
984            const PUBLIC: bool = #public;
985            const MODULE: &'static str = ::core::module_path!();
986            type Base = #base;
987            fn written() -> ::flow_toolkit::__bridge::TypeRef<::flow_toolkit::__bridge::Owner> {
988                ::flow_toolkit::__bridge::TypeRef::qualified(
989                    ::flow_toolkit::__bridge::Owner::Rust(::core::module_path!()),
990                    ::core::stringify!(#name),
991                )
992            }
993        }
994    })
995}
996
997/// A record's fields, as `wire_impl!` takes them, its `PhantomData`
998/// fields, and what its declaration's text says of each field.
999fn record_fields(
1000    fields: &syn::FieldsNamed,
1001) -> syn::Result<(
1002    Vec<proc_macro2::TokenStream>,
1003    Vec<&syn::Ident>,
1004    Vec<proc_macro2::TokenStream>,
1005)> {
1006    let mut listed = Vec::new();
1007    let mut phantoms = Vec::new();
1008    let mut members = Vec::new();
1009    for field in &fields.named {
1010        let ident = field_ident(field)?;
1011        if phantom(&field.ty) {
1012            // A `PhantomData` field is skipped: its type parameter stays on
1013            // the declaration, and it crosses as nothing (`abi.md`,
1014            // *Extracting a contract*).
1015            phantoms.push(ident);
1016            continue;
1017        }
1018        let flow = field_name(field)?;
1019        let ty = &field.ty;
1020        listed.push(quote! { #ident #flow: #ty });
1021        // A Rust field that is not `pub` is a private Flow field (`abi.md`,
1022        // *Generated contracts*).
1023        members.push(note(&field.attrs, public(&field.vis), &[]));
1024    }
1025    Ok((listed, phantoms, members))
1026}
1027
1028/// An enum's constructors, as `wire_impl!` takes them, and what its
1029/// declaration's text says of each.
1030fn enum_constructors(
1031    data: &syn::DataEnum,
1032) -> syn::Result<(Vec<proc_macro2::TokenStream>, Vec<proc_macro2::TokenStream>)> {
1033    let mut listed = Vec::new();
1034    let mut members = Vec::new();
1035    for (number, variant) in data.variants.iter().enumerate() {
1036        let ident = &variant.ident;
1037        let (kind, parts, fields) = match &variant.fields {
1038            Fields::Unit => (quote! { Empty }, Vec::new(), Vec::new()),
1039            Fields::Unnamed(fields) => (
1040                quote! { Positional },
1041                fields
1042                    .unnamed
1043                    .iter()
1044                    .enumerate()
1045                    .map(|(at, field)| {
1046                        let (member, bind, ty) =
1047                            (syn::Index::from(at), format_ident!("p{at}"), &field.ty);
1048                        quote! { #member (#bind) "": #ty }
1049                    })
1050                    .collect(),
1051                Vec::new(),
1052            ),
1053            Fields::Named(fields) => {
1054                let mut parts = Vec::new();
1055                let mut notes = Vec::new();
1056                for (at, field) in fields.named.iter().enumerate() {
1057                    let (member, bind, ty) =
1058                        (field_ident(field)?, format_ident!("p{at}"), &field.ty);
1059                    let flow = field_name(field)?;
1060                    parts.push(quote! { #member (#bind) #flow: #ty });
1061                    notes.push(note(&field.attrs, true, &[]));
1062                }
1063                (quote! { Named }, parts, notes)
1064            }
1065        };
1066        let number = proc_macro2::Literal::usize_unsuffixed(number);
1067        listed.push(quote! { #ident = #number #kind { #(#parts),* } });
1068        members.push(note(&variant.attrs, true, &fields));
1069    }
1070    Ok((listed, members))
1071}
1072
1073fn expand_data(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1074    let parameters = type_parameters(&input.generics)?;
1075    if let Some(std) = std_declaration(&input.attrs)? {
1076        return std_data(input, &parameters, &std);
1077    }
1078    let head = wire_head(input, &parameters);
1079    match &input.data {
1080        Data::Struct(syn::DataStruct {
1081            fields: Fields::Unnamed(fields),
1082            ..
1083        }) => newtype_data(input, &parameters, fields),
1084        Data::Struct(syn::DataStruct {
1085            fields: Fields::Named(fields),
1086            ..
1087        }) => {
1088            let (listed, phantoms, members) = record_fields(fields)?;
1089            let notes = notes(input, &members);
1090            Ok(quote! {
1091                ::flow_toolkit::__bridge::wire_impl! {
1092                    #head record { #(#listed),* } phantom [#(#phantoms),*] notes #notes
1093                }
1094            })
1095        }
1096        Data::Struct(_) => Err(syn::Error::new_spanned(
1097            input,
1098            "Flow records need named fields",
1099        )),
1100        Data::Enum(data) => {
1101            let (listed, members) = enum_constructors(data)?;
1102            let notes = notes(input, &members);
1103            Ok(quote! {
1104                ::flow_toolkit::__bridge::wire_impl! {
1105                    #head enum { #(#listed),* } notes #notes
1106                }
1107            })
1108        }
1109        Data::Union(_) => Err(syn::Error::new_spanned(
1110            input,
1111            "Rust unions cannot cross a Tool boundary",
1112        )),
1113    }
1114}
1115
1116/// Registers one optional process resource initializer without an authored launcher.
1117#[proc_macro_attribute]
1118pub fn lifespan(attr: TokenStream, item: TokenStream) -> TokenStream {
1119    let function = parse_macro_input!(item as ItemFn);
1120    match expand_lifespan(&attr, &function) {
1121        Ok(tokens) => tokens.into(),
1122        Err(error) => error.to_compile_error().into(),
1123    }
1124}
1125
1126fn expand_lifespan(attr: &TokenStream, function: &ItemFn) -> syn::Result<proc_macro2::TokenStream> {
1127    if !attr.is_empty()
1128        || !function.sig.inputs.is_empty()
1129        || !function.sig.generics.params.is_empty()
1130        || matches!(function.sig.safety, syn::Safety::Unsafe(_))
1131        || function.sig.abi.is_some()
1132        || !matches!(function.vis, syn::Visibility::Public(_))
1133    {
1134        return Err(syn::Error::new_spanned(
1135            &function.sig,
1136            "#[lifespan] requires a public safe nongeneric zero-argument Rust function",
1137        ));
1138    }
1139    let name = &function.sig.ident;
1140    let factory = format_ident!("__flow_lifespan_{}", name);
1141    let invoke = if function.sig.asyncness.is_some() {
1142        quote! { ::flow_toolkit::__bridge::block_on(#name()) }
1143    } else {
1144        quote! { #name() }
1145    };
1146    Ok(quote! {
1147        #function
1148        #[doc(hidden)]
1149        pub fn #factory()->::std::result::Result<::flow_toolkit::__bridge::Lifespan,::flow_toolkit::StartError> {
1150            (#invoke).map(::flow_toolkit::Resource::into_lifespan).map_err(::std::convert::Into::into)
1151        }
1152    })
1153}
1154
1155#[cfg(test)]
1156#[cfg_attr(coverage, coverage(off))]
1157mod tests {
1158    use super::*;
1159    use syn::parse::Parser as _;
1160    use syn::parse_quote;
1161
1162    #[test]
1163    fn lifespan_adapter_preserves_sync_and_async_factories_and_rejects_parameters() {
1164        for function in [
1165            parse_quote!(
1166                pub fn open() -> Result<Resource<Pool>, String> {
1167                    unreachable!()
1168                }
1169            ),
1170            parse_quote!(
1171                pub async fn open() -> Result<Resource<Pool>, String> {
1172                    unreachable!()
1173                }
1174            ),
1175        ] {
1176            syn::parse2::<syn::File>(expand_lifespan(&TokenStream::new(), &function).unwrap())
1177                .unwrap();
1178        }
1179        for function in [
1180            parse_quote!(
1181                fn hidden() -> Result<Resource<Pool>, String> {
1182                    unreachable!()
1183                }
1184            ),
1185            parse_quote!(
1186                pub fn with_arg(value: String) -> Result<Resource<Pool>, String> {
1187                    unreachable!()
1188                }
1189            ),
1190            parse_quote!(
1191                pub fn generic<T>() -> Result<Resource<T>, String> {
1192                    unreachable!()
1193                }
1194            ),
1195        ] {
1196            assert!(
1197                expand_lifespan(&TokenStream::new(), &function)
1198                    .unwrap_err()
1199                    .to_string()
1200                    .contains("zero-argument")
1201            );
1202        }
1203    }
1204    #[test]
1205    fn a_return_type_other_than_result_of_a_problem_or_no_answer_is_declared_whole() {
1206        for (function, declared) in [
1207            (
1208                parse_quote!(
1209                    pub fn plain() -> String {
1210                        String::new()
1211                    }
1212                ),
1213                ":: std :: result :: Result :: < _ , :: flow_toolkit :: NoAnswer > :: Ok",
1214            ),
1215            (
1216                parse_quote!(
1217                    pub fn nothing() {}
1218                ),
1219                "types . form (< () as :: flow_toolkit :: Shaped > :: FORM)",
1220            ),
1221            (
1222                parse_quote!(
1223                    pub fn domain() -> Result<String, Declined> {
1224                        Ok(String::new())
1225                    }
1226                ),
1227                "types . form (< Result < String , Declined > as :: flow_toolkit :: Shaped > :: FORM)",
1228            ),
1229            (
1230                parse_quote!(
1231                    pub fn odd() -> Result<'a, String> {
1232                        unreachable!()
1233                    }
1234                ),
1235                "types . form (< Result < 'a , String > as :: flow_toolkit :: Shaped > :: FORM)",
1236            ),
1237            (
1238                parse_quote!(
1239                    pub fn problems() -> Result<Result<String, Declined>, flow_toolkit::ToolProblem>
1240                    {
1241                        Ok(Ok(String::new()))
1242                    }
1243                ),
1244                "types . form (< Result < String , Declined > as :: flow_toolkit :: Shaped > :: FORM)",
1245            ),
1246            (
1247                parse_quote!(
1248                    pub fn holds() -> Result<String, NoAnswer> {
1249                        Ok(String::new())
1250                    }
1251                ),
1252                "types . form (< String as :: flow_toolkit :: Shaped > :: FORM)",
1253            ),
1254        ] {
1255            let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
1256                .expect("any owned return type is a Tool's result")
1257                .to_string();
1258            assert!(source.contains(declared), "{declared} in {source}");
1259        }
1260    }
1261
1262    #[test]
1263    fn a_default_is_written_through_the_trait_of_its_kind_and_checked_by_the_compiler() {
1264        let function: ItemFn = parse_quote!(
1265            pub fn search(
1266                context: &Context,
1267                query: String,
1268                #[flow(default = 20)] limit: Int,
1269                #[flow(default = -3)] offset: Int,
1270                #[flow(default = true)] exact: bool,
1271                #[flow(default = "a \"b\"")] label: String,
1272                #[flow(default = None)] owner: Option<String>,
1273                #[flow(default = Some(5))] page: Option<Int>,
1274                #[flow(default = "x")] tag: Option<String>,
1275            ) -> Vec<String> {
1276                Vec::new()
1277            }
1278        );
1279        let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
1280            .expect("defaults of every kind")
1281            .to_string();
1282        for expected in [
1283            "< Int as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"20\")",
1284            "< Int as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"-3\")",
1285            "< bool as :: flow_toolkit :: __bridge :: DefaultBool > :: bool (true)",
1286            "< String as :: flow_toolkit :: __bridge :: DefaultText > :: text (\"a \\\"b\\\"\")",
1287            "< Option < String > as :: flow_toolkit :: __bridge :: DefaultOption > :: none ()",
1288            "< Option < Int > as :: flow_toolkit :: __bridge :: DefaultOption > :: some (< < Option < Int > as :: flow_toolkit :: __bridge :: DefaultOption > :: Inner as :: flow_toolkit :: __bridge :: DefaultInt > :: int (\"5\"))",
1289            "< Option < String > as :: flow_toolkit :: __bridge :: DefaultText > :: text (\"x\")",
1290        ] {
1291            assert!(source.contains(expected), "{expected} in {source}");
1292        }
1293        assert!(
1294            !source.contains("# [flow"),
1295            "the attribute is read by #[tool] and not left for Rust: {source}"
1296        );
1297    }
1298
1299    #[test]
1300    fn a_constructor_default_is_written_bare_and_checked_as_a_unit_pattern_of_the_enum() {
1301        let function: ItemFn = parse_quote!(
1302            pub fn note(message: String, #[flow(default = Info)] level: Level) {}
1303        );
1304        let source = expand_tool(&proc_macro2::TokenStream::new(), &function)
1305            .expect("a constructor default")
1306            .to_string();
1307        for expected in [
1308            "matches ! (value , Level :: Info)",
1309            ":: std :: string :: String :: from (\"Info\")",
1310        ] {
1311            assert!(source.contains(expected), "{expected} in {source}");
1312        }
1313        for (function, message) in [
1314            (
1315                parse_quote!(
1316                    pub fn f(#[flow(default = Info)] x: Option<Level>) {}
1317                ),
1318                "a constructor default is written on a parameter of its enum's type",
1319            ),
1320            (
1321                parse_quote!(
1322                    pub fn f(#[flow(default = Info)] x: <T as Tr>::Level) {}
1323                ),
1324                "a constructor default is written on a parameter of its enum's type",
1325            ),
1326            (
1327                parse_quote!(
1328                    pub fn f(#[flow(default = Level::Info)] x: Level) {}
1329                ),
1330                "or a payload-free constructor of the parameter's enum written bare",
1331            ),
1332            (
1333                parse_quote!(
1334                    pub fn f(#[flow(default = info)] x: Level) {}
1335                ),
1336                "or a payload-free constructor of the parameter's enum written bare",
1337            ),
1338        ] {
1339            let error = expand_tool(&proc_macro2::TokenStream::new(), &function)
1340                .expect_err("refused before generating code");
1341            assert!(error.to_string().contains(message), "{message}: {error}");
1342        }
1343    }
1344
1345    #[test]
1346    fn a_default_that_no_contract_could_write_is_a_compile_error() {
1347        for (function, message) in [
1348            (
1349                parse_quote!(
1350                    pub fn f(#[flow(default = 1.5)] x: Decimal) {}
1351                ),
1352                "a default is an integer, boolean or string literal",
1353            ),
1354            (
1355                parse_quote!(
1356                    pub fn f(#[flow(default = make())] x: Int) {}
1357                ),
1358                "a default is an integer, boolean or string literal",
1359            ),
1360            (
1361                parse_quote!(
1362                    pub fn f(#[flow(default = -true)] x: bool) {}
1363                ),
1364                "a default is an integer, boolean or string literal",
1365            ),
1366            (
1367                parse_quote!(
1368                    pub fn f(#[flow(default = Some(None))] x: Option<Option<Int>>) {}
1369                ),
1370                "a default is an integer, boolean or string literal",
1371            ),
1372            (
1373                parse_quote!(
1374                    pub fn f(#[flow(default = 5u8)] x: Int) {}
1375                ),
1376                "takes no suffix",
1377            ),
1378            (
1379                parse_quote!(
1380                    pub fn f(#[flow(other = 5)] x: Int) {}
1381                ),
1382                "expected #[flow(default = value)]",
1383            ),
1384            (
1385                parse_quote!(
1386                    pub fn f(#[flow(default)] x: Int) {}
1387                ),
1388                "expected #[flow(default = value)]",
1389            ),
1390            (
1391                parse_quote!(
1392                    pub fn f(
1393                        #[flow(default = 1)]
1394                        #[flow(default = 2)]
1395                        x: Int,
1396                    ) {
1397                    }
1398                ),
1399                "a parameter has one default",
1400            ),
1401            (
1402                parse_quote!(
1403                    pub fn f(#[flow(default = 1)] x: Int, y: Int) {}
1404                ),
1405                "optional parameters come last",
1406            ),
1407            (
1408                parse_quote!(
1409                    pub fn f(#[flow(default = 1)] context: &Context) {}
1410                ),
1411                "takes no default",
1412            ),
1413        ] {
1414            let error = expand_tool(&proc_macro2::TokenStream::new(), &function)
1415                .expect_err("refused before generating code");
1416            assert!(error.to_string().contains(message), "{message}: {error}");
1417        }
1418        let zero: ItemFn = parse_quote!(
1419            pub fn f(#[flow(default = -0)] x: Int) {}
1420        );
1421        let source = expand_tool(&proc_macro2::TokenStream::new(), &zero)
1422            .unwrap()
1423            .to_string();
1424        assert!(
1425            source.contains("int (\"0\")"),
1426            "negative zero is zero: {source}"
1427        );
1428    }
1429
1430    #[test]
1431    fn nontext_doc_attributes_get_deliberate_handling() {
1432        for function in [
1433            parse_quote!(
1434                #[doc = 1]
1435                pub fn docs() -> Result<String, String> {
1436                    unreachable!()
1437                }
1438            ),
1439            parse_quote!(
1440                #[doc=call()]
1441                pub fn docs() -> Result<String, String> {
1442                    unreachable!()
1443                }
1444            ),
1445            parse_quote!(
1446                #[doc(hidden)]
1447                pub fn docs() -> Result<String, String> {
1448                    unreachable!()
1449                }
1450            ),
1451        ] {
1452            assert!(expand_tool(&proc_macro2::TokenStream::new(), &function).is_ok());
1453        }
1454    }
1455    #[test]
1456    fn a_tool_attribute_with_arguments_is_refused() {
1457        let function: ItemFn = parse_quote!(
1458            pub fn echo() -> Result<(), String> {
1459                Ok(())
1460            }
1461        );
1462        let error = expand_tool(&quote!(unexpected), &function).unwrap_err();
1463        assert_eq!(error.to_string(), "#[tool] takes no arguments");
1464    }
1465
1466    #[test]
1467    fn function_adapters_reject_unrepresentable_signatures_before_generating_code() {
1468        for (function, message) in [
1469            (
1470                parse_quote!(
1471                    fn hidden() -> Result<(), String> {
1472                        Ok(())
1473                    }
1474                ),
1475                "public",
1476            ),
1477            (
1478                parse_quote!(
1479                    pub unsafe fn dangerous() -> Result<(), String> {
1480                        Ok(())
1481                    }
1482                ),
1483                "safe",
1484            ),
1485            (
1486                parse_quote!(
1487                    pub fn generic<const N: usize>() -> Result<(), String> {
1488                        Ok(())
1489                    }
1490                ),
1491                "type parameters",
1492            ),
1493            (
1494                parse_quote!(
1495                    pub extern "C" fn foreign() -> Result<(), String> {
1496                        Ok(())
1497                    }
1498                ),
1499                "Rust functions",
1500            ),
1501            (
1502                parse_quote!(
1503                    pub fn method(&self) -> Result<(), String> {
1504                        Ok(())
1505                    }
1506                ),
1507                "receiver",
1508            ),
1509            (
1510                parse_quote!(
1511                    pub fn pattern((a, b): (String, String)) -> Result<(), String> {
1512                        Ok(())
1513                    }
1514                ),
1515                "simple names",
1516            ),
1517            (
1518                parse_quote!(
1519                    pub fn reference() -> &str {
1520                        ""
1521                    }
1522                ),
1523                "an owned value",
1524            ),
1525            (
1526                parse_quote!(
1527                    pub fn generic_problem() -> Result<String, ToolProblem<String>> {
1528                        Ok(String::new())
1529                    }
1530                ),
1531                "ToolProblem and NoAnswer take no type argument",
1532            ),
1533            (
1534                parse_quote!(
1535                    pub fn two(a: Context, b: &Context) -> Result<(), String> {
1536                        Ok(())
1537                    }
1538                ),
1539                "at most one",
1540            ),
1541        ] {
1542            let error = expand_tool(&proc_macro2::TokenStream::new(), &function).unwrap_err();
1543            assert!(error.to_string().contains(message), "{error}");
1544        }
1545    }
1546
1547    #[test]
1548    fn sync_and_async_adapters_keep_the_original_function_and_inject_context() {
1549        let sync: ItemFn = parse_quote!(
1550            #[doc = "Searches documents."]
1551            pub fn search(context: &Context, query: String) -> Result<String, ToolProblem> {
1552                Ok(query)
1553            }
1554        );
1555        let tokens = expand_tool(&proc_macro2::TokenStream::new(), &sync).unwrap();
1556        syn::parse2::<syn::File>(tokens.clone()).unwrap();
1557        let source = tokens.to_string();
1558        assert!(source.contains("pub fn search"));
1559        assert!(source.contains("__flow_tool_search"));
1560        assert!(source.contains("Searches documents."));
1561        let decoded = source
1562            .find("let __flow_argument_0 = match args . take :: < String > (\"query\")")
1563            .expect("the argument is decoded");
1564        let finished = source
1565            .find("args . finish ()")
1566            .expect("leftover bytes are refused");
1567        let invoked = source
1568            .find("search (_context , __flow_argument_0)")
1569            .expect("the author's function is called with the decoded argument");
1570        assert!(decoded < finished && finished < invoked, "{source}");
1571        let asynchronous: ItemFn = parse_quote!(
1572            pub async fn wait(context: Context) -> Result<String, String> {
1573                Ok(String::new())
1574            }
1575        );
1576        let source = expand_tool(&proc_macro2::TokenStream::new(), &asynchronous)
1577            .unwrap()
1578            .to_string();
1579        assert!(source.contains("block_on"));
1580        assert!(source.contains("_context . clone"));
1581        assert!(
1582            source.contains("Result :: < _ , :: flow_toolkit :: NoAnswer > :: Ok"),
1583            "a return type other than Result<R, ToolProblem> or Result<R, NoAnswer> is always a value: {source}"
1584        );
1585    }
1586
1587    #[test]
1588    fn a_host_type_is_a_nongeneric_tuple_struct_holding_one_string() {
1589        let message = "a host type is a nongeneric tuple struct with one String field";
1590        for source in [
1591            "pub struct Session<T>(T);",
1592            "pub struct Session { handle: String }",
1593            "pub struct Session(u64);",
1594            "pub struct Session(String, String);",
1595            "pub enum Session { Open(String) }",
1596        ] {
1597            let input = syn::parse_str::<DeriveInput>(source).unwrap();
1598            let error = expand_handle(&input).unwrap_err();
1599            assert_eq!(error.to_string(), message, "{source}");
1600            assert!(error.to_compile_error().to_string().contains(message));
1601        }
1602        let input = syn::parse_str::<DeriveInput>("pub struct Session(String);").unwrap();
1603        syn::parse2::<syn::File>(expand_handle(&input).unwrap()).unwrap();
1604    }
1605
1606    #[test]
1607    fn a_flow_attribute_on_a_type_names_a_std_declaration_or_points_to_the_handle_derive() {
1608        let message = "expected #[flow(std = \"module.Name\")], naming a std declaration; a host type derives Handle";
1609        for source in [
1610            "#[flow(other)] pub struct Session(String);",
1611            "#[flow(opaque)] pub struct Session(String);",
1612            "#[flow(name = \"code.Bundle\")] pub struct Bundle(Encoded);",
1613        ] {
1614            let input = syn::parse_str::<DeriveInput>(source).unwrap();
1615            assert_eq!(
1616                expand_data(&input).unwrap_err().to_string(),
1617                message,
1618                "{source}"
1619            );
1620        }
1621    }
1622
1623    #[test]
1624    fn a_std_declaration_is_named_as_module_dot_name() {
1625        for (source, message) in [
1626            (
1627                "#[flow(std = \"Bundle\")] pub struct Bundle(Encoded);",
1628                "`Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1629            ),
1630            (
1631                "#[flow(std = \"code.bundle\")] pub struct Bundle(Encoded);",
1632                "`code.bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1633            ),
1634            (
1635                "#[flow(std = \"Code.Bundle\")] pub struct Bundle(Encoded);",
1636                "`Code.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1637            ),
1638            (
1639                "#[flow(std = \"code.Bundel\")] pub struct Bundle(Encoded);",
1640                "`code.Bundel` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1641            ),
1642            (
1643                "#[flow(std = \"cod.Bundle\")] pub struct Bundle(Encoded);",
1644                "`cod.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1645            ),
1646            (
1647                "#[flow(std = \"std@v1/code.Bundle\")] pub struct Bundle(Encoded);",
1648                "`std@v1/code.Bundle` names no std declaration: expected \"module.Name\", such as \"code.Bundle\"",
1649            ),
1650            (
1651                "#[flow(std = code.Bundle)] pub struct Bundle(Encoded);",
1652                "`std` takes a string literal, \"module.Name\"",
1653            ),
1654            (
1655                "#[flow(std = \"code.Bundle\")] #[flow(std = \"code.Checked\")] pub struct Bundle(Encoded);",
1656                "a type names one std declaration",
1657            ),
1658        ] {
1659            let input = syn::parse_str::<DeriveInput>(source).unwrap();
1660            assert_eq!(
1661                expand_data(&input).unwrap_err().to_string(),
1662                message,
1663                "{source}"
1664            );
1665        }
1666    }
1667
1668    #[test]
1669    fn a_std_declarations_rust_type_holds_its_value_in_one_std_value() {
1670        let shape = "a std declaration's Rust type is a tuple struct holding its value in one flow_toolkit::Encoded field, beside any PhantomData";
1671        for (source, message) in [
1672            (
1673                "#[flow(std = \"code.Bundle\")] pub struct Bundle { value: Encoded }",
1674                shape,
1675            ),
1676            (
1677                "#[flow(std = \"code.Bundle\")] pub enum Bundle { Value(Encoded) }",
1678                shape,
1679            ),
1680            (
1681                "#[flow(std = \"code.Bundle\")] pub struct Bundle(Encoded, Encoded);",
1682                shape,
1683            ),
1684            (
1685                "#[flow(std = \"code.Bundle\")] pub struct Bundle(String);",
1686                "a std declaration's value is held in a flow_toolkit::Encoded",
1687            ),
1688        ] {
1689            let input = syn::parse_str::<DeriveInput>(source).unwrap();
1690            assert_eq!(
1691                expand_data(&input).unwrap_err().to_string(),
1692                message,
1693                "{source}"
1694            );
1695        }
1696        for source in [
1697            "#[flow(std = \"code.Bundle\")] pub struct Bundle(pub flow_toolkit::Encoded);",
1698            "#[flow(std = \"code.LocalRef\")] pub struct LocalRef<T>(Encoded, PhantomData<T>);",
1699        ] {
1700            let input = syn::parse_str::<DeriveInput>(source).unwrap();
1701            syn::parse2::<syn::File>(expand_data(&input).unwrap()).unwrap();
1702        }
1703    }
1704
1705    #[test]
1706    fn record_and_enum_derives_reject_rust_shapes_without_flow_data_correspondence() {
1707        for input in [
1708            parse_quote!(
1709                struct Pair(String, String);
1710            ),
1711            parse_quote!(
1712                struct Nothing(PhantomData<String>);
1713            ),
1714            parse_quote!(
1715                struct Unit;
1716            ),
1717            parse_quote!(union Bits { bits:u64, number:f64 }),
1718        ] {
1719            assert!(expand_data(&input).is_err());
1720        }
1721        let input: DeriveInput = parse_quote!(
1722            pub enum Choice {
1723                Empty,
1724                One(String),
1725                Pair(String, String),
1726                Named { note: Option<String> },
1727            }
1728        );
1729        syn::parse2::<syn::File>(expand_data(&input).unwrap()).unwrap();
1730    }
1731
1732    #[test]
1733    fn a_one_field_tuple_struct_is_a_newtype_beside_any_phantom_data() {
1734        for input in [
1735            parse_quote!(
1736                pub struct UserId(pub String);
1737            ),
1738            parse_quote!(
1739                pub struct Labeled<T>(pub Vec<T>);
1740            ),
1741            parse_quote!(
1742                pub struct Id<T>(pub String, PhantomData<T>);
1743            ),
1744            parse_quote!(
1745                pub struct Tagged<T>(::core::marker::PhantomData<T>, pub String);
1746            ),
1747        ] {
1748            let input: DeriveInput = input;
1749            let expanded = expand_data(&input).unwrap();
1750            assert!(
1751                expanded.to_string().contains("newtype {")
1752                    && expanded.to_string().contains("public : true"),
1753                "{expanded}"
1754            );
1755            syn::parse2::<syn::File>(expanded).unwrap();
1756        }
1757        let renamed: DeriveInput = parse_quote!(
1758            pub struct UserId(#[flow(name = "id")] pub String);
1759        );
1760        assert_eq!(
1761            expand_data(&renamed).unwrap_err().to_string(),
1762            "a newtype's field has no Flow name to rename"
1763        );
1764    }
1765
1766    #[test]
1767    fn a_field_attribute_other_than_a_string_name_is_a_compile_error() {
1768        for (input, expected) in [
1769            (
1770                parse_quote!(
1771                    pub struct Record {
1772                        #[flow(rename = "x")]
1773                        value: String,
1774                    }
1775                ),
1776                "expected #[flow(name = \"...\")]",
1777            ),
1778            (
1779                parse_quote!(
1780                    pub struct Record {
1781                        #[flow(skip)]
1782                        value: String,
1783                    }
1784                ),
1785                "expected #[flow(name = \"...\")]",
1786            ),
1787            (
1788                parse_quote!(
1789                    pub struct Record {
1790                        #[flow(name = x)]
1791                        value: String,
1792                    }
1793                ),
1794                "`name` takes a string literal",
1795            ),
1796            (
1797                parse_quote!(
1798                    pub struct Record {
1799                        #[flow(name = "a")]
1800                        #[flow(name = "b")]
1801                        value: String,
1802                    }
1803                ),
1804                "a field is renamed once",
1805            ),
1806            (
1807                parse_quote!(
1808                    pub enum Choice {
1809                        Named {
1810                            #[flow(nme = "x")]
1811                            value: String,
1812                        },
1813                    }
1814                ),
1815                "expected #[flow(name = \"...\")]",
1816            ),
1817        ] {
1818            let input: DeriveInput = input;
1819            let error = expand_data(&input).expect_err("a malformed field attribute is refused");
1820            assert_eq!(
1821                error.to_string(),
1822                expected,
1823                "the refusal names the accepted form"
1824            );
1825        }
1826        let renamed: DeriveInput = parse_quote!(
1827            pub struct Record {
1828                #[flow(name = "wire")]
1829                r#value: String,
1830            }
1831        );
1832        let tokens = expand_data(&renamed)
1833            .expect("a string name is accepted")
1834            .to_string();
1835        assert!(
1836            tokens.contains("\"wire\"") && !tokens.contains("\"value\""),
1837            "the field crosses under its declared name: {tokens}"
1838        );
1839        let field: syn::Field = syn::Field::parse_unnamed
1840            .parse2(quote! { String })
1841            .expect("an unnamed field parses");
1842        assert!(
1843            field_name(&field).is_err() && field_ident(&field).is_err(),
1844            "an unnamed field has no wire name"
1845        );
1846    }
1847}