function

Attribute Macro function 

Source
#[function]
Available on crate feature macros only.
Expand description

§Function Macro Documentation

This module provides a procedural macro for generating functions that can parse arguments from a string slice and execute with type-safe parameters.

§Overview

The macro transforms a Rust function into one that:

  • Takes &[String] as input
  • Validates argument count matches parameter count
  • Parses each argument to the expected type
  • Returns a FuncResult (Result<String, FunctionError>)

§Usage

§Basic Example

#[function]
fn add(a: i32, b: i32) {
    Ok((a + b).to_string())
}

This generates:

fn add(args: &[String]) -> srtemplate::prelude::FuncResult {
    srtemplate::prelude::validations::args_min_len(args, 2)?;
    srtemplate::prelude::validations::args_max_len(args, 2)?;

    let a = args[0].parse::<i32>().map_err(|_| srtemplate::prelude::FromArgsError::ParseFailed(0))?;
    let b = args[1].parse::<i32>().map_err(|_| srtemplate::prelude::FromArgsError::ParseFailed(1))?;

    Ok((a + b).to_string())
}

§Visibility

The macro preserves the original function’s visibility:

#[function]
pub fn public_function(x: f64) {
    Ok((x * 2.0).to_string())
}

§Error Handling

The generated function automatically handles:

  • Argument count validation (min and max)
  • Type parsing errors

§Implementation Details

§Function Transformation

The macro performs several transformations:

  1. Argument Validation: Adds checks for exact argument count matching parameter count
  2. Parameter Parsing: Generates code to parse each string argument to the corresponding parameter type
  3. Body Preservation: Keeps the original function body intact

§Restrictions

  1. No Receiver Parameters: Functions with self parameters are rejected
  2. Required Body: Functions must have a body
  3. Typed Parameters: All parameters must have explicit type annotations

§Error Cases

The macro will error if:

  • The function has a self parameter
  • Any parameter lacks a type annotation
  • The function lacks a body

§Technical Notes

The implementation uses:

  • venial for parsing the function syntax
  • proc_macro2 and quote for code generation
  • Span-preserving operations for better error reporting

The generated code relies on these types being in scope:

  • srtemplate::prelude::FuncResult
  • srtemplate::prelude::FromArgsError
  • srtemplate::prelude::validations functions