Skip to main content

shape_ast/error/
macros.rs

1//! Error handling macros for reducing boilerplate in function implementations
2//!
3//! These macros provide consistent error messages and reduce code duplication
4//! across the runtime evaluation functions.
5
6/// Validates that exactly N arguments were passed to a function.
7///
8/// # Example
9/// ```ignore
10/// require_args!(args, 2, "add");
11/// // Equivalent to:
12/// // if args.len() != 2 {
13/// //     return Err(ShapeError::RuntimeError {
14/// //         message: "add() requires exactly 2 argument(s)".to_string(),
15/// //         location: None,
16/// //     });
17/// // }
18/// ```
19#[macro_export]
20macro_rules! require_args {
21    ($args:expr, $count:expr, $func:expr) => {
22        if $args.len() != $count {
23            return Err($crate::error::ShapeError::RuntimeError {
24                message: format!(
25                    "{}() requires exactly {} argument{}",
26                    $func,
27                    $count,
28                    if $count == 1 { "" } else { "s" }
29                ),
30                location: None,
31            });
32        }
33    };
34}
35
36/// Validates that at least N arguments were passed to a function.
37///
38/// # Example
39/// ```ignore
40/// require_min_args!(args, 1, "sum");
41/// // Equivalent to:
42/// // if args.len() < 1 {
43/// //     return Err(ShapeError::RuntimeError {
44/// //         message: "sum() requires at least 1 argument(s)".to_string(),
45/// //         location: None,
46/// //     });
47/// // }
48/// ```
49#[macro_export]
50macro_rules! require_min_args {
51    ($args:expr, $min:expr, $func:expr) => {
52        if $args.len() < $min {
53            return Err($crate::error::ShapeError::RuntimeError {
54                message: format!(
55                    "{}() requires at least {} argument{}",
56                    $func,
57                    $min,
58                    if $min == 1 { "" } else { "s" }
59                ),
60                location: None,
61            });
62        }
63    };
64}
65
66/// Validates that arguments count is within a range.
67///
68/// # Example
69/// ```ignore
70/// require_args_range!(args, 1, 3, "range");
71/// ```
72#[macro_export]
73macro_rules! require_args_range {
74    ($args:expr, $min:expr, $max:expr, $func:expr) => {
75        if $args.len() < $min || $args.len() > $max {
76            return Err($crate::error::ShapeError::RuntimeError {
77                message: format!(
78                    "{}() requires between {} and {} arguments, got {}",
79                    $func,
80                    $min,
81                    $max,
82                    $args.len()
83                ),
84                location: None,
85            });
86        }
87    };
88}