bstack_raii_derive 0.1.0

Procedural macros for bstack_raii (#[bstack_block], bstack_move!, bstack_cast!)
Documentation
//! Implementation of the `bstack_cast!(expr as Target)` macro.
//!
//! A function-like macro can't observe the surrounding `let x: T = …`
//! annotation, so the target type is given explicitly with `as`, and the
//! direction is chosen from the target's tokens:
//!
//! * `expr as BStackOwnedSlice`     — owned upcast     → `BStackOwned::into_slice`
//! * `expr as BStackOwned<X, _>`    — owned downcast   → `BStackCastInto::cast_into::<X>`
//! * `slice as X` (a block type)    — borrowed downcast → `BStackCastAs::cast_as::<X>`
//! * `slice as Foreign<X>`          — normal → foreign  → `Foreign::from_local`
//! * `foreign as BStackRef<X>`      — foreign → normal  → `Foreign::into_local`
//!
//! The borrowed upcast (`X` → `BStackSlice`) needs a stack, so it is the
//! generated `handle.as_slice(stack)` method rather than a `bstack_cast!` form.

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Error, ExprCast, GenericArgument, PathArguments, Type};

pub fn expand(input: TokenStream) -> syn::Result<TokenStream> {
    let cast: ExprCast = syn::parse2(input).map_err(|_| {
        Error::new(
            proc_macro2::Span::call_site(),
            "[BSTACK0701] bstack_cast! expects `expr as Target` (e.g. `bstack_cast!(slice as BStackOwned<X, _>)`)",
        )
    })?;
    let expr = &cast.expr;
    let ty = &*cast.ty;

    let Type::Path(tp) = ty else {
        return Err(Error::new_spanned(
            ty,
            "[BSTACK0702] bstack_cast!: target must be a type path",
        ));
    };
    let seg = tp.path.segments.last().expect("non-empty path");

    let tokens = match seg.ident.to_string().as_str() {
        "BStackOwnedSlice" => quote!((#expr).into_slice()),
        "BStackSlice" => {
            return Err(Error::new_spanned(
                ty,
                "[BSTACK0703] bstack_cast! can't build a borrowed slice (it needs a stack); \
                 use `handle.as_slice(stack)` instead",
            ));
        }
        "BStackOwned" => {
            let inner = first_type_arg(seg)?;
            quote!(::bstack_raii::BStackCastInto::cast_into::<#inner>(#expr))
        }
        // normal → foreign: a `BStackSlice` into some registered file → `Foreign<T>`
        // naming it (`None` if the file isn't attached). No I/O.
        "Foreign" => {
            let inner = first_type_arg(seg)?;
            quote!(::bstack_raii::Foreign::<#inner>::from_local(&#expr))
        }
        // foreign → normal: a `Foreign<T>` → its offset-only `BStackRef<T>` in the
        // target file (`None` unless that file is `SELF`/attached). No I/O.
        "BStackRef" => quote!((#expr).into_local()),
        // A concrete block type: borrowed downcast off a `BStackSlice`.
        _ => quote!(::bstack_raii::BStackCastAs::cast_as::<#ty>(&#expr)),
    };
    Ok(tokens)
}

/// Extract `X` from a `BStackOwned<X, ..>` target.
fn first_type_arg(seg: &syn::PathSegment) -> syn::Result<&Type> {
    if let PathArguments::AngleBracketed(ab) = &seg.arguments {
        for arg in &ab.args {
            if let GenericArgument::Type(t) = arg {
                return Ok(t);
            }
        }
    }
    Err(Error::new_spanned(
        seg,
        "[BSTACK0704] expected `BStackOwned<BlockType, _>` for an owned downcast",
    ))
}