const-router-macros 0.1.0

Procedural macros for const-router.
Documentation
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use syn::{Error, Result};

mod handler;
mod router;

/// Builds a `const_router::Router` with routes sorted by static string key.
///
/// The first input is the fallback handler. The remaining inputs use
/// `"/path" => handler` entries separated by commas.
/// Each handler should be produced by `#[const_router::handler]`.
/// Duplicate keys are rejected at macro expansion time.
#[proc_macro]
pub fn router(input: TokenStream) -> TokenStream {
    compile(router::expand(input.into()))
}

/// Converts a synchronous or asynchronous function returning `Result` into a
/// `const_router` handler.
///
/// The function may take either no request argument or one request argument:
///
/// - `fn() -> Result<TResponse, TError>`
/// - `fn(TRequest) -> Result<TResponse, TError>`
/// - `async fn() -> Result<TResponse, TError>`
/// - `async fn(TRequest) -> Result<TResponse, TError>`
#[proc_macro_attribute]
pub fn handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    if !attr.is_empty() {
        return Error::new(
            proc_macro2::Span::call_site(),
            "`handler` does not accept arguments",
        )
        .into_compile_error()
        .into();
    }

    compile(handler::expand(item.into()))
}

fn compile(result: Result<TokenStream2>) -> TokenStream {
    result.unwrap_or_else(Error::into_compile_error).into()
}