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
use proc_macro2::{TokenStream, TokenTree};
use quote::{ToTokens, quote};
use syn::{FnArg, ImplItem, ImplItemFn, ItemImpl, ReturnType, Type, Visibility, parse_quote};

pub(crate) fn expand(mut implementation: ItemImpl) -> syn::Result<TokenStream> {
    if implementation.trait_.is_some() {
        return Err(syn::Error::new_spanned(
            &implementation,
            "`notification` goes on an inherent impl, such as `impl InvoicePaid { .. }`",
        ));
    }

    let mut messages = Vec::new();
    let mut channels = None;
    let mut notifiable: Option<TokenStream> = None;
    let mut remaining = Vec::new();
    for item in std::mem::take(&mut implementation.items) {
        let ImplItem::Fn(mut method) = item else {
            remaining.push(item);
            continue;
        };
        let name = method.sig.ident.to_string();
        let via = take_via(&mut method)?;
        let message = match via {
            Some(channel) => Some(Message::Via(channel)),
            None if name == "mail" => Some(Message::Mail),
            None if name == "sms" => Some(Message::Sms),
            None if name == "slack" => Some(Message::Via(quote!(::laravel::notification::Slack))),
            None if name == "channels" => None,
            None => {
                remaining.push(ImplItem::Fn(method));
                continue;
            }
        };

        let ty = notifiable_of(&method)?;
        match &notifiable {
            None => notifiable = Some(ty.to_token_stream()),
            Some(existing) if existing.to_string() == ty.to_token_stream().to_string() => {}
            Some(existing) => {
                return Err(syn::Error::new_spanned(
                    ty,
                    format!(
                        "every method takes the same notifiable, `&{existing}`; write another `#[notification]` impl for each notifiable type"
                    ),
                ));
            }
        }
        method.vis = Visibility::Inherited;
        match message {
            Some(message) => {
                wrap_in_result(&mut method);
                messages.push((message, method));
            }
            None => channels = Some(method),
        }
    }

    // Mail and SMS come first, then package channels in the order they're written...
    messages.sort_by_key(|(message, _)| match message {
        Message::Mail => 0,
        Message::Sms => 1,
        Message::Via(_) => 2,
    });
    let Some(notifiable) = notifiable.filter(|_| !messages.is_empty()) else {
        return Err(syn::Error::new_spanned(
            &implementation.self_ty,
            "a notification needs a `mail`, `sms`, or `slack` method, or a `#[via(Channel)]` method",
        ));
    };

    let ty = implementation.self_ty.to_token_stream();
    let (impl_generics, _, where_clause) = implementation.generics.split_for_impl();
    let (impl_generics, where_clause) = (impl_generics.to_token_stream(), where_clause.to_token_stream());
    let listed: Vec<TokenStream> = messages
        .iter()
        .map(|(message, _)| match message {
            Message::Mail => quote!(::laravel::notification::Mail),
            Message::Sms => quote!(::laravel::notification::Sms),
            Message::Via(channel) => channel.clone(),
        })
        .collect();
    let listed = match listed.as_slice() {
        [channel] => quote!(#channel),
        channels => quote!((#(#channels),*)),
    };
    let traits: Vec<TokenStream> = messages
        .into_iter()
        .map(|(message, mut method)| {
            let to = match message {
                Message::Mail => quote!(ToMail<#notifiable>),
                Message::Sms => quote!(ToSms<#notifiable>),
                Message::Via(channel) => {
                    method.sig.ident = syn::Ident::new("message", method.sig.ident.span());
                    quote!(ToChannel<#channel, #notifiable>)
                }
            };
            quote! {
                #[allow(refining_impl_trait)]
                impl #impl_generics ::laravel::notification::#to for #ty #where_clause {
                    #method
                }
            }
        })
        .collect();
    let remaining = (!remaining.is_empty()).then(|| {
        implementation.items = remaining;
        quote!(#implementation)
    });

    Ok(quote! {
        #remaining

        impl #impl_generics ::laravel::notification::Notification<#notifiable> for #ty #where_clause {
            type Channels = #listed;

            #channels
        }

        #(#traits)*
    })
}

/// The message a `#[notification]` method builds.
enum Message {
    Mail,
    Sms,
    /// A package channel, from `#[via(Slack)]`.
    Via(TokenStream),
}

/// Remove the method's `#[via(Channel)]` attribute, returning the channel...
fn take_via(method: &mut ImplItemFn) -> syn::Result<Option<TokenStream>> {
    let mut channel = None;
    let mut error = None;
    method.attrs.retain(|attribute| {
        if !attribute.path().is_ident("via") {
            return true;
        }
        match (attribute.parse_args::<syn::Path>(), &channel) {
            (Ok(path), None) => channel = Some(path.to_token_stream()),
            (Ok(_), Some(_)) => {
                error = Some(syn::Error::new_spanned(attribute, "a method sends one channel"));
            }
            (Err(_), _) => {
                error = Some(syn::Error::new_spanned(
                    attribute,
                    "`via` names one channel, as in `#[via(Slack)]`",
                ));
            }
        }
        false
    });

    error.map_or(Ok(channel), Err)
}

/// The name a channel is registered under, when the attribute gives one.
#[derive(Default)]
pub(crate) struct ChannelOptions {
    name: Option<syn::LitStr>,
}

impl syn::parse::Parse for ChannelOptions {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        if input.is_empty() {
            return Ok(Self::default());
        }
        let option: syn::MetaNameValue = input.parse()?;
        if !option.path.is_ident("name") || !input.is_empty() {
            return Err(syn::Error::new_spanned(
                option.path,
                "`channel` takes one option, as in `#[channel(name = \"slack\")]`",
            ));
        }

        Ok(Self {
            name: Some(crate::syntax::string(&option.value, "name")?),
        })
    }
}

pub(crate) fn expand_channel(options: ChannelOptions, implementation: ItemImpl) -> syn::Result<TokenStream> {
    let ident = crate::syntax::inherent_impl(&implementation, "channel")?;
    let ty = &implementation.self_ty;
    let send = crate::syntax::method(&implementation, "send")
        .ok_or_else(|| syn::Error::new_spanned(ty, "a channel requires an async `send(route, message)` function"))?;
    let usage = "`send` is an async function that takes the route and the message, as in `async fn send(webhook: String, message: SlackMessage) -> laravel::Result<()>`";
    crate::syntax::require_async(&send.sig, usage)?;
    let arguments: Vec<&Type> = send
        .sig
        .inputs
        .iter()
        .filter_map(|argument| match argument {
            FnArg::Typed(argument) => Some(&*argument.ty),
            FnArg::Receiver(_) => None,
        })
        .collect();
    let [route, message] = arguments.as_slice() else {
        return Err(syn::Error::new_spanned(&send.sig, usage));
    };
    if send.sig.inputs.len() != 2 {
        return Err(syn::Error::new_spanned(&send.sig, usage));
    }
    let check = crate::syntax::method(&implementation, "check").map(|_| {
        quote! {
            fn check(__laravel_message: &Self::Message) -> ::laravel::Result<()> {
                <#ty>::check(__laravel_message)
            }
        }
    });

    let name = crate::syntax::registered_name(options.name.as_ref(), ident);

    Ok(quote! {
        #implementation

        impl ::laravel::notification::Channel for #ty {
            const NAME: &'static str = #name;
            type Route = #route;
            type Message = #message;

            fn send(
                __laravel_route: Self::Route,
                __laravel_message: Self::Message,
            ) -> impl ::core::future::Future<Output = ::laravel::Result<()>> + ::core::marker::Send {
                <#ty>::send(__laravel_route, __laravel_message)
            }

            #check
        }

        ::laravel::__inventory::submit! {
            ::laravel::queue::__Registration::new::<::laravel::notification::__Deliver<#ty>>()
        }
    })
}

/// Let a method that can't fail return its message: a return type other than a `Result`
/// becomes `laravel::Result<..>`, and the body runs in a closure, so `return` still works,
/// whose value is wrapped in `Ok`...
fn wrap_in_result(method: &mut ImplItemFn) {
    let ReturnType::Type(_, ty) = &method.sig.output else {
        return;
    };
    if matches!(&**ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "Result")) {
        return;
    }
    let ty = ty.to_token_stream();
    let block = &method.block;
    // A closure can't name an `impl Trait` type, so it infers those...
    let opaque = ty
        .clone()
        .into_iter()
        .any(|token| matches!(token, TokenTree::Ident(ident) if ident == "impl"));
    let closure = if opaque {
        quote!(|| #block)
    } else {
        quote!(|| -> #ty #block)
    };
    method.block = parse_quote!({ ::core::result::Result::Ok((#closure)()) });
    method.sig.output = parse_quote!(-> ::laravel::Result<#ty>);
}

/// The notifiable type that a `mail`, `sms`, `slack`, `#[via]`, or `channels` method takes as `&N`, after `&self`...
fn notifiable_of(method: &ImplItemFn) -> syn::Result<&Type> {
    let name = &method.sig.ident;
    if let Some(asyncness) = &method.sig.asyncness {
        return Err(syn::Error::new_spanned(
            asyncness,
            format!("`{name}` can't be async; load what it needs before you send the notification"),
        ));
    }
    let mut inputs = method.sig.inputs.iter();
    let receiver = matches!(
        inputs.next(),
        Some(FnArg::Receiver(receiver)) if receiver.reference.is_some() && receiver.mutability.is_none()
    );
    let notifiable = match inputs.next() {
        Some(FnArg::Typed(argument)) => match &*argument.ty {
            Type::Reference(reference) if reference.mutability.is_none() => Some(&*reference.elem),
            _ => None,
        },
        _ => None,
    };

    match notifiable {
        Some(notifiable) if receiver => Ok(notifiable),
        _ => Err(syn::Error::new_spanned(
            &method.sig,
            format!("`{name}` takes `&self` and the notifiable, as in `fn {name}(&self, user: &User)`"),
        )),
    }
}