#[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:
- Argument Validation: Adds checks for exact argument count matching parameter count
- Parameter Parsing: Generates code to parse each string argument to the corresponding parameter type
- Body Preservation: Keeps the original function body intact
§Restrictions
- No Receiver Parameters: Functions with
selfparameters are rejected - Required Body: Functions must have a body
- Typed Parameters: All parameters must have explicit type annotations
§Error Cases
The macro will error if:
- The function has a
selfparameter - Any parameter lacks a type annotation
- The function lacks a body
§Technical Notes
The implementation uses:
venialfor parsing the function syntaxproc_macro2andquotefor code generation- Span-preserving operations for better error reporting
The generated code relies on these types being in scope:
srtemplate::prelude::FuncResultsrtemplate::prelude::FromArgsErrorsrtemplate::prelude::validationsfunctions