mf_expression/functions/
registry.rs

1//! 函数注册表模块
2//!
3//! 管理内置函数和已废弃函数的注册和查找
4
5use crate::functions::defs::FunctionDefinition;
6use crate::functions::{DeprecatedFunction, FunctionKind, InternalFunction};
7use crate::functions::mf_function::MfFunctionRegistry;
8use nohash_hasher::{BuildNoHashHasher, IsEnabled};
9use std::cell::RefCell;
10use std::collections::HashMap;
11use std::rc::Rc;
12use strum::IntoEnumIterator;
13
14impl IsEnabled for InternalFunction {}
15impl IsEnabled for DeprecatedFunction {}
16
17/// 函数注册表
18///
19/// 负责管理和查找所有可用的函数定义,包括内置函数和已废弃函数
20pub struct FunctionRegistry {
21    /// 内置函数映射表:函数枚举 -> 函数定义
22    internal_functions: HashMap<
23        InternalFunction,
24        Rc<dyn FunctionDefinition>,
25        BuildNoHashHasher<InternalFunction>,
26    >,
27    /// 已废弃函数映射表:函数枚举 -> 函数定义
28    deprecated_functions: HashMap<
29        DeprecatedFunction,
30        Rc<dyn FunctionDefinition>,
31        BuildNoHashHasher<DeprecatedFunction>,
32    >,
33}
34
35impl FunctionRegistry {
36    // 线程本地存储的注册表实例
37    thread_local!(
38        static INSTANCE: RefCell<FunctionRegistry> = RefCell::new(FunctionRegistry::new_internal())
39    );
40
41    /// 根据函数类型获取函数定义
42    ///
43    /// # 参数
44    /// * `kind` - 函数类型(内置、已废弃、闭包或自定义)
45    ///
46    /// # 返回值
47    /// * `Some(Rc<dyn FunctionDefinition>)` - 找到的函数定义
48    /// * `None` - 未找到对应的函数定义
49    pub fn get_definition(
50        kind: &FunctionKind
51    ) -> Option<Rc<dyn FunctionDefinition>> {
52        match kind {
53            FunctionKind::Internal(internal) => Self::INSTANCE
54                .with_borrow(|i| i.internal_functions.get(&internal).cloned()),
55            FunctionKind::Deprecated(deprecated) => {
56                Self::INSTANCE.with_borrow(|i| {
57                    i.deprecated_functions.get(&deprecated).cloned()
58                })
59            },
60            FunctionKind::Closure(_) => None, // 闭包函数不在注册表中,由编译器特殊处理
61            FunctionKind::Mf(mf) => {
62                MfFunctionRegistry::get_definition(&mf.name)
63            },
64        }
65    }
66
67    /// 创建内部注册表实例
68    ///
69    /// 初始化时自动注册所有内置函数和已废弃函数
70    fn new_internal() -> Self {
71        // 遍历所有内置函数并创建映射
72        let internal_functions = InternalFunction::iter()
73            .map(|i| (i.clone(), (&i).into()))
74            .collect();
75
76        // 遍历所有已废弃函数并创建映射
77        let deprecated_functions = DeprecatedFunction::iter()
78            .map(|i| (i.clone(), (&i).into()))
79            .collect();
80
81        Self { internal_functions, deprecated_functions }
82    }
83}