laravel-rust-queue-macros 0.1.0

Laravel for Rust's procedural macros for jobs, events, notifications and workflows, re-exported by `laravel-rust`
Documentation
//! The parts that the methods generated for jobs, queued listeners, callbacks, job middleware,
//! and Slack actions share: the arguments the queue passes in, and the services and config
//! sections the queue resolves.

use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{FnArg, Ident, Signature, Type};

use crate::syntax::{self, is_dependency, is_reference_to};

/// A reference the queue passes to a generated method, which hands it on to the user's method.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Provided {
    Attempt,
    Batch,
    Error,
    Interaction,
    Run,
}

impl Provided {
    fn name(self) -> &'static str {
        match self {
            Self::Attempt => "Attempt",
            Self::Batch => "Batch",
            Self::Error => "Error",
            Self::Interaction => "Interaction",
            Self::Run => "Run",
        }
    }

    fn binding(self) -> TokenStream {
        match self {
            Self::Attempt => quote!(__laravel_attempt),
            Self::Batch => quote!(__laravel_batch),
            Self::Error => quote!(__laravel_error),
            Self::Interaction => quote!(__laravel_interaction),
            Self::Run => quote!(__laravel_run),
        }
    }
}

/// How a generated method calls the user's: the dependencies it resolves first, then the arguments.
pub(crate) struct Arguments {
    pub(crate) resolve: Vec<TokenStream>,
    pub(crate) values: Vec<TokenStream>,
    /// The bindings `resolve` declares, in order.
    pub(crate) resolved: Vec<TokenStream>,
}

/// Pass each `provided` reference at most once and resolve `Inject<T>` and `Section<T>` for the
/// job, listener or callback `owner` names. Any other argument is `misplaced`.
pub(crate) fn arguments<'a>(
    method: &Ident,
    types: impl IntoIterator<Item = &'a Type>,
    provided: &[Provided],
    owner: &TokenStream,
    misplaced: &str,
) -> syn::Result<Arguments> {
    let mut passed = Vec::new();
    let mut arguments = Arguments {
        resolve: Vec::new(),
        values: Vec::new(),
        resolved: Vec::new(),
    };
    for (index, ty) in types.into_iter().enumerate() {
        if let Some(&reference) = provided.iter().find(|reference| is_reference_to(ty, reference.name())) {
            if passed.contains(&reference) {
                let shown = if reference == Provided::Error {
                    "laravel::Error"
                } else {
                    reference.name()
                };
                return Err(syn::Error::new_spanned(
                    ty,
                    format!("`{method}` takes at most one `&{shown}`"),
                ));
            }
            passed.push(reference);
            arguments.values.push(reference.binding());
        } else if is_dependency(ty) {
            let binding = format_ident!("__laravel_dependency_{index}");
            arguments.resolve.push(quote_spanned! {ty.span()=>
                let #binding: #ty = <#ty as ::laravel::container::__Injectable>::resolve(#owner).await?;
            });
            arguments.values.push(quote!(#binding));
            arguments.resolved.push(quote!(#binding));
        } else {
            return Err(syn::Error::new_spanned(ty, misplaced));
        }
    }

    Ok(arguments)
}

/// Call `callee` with `first`, then the rest of the method's arguments, and convert its result.
pub(crate) fn call(
    callee: TokenStream,
    first: TokenStream,
    signature: &Signature,
    provided: &[Provided],
    owner: TokenStream,
    misplaced: &str,
) -> syn::Result<TokenStream> {
    let types = signature.inputs.iter().skip(1).map(|argument| match argument {
        FnArg::Typed(argument) => &*argument.ty,
        FnArg::Receiver(_) => unreachable!("only the first argument can be a receiver"),
    });
    let Arguments { resolve, values, .. } = arguments(&signature.ident, types, provided, &owner, misplaced)?;
    let result = quote_spanned! {syntax::output_span(signature)=>
        ::laravel::queue::JobResult::into_result(__laravel_output)
    };

    Ok(quote! {
        #(#resolve)*
        let __laravel_output = #callee(#first, #(#values),*).await;
        #result
    })
}