autocontext 0.1.1

Procedural macro that automatically attaches anyhow context to function results
Documentation
//! # autocontext
//!
//! A procedural macro that automatically attaches [`anyhow`] context to
//! function results, eliminating boilerplate `.context("...")` calls.
//!
//! ## Quick start
//!
//! ```rust
//! use autocontext::autocontext;
//! use anyhow::{bail, Result};
//!
//! #[autocontext]
//! fn load_config(path: &str) -> Result<String> {
//!     let raw = std::fs::read_to_string(path)?;
//!     Ok(raw)
//! }
//! ```
//!
//! ## With argument logging
//!
//! ```rust
//! # use autocontext::autocontext;
//! # use anyhow::Result;
//! #[autocontext(args(path, retries))]
//! fn connect(path: &str, retries: u32) -> Result<()> {
//!     # Ok(())
//! }
//! // On error: "connect: path=\"/tmp/sock\" retries=3"
//! ```

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    Expr, Ident, ItemFn, LitStr, ReturnType, Token,
};

// ─────────────────────────────────────────────────────────────────────────────
// Attribute arguments
// ─────────────────────────────────────────────────────────────────────────────

/// Parsed arguments of the `#[autocontext(...)]` attribute.
///
/// Supported forms (combinable):
///   - `#[autocontext]`
///   - `#[autocontext("custom msg")]`
///   - `#[autocontext(per_try)]`
///   - `#[autocontext(args(a, b, c))]`
///   - `#[autocontext(per_try, args(a, b))]`
///   - `#[autocontext("msg", args(a, b))]`
struct AttrArgs {
    /// Optional user-supplied context message.
    message: Option<String>,
    /// When `true`, each `?` in the body gets its own `.with_context(...)`.
    per_try: bool,
    /// Argument identifiers to include in the context via `{:?}`.
    log_args: Vec<Ident>,
}

impl Parse for AttrArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut message = None;
        let mut per_try = false;
        let mut log_args = Vec::new();

        // Parse comma-separated items: "msg", per_try, args(...)
        let items = Punctuated::<AttrItem, Token![,]>::parse_terminated(input)?;

        for item in items {
            match item {
                AttrItem::Message(s) => message = Some(s),
                AttrItem::PerTry => per_try = true,
                AttrItem::Args(idents) => log_args = idents,
            }
        }

        Ok(Self {
            message,
            per_try,
            log_args,
        })
    }
}

/// A single item inside `#[autocontext(...)]`.
enum AttrItem {
    /// A string literal: `"custom message"`
    Message(String),
    /// The keyword `per_try`
    PerTry,
    /// `args(ident1, ident2, ...)`
    Args(Vec<Ident>),
}

impl Parse for AttrItem {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        // String literal
        if input.peek(LitStr) {
            let lit: LitStr = input.parse()?;
            return Ok(AttrItem::Message(lit.value()));
        }

        // Identifier: either `per_try` or `args`
        if input.peek(Ident) {
            let ident: Ident = input.parse()?;

            if ident == "per_try" {
                return Ok(AttrItem::PerTry);
            }

            if ident == "args" {
                // Expect parenthesized list: args(a, b, c)
                let content;
                syn::parenthesized!(content in input);
                let idents = Punctuated::<Ident, Token![,]>::parse_terminated(&content)?;
                return Ok(AttrItem::Args(idents.into_iter().collect()));
            }

            return Err(syn::Error::new(
                ident.span(),
                "expected `per_try`, `args(...)`, or a string literal",
            ));
        }

        Err(input.error("expected `per_try`, `args(...)`, or a string literal"))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Entry point
// ─────────────────────────────────────────────────────────────────────────────

/// Automatically attaches [`anyhow::Context`] to a function's `Result`.
///
/// # Attribute options
///
/// | Syntax | Effect |
/// |--------|--------|
/// | `#[autocontext]` | Context = function name |
/// | `#[autocontext("msg")]` | Context = custom string |
/// | `#[autocontext(per_try)]` | Context on every `?` |
/// | `#[autocontext(args(a, b))]` | Include `a`, `b` (via `Debug`) in message |
///
/// Options are combinable: `#[autocontext(per_try, args(id, name))]`.
#[proc_macro_attribute]
pub fn autocontext(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as AttrArgs);
    let input_fn = parse_macro_input!(item as ItemFn);

    // If the function does not return Result, emit it unchanged.
    if !returns_result(&input_fn) {
        return TokenStream::from(quote!(#input_fn));
    }

    let fn_name = input_fn.sig.ident.to_string();
    let context_msg = args.message.unwrap_or(fn_name);

    let output = if args.per_try {
        expand_per_try(&input_fn, &context_msg, &args.log_args)
    } else {
        expand_wrap(&input_fn, &context_msg, &args.log_args)
    };

    TokenStream::from(output)
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Returns `true` if the function signature declares a `Result<...>` return type.
fn returns_result(f: &ItemFn) -> bool {
    match &f.sig.output {
        ReturnType::Default => false,
        ReturnType::Type(_, ty) => {
            let tokens = quote!(#ty).to_string();
            tokens.starts_with("Result")
                || tokens.contains(":: Result")
                || tokens.contains("anyhow :: Result")
        }
    }
}

/// Builds the context expression.
///
/// - Without args: a static `&str` → uses `.context(msg)`.
/// - With args: a `format!(...)` closure → uses `.with_context(|| format!(...))`.
fn build_context_expr(msg: &str, log_args: &[Ident]) -> TokenStream2 {
    if log_args.is_empty() {
        quote! { ::anyhow::Context::context(__autocontext_result, #msg) }
    } else {
        let fmt_str = build_format_string(msg, log_args);
        let args = log_args;
        quote! {
            ::anyhow::Context::with_context(__autocontext_result, || {
                format!(#fmt_str, #(#args),*)
            })
        }
    }
}

/// Builds a format string like `"connect: path={:?} retries={:?}"`.
fn build_format_string(msg: &str, log_args: &[Ident]) -> String {
    if log_args.is_empty() {
        return msg.to_string();
    }
    let args_part: Vec<String> = log_args
        .iter()
        .map(|id| format!("{}={{:?}}", id))
        .collect();
    format!("{}: {}", msg, args_part.join(" "))
}

// ─────────────────────────────────────────────────────────────────────────────
// Expansion: wrap mode (default)
// ─────────────────────────────────────────────────────────────────────────────

fn expand_wrap(f: &ItemFn, msg: &str, log_args: &[Ident]) -> TokenStream2 {
    let attrs = &f.attrs;
    let vis = &f.vis;
    let sig = &f.sig;
    let body = &f.block;
    let is_async = sig.asyncness.is_some();

    let ret_ty = match &sig.output {
        ReturnType::Type(_, ty) => ty,
        ReturnType::Default => {
            return quote! { #(#attrs)* #vis #sig #body };
        }
    };

    let ctx_expr = build_context_expr(msg, log_args);

    if is_async {
        quote! {
            #(#attrs)*
            #vis #sig {
                let __autocontext_result: #ret_ty = async #body.await;
                #ctx_expr
            }
        }
    } else {
        quote! {
            #(#attrs)*
            #vis #sig {
                let __autocontext_result = (|| -> #ret_ty #body)();
                #ctx_expr
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Expansion: per-try mode
// ─────────────────────────────────────────────────────────────────────────────

fn expand_per_try(f: &ItemFn, msg: &str, log_args: &[Ident]) -> TokenStream2 {
    let attrs = &f.attrs;
    let vis = &f.vis;
    let sig = &f.sig;

    let mut body = (*f.block).clone();

    let mut folder = TryFolder {
        msg: msg.to_string(),
        counter: 0,
        log_args: log_args.to_vec(),
    };
    syn::visit_mut::VisitMut::visit_block_mut(&mut folder, &mut body);

    quote! {
        #(#attrs)*
        #vis #sig #body
    }
}

/// AST visitor that rewrites `Expr::Try` nodes.
struct TryFolder {
    msg: String,
    counter: u32,
    log_args: Vec<Ident>,
}

impl syn::visit_mut::VisitMut for TryFolder {
    fn visit_expr_mut(&mut self, expr: &mut Expr) {
        // Recurse into child expressions first (depth-first).
        syn::visit_mut::visit_expr_mut(self, expr);

        if let Expr::Try(try_expr) = expr {
            let inner = &try_expr.expr;
            let ctx_label = format!("{} [try #{}]", self.msg, self.counter);
            self.counter += 1;

            let wrapped: Expr = if self.log_args.is_empty() {
                // Static context — no allocation on success path.
                syn::parse_quote! {
                    ::anyhow::Context::with_context(#inner, || #ctx_label)
                }
            } else {
                // Dynamic context with argument values.
                let fmt_str = build_format_string(&ctx_label, &self.log_args);
                let args = &self.log_args;
                syn::parse_quote! {
                    ::anyhow::Context::with_context(#inner, || {
                        format!(#fmt_str, #(#args),*)
                    })
                }
            };

            *try_expr.expr = wrapped;
        }
    }
}