mf_expression/functions/
method.rs

1//! 方法注册表模块
2//!
3//! 管理各种类型的方法,包括日期方法等
4
5use crate::functions::date_method::DateMethod;
6use crate::functions::defs::FunctionDefinition;
7use nohash_hasher::{BuildNoHashHasher, IsEnabled};
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::fmt::Display;
11use std::rc::Rc;
12use strum::IntoEnumIterator;
13
14impl IsEnabled for DateMethod {}
15
16/// 方法类型枚举
17///
18/// 定义了所有可用的方法类型
19#[derive(Debug, PartialEq, Eq, Clone)]
20pub enum MethodKind {
21    /// 日期方法
22    DateMethod(DateMethod),
23}
24
25impl TryFrom<&str> for MethodKind {
26    type Error = strum::ParseError;
27
28    /// 从字符串解析方法类型
29    ///
30    /// # 参数
31    /// * `value` - 方法名称字符串
32    ///
33    /// # 返回值
34    /// * `Ok(MethodKind)` - 成功解析的方法类型
35    /// * `Err` - 未知的方法名称
36    fn try_from(value: &str) -> Result<Self, Self::Error> {
37        DateMethod::try_from(value).map(MethodKind::DateMethod)
38    }
39}
40
41impl Display for MethodKind {
42    fn fmt(
43        &self,
44        f: &mut std::fmt::Formatter<'_>,
45    ) -> std::fmt::Result {
46        match self {
47            MethodKind::DateMethod(d) => write!(f, "{d}"),
48        }
49    }
50}
51
52/// 方法注册表
53///
54/// 负责管理和查找各种类型的方法定义
55pub struct MethodRegistry {
56    /// 日期方法映射表:方法枚举 -> 方法定义
57    date_methods: HashMap<
58        DateMethod,
59        Rc<dyn FunctionDefinition>,
60        BuildNoHashHasher<DateMethod>,
61    >,
62}
63
64impl MethodRegistry {
65    // 线程本地存储的方法注册表实例
66    thread_local!(
67        static INSTANCE: RefCell<MethodRegistry> = RefCell::new(MethodRegistry::new_internal())
68    );
69
70    /// 根据方法类型获取方法定义
71    ///
72    /// # 参数
73    /// * `kind` - 方法类型
74    ///
75    /// # 返回值
76    /// * `Some(Rc<dyn FunctionDefinition>)` - 找到的方法定义
77    /// * `None` - 未找到对应的方法定义
78    pub fn get_definition(
79        kind: &MethodKind
80    ) -> Option<Rc<dyn FunctionDefinition>> {
81        match kind {
82            MethodKind::DateMethod(dm) => {
83                Self::INSTANCE.with_borrow(|i| i.date_methods.get(&dm).cloned())
84            },
85        }
86    }
87
88    /// 创建内部方法注册表实例
89    ///
90    /// 初始化时自动注册所有日期方法
91    fn new_internal() -> Self {
92        // 遍历所有日期方法并创建映射
93        let date_methods =
94            DateMethod::iter().map(|i| (i.clone(), (&i).into())).collect();
95
96        Self { date_methods }
97    }
98}