Skip to main content

mf_macro/
extension.rs

1/// 扩展宏实现,用于更简单的 Extension 创建(旧版)
2#[macro_export]
3macro_rules! impl_extension {
4    () => {
5        {
6            mf_core::extension::Extension::new()
7        }
8    };
9    ($(attr:$attr:expr),*) => {
10        {
11            let mut ext = mf_core::extension::Extension::new();
12            $(
13                ext.add_global_attribute($attr);
14            )*
15            ext
16        }
17    };
18    ($(plugin:$plugin:expr),*) => {
19        {
20            let mut ext = mf_core::extension::Extension::new();
21            $(
22                ext.add_plugin(std::sync::Arc::new($plugin));
23            )*
24            ext
25        }
26    };
27    ($(op:$op:expr),*) => {
28        {
29            let mut ext = mf_core::extension::Extension::new();
30            $(
31                ext.add_op_fn(std::sync::Arc::new($op));
32            )*
33            ext
34        }
35    };
36    ($(attr:$attr:expr),* ; $(plugin:$plugin:expr),*) => {
37        {
38            let mut ext = mf_core::extension::Extension::new();
39            $(
40                ext.add_global_attribute($attr);
41            )*
42            $(
43                ext.add_plugin(std::sync::Arc::new($plugin));
44            )*
45            ext
46        }
47    };
48    ($(attr:$attr:expr),* ; $(plugin:$plugin:expr),* ; $(op:$op:expr),*) => {
49        {
50            let mut ext = mf_core::extension::Extension::new();
51            $(
52                ext.add_global_attribute($attr);
53            )*
54            $(
55                ext.add_plugin(std::sync::Arc::new($plugin));
56            )*
57            $(
58                ext.add_op_fn(std::sync::Arc::new($op));
59            )*
60            ext
61        }
62    };
63}
64
65/// 声明操作函数块。类似于 Deno 的 ops! 宏。
66///
67/// # 示例
68///
69/// ```rust
70/// use std::sync::Arc;
71/// use mf_core::{ForgeResult, extension::OpFn};
72/// use mf_state::ops::GlobalResourceManager;
73/// use mf_macro::mf_ops;
74///
75/// // 简单的操作块
76/// mf_ops!(my_ops, [
77///     op_hello,
78///     op_world
79/// ]);
80///
81/// fn op_hello(_manager: &GlobalResourceManager) -> ForgeResult<()> {
82///     println!("Hello");
83///     Ok(())
84/// }
85///
86/// fn op_world(_manager: &GlobalResourceManager) -> ForgeResult<()> {
87///     println!("World");
88///     Ok(())
89/// }
90/// ```
91#[macro_export]
92macro_rules! mf_ops {
93    ($name:ident, [ $( $op:ident ),+ $(,)? ]) => {
94        pub fn $name() -> mf_core::extension::OpFn {
95            vec![
96                $(
97                    std::sync::Arc::new($op),
98                )+
99            ]
100        }
101    };
102}
103
104/// 定义具有声明式语法的 ModuForge 扩展,类似于 Deno 的 extension! 宏。
105/// 此宏创建结构体和扩展的相关初始化方法。
106///
107/// # 示例
108///
109/// ```rust
110/// use mf_macro::mf_extension;
111/// use mf_core::types::GlobalAttributeItem;
112/// use std::sync::Arc;
113///
114/// // 定义操作函数
115/// fn setup_logging(_manager: &mf_state::ops::GlobalResourceManager) -> mf_core::ForgeResult<()> {
116///     println!("日志系统初始化");
117///     Ok(())
118/// }
119///
120/// fn cleanup_resources(_manager: &mf_state::ops::GlobalResourceManager) -> mf_core::ForgeResult<()> {
121///     println!("资源清理完成");
122///     Ok(())
123/// }
124///
125/// // 定义节点转换函数
126/// fn node_transformer(node: &mf_core::node::Node) -> Option<mf_core::node::Node> {
127///     // 对特定节点类型进行二次修改
128///     if node.name() == "paragraph" {
129///         let mut new_node = node.clone();
130///         // 添加默认样式或属性
131///         new_node.add_attribute("class", "enhanced-paragraph");
132///         Some(new_node)
133///     } else {
134///         Some(node.clone())  // 其他节点保持不变
135///     }
136/// }
137///
138/// // 创建包含操作和节点禁用的扩展
139/// mf_extension!(
140///     logging_extension,
141///     ops = [ setup_logging, cleanup_resources ],
142///     node_transform = node_transformer,
143///     docs = "用于日志记录、资源管理和节点转换的扩展"
144/// );
145///
146/// // 使用方法
147/// let ext = logging_extension::init();
148/// ```
149///
150/// ## 可用选项:
151///
152/// - `ops`: 操作函数列表,函数签名为 `fn(&GlobalResourceManager) -> ForgeResult<()>`
153/// - `plugins`: 要包含的插件实例列表
154/// - `global_attributes`: 全局属性项列表
155/// - `node_transform`: 节点转换函数,签名为 `fn(&Node) -> Option<Node>`
156/// - `docs`: 扩展的文档字符串
157#[macro_export]
158macro_rules! mf_extension {
159    (
160        $name:ident
161        $(, ops = [ $( $op:ident ),+ $(,)? ] )?
162        $(, plugins = [ $( $plugin:expr ),+ $(,)? ] )?
163        $(, global_attributes = [ $( $attr:expr ),+ $(,)? ] )?
164        $(, node_transform = $node_transform_fn:expr )?
165        $(, docs = $docs:expr )?
166        $(,)?
167    ) => {
168        $( #[doc = $docs] )?
169        ///
170        /// 用于框架的 ModuForge 扩展。
171        /// 要使用它,请调用 init() 方法获取 Extension 实例:
172        ///
173        /// ```rust,ignore
174        /// use mf_core::extension::Extension;
175        ///
176        #[doc = concat!("let extension = ", stringify!($name), "::init();")]
177        /// ```
178        #[allow(non_camel_case_types)]
179        pub struct $name;
180
181        impl $name {
182            /// 初始化此扩展以供 ModuForge 运行时使用。
183            ///
184            /// # 返回
185            /// 可在框架初始化期间使用的 Extension 对象
186            pub fn init() -> mf_core::extension::Extension {
187                let mut ext = mf_core::extension::Extension::new();
188
189                // 添加操作函数
190                $(
191                    let ops: mf_core::extension::OpFn = vec![
192                        $(
193                            std::sync::Arc::new($op),
194                        )+
195                    ];
196                    for op in ops {
197                        ext.add_op_fn(op);
198                    }
199                )?
200
201                // 添加插件
202                $(
203                    $(
204                        ext.add_plugin(std::sync::Arc::new($plugin));
205                    )+
206                )?
207
208                // 添加全局属性
209                $(
210                    $(
211                        ext.add_global_attribute($attr);
212                    )+
213                )?
214
215                // 添加节点转换函数
216                $(
217                    ext.add_node_transform(std::sync::Arc::new($node_transform_fn));
218                )?
219
220                ext
221            }
222        }
223    };
224}
225
226/// 带配置支持的简化扩展宏
227#[macro_export]
228macro_rules! mf_extension_with_config {
229    (
230        $name:ident,
231        config = { $( $config_field:ident : $config_type:ty ),+ $(,)? },
232        init_fn = $init_fn:expr
233        $(, docs = $docs:expr )?
234        $(,)?
235    ) => {
236        $( #[doc = $docs] )?
237        ///
238        /// 可配置的 ModuForge 扩展。
239        #[allow(non_camel_case_types)]
240        pub struct $name;
241
242        impl $name {
243            /// 使用配置初始化此扩展。
244            pub fn init( $( $config_field: $config_type ),+ ) -> mf_core::extension::Extension {
245                let mut ext = mf_core::extension::Extension::new();
246                ($init_fn)(&mut ext, $( $config_field ),+ );
247                ext
248            }
249        }
250    };
251}
252
253/// 用于创建全局属性项的辅助宏
254#[macro_export]
255macro_rules! mf_global_attr {
256    ($types:expr, $attributes:expr) => {{
257        use std::collections::HashMap;
258        use mf_model::schema::AttributeSpec;
259
260        let mut attr_map = HashMap::new();
261        let attributes: Vec<(&str, AttributeSpec)> = $attributes;
262        for (key, spec) in attributes {
263            attr_map.insert(key.to_string(), spec);
264        }
265
266        mf_core::types::GlobalAttributeItem {
267            types: $types.iter().map(|s| s.to_string()).collect(),
268            attributes: attr_map,
269        }
270    }};
271
272    // 用于字符串键值对的简化版本(创建基本的 AttributeSpec)
273    ($type_name:expr, $key:expr, $value:expr) => {{
274        use std::collections::HashMap;
275        use mf_model::schema::AttributeSpec;
276        use serde_json::Value;
277
278        let mut attr_map = HashMap::new();
279        attr_map.insert(
280            $key.to_string(),
281            AttributeSpec { default: Some(Value::String($value.to_string())) },
282        );
283
284        mf_core::types::GlobalAttributeItem {
285            types: vec![$type_name.to_string()],
286            attributes: attr_map,
287        }
288    }};
289}
290
291/// 用于创建带错误处理的操作函数的辅助宏
292#[macro_export]
293macro_rules! mf_op {
294    ($name:ident, $body:block) => {
295        fn $name(
296            _manager: &mf_state::ops::GlobalResourceManager
297        ) -> mf_core::ForgeResult<()> {
298            $body
299        }
300    };
301    ($name:ident, |$manager:ident| $body:block) => {
302        fn $name(
303            $manager: &mf_state::ops::GlobalResourceManager
304        ) -> mf_core::ForgeResult<()> {
305            $body
306        }
307    };
308}
309
310/// 用于创建节点转换函数的辅助宏
311#[macro_export]
312macro_rules! mf_node_transform {
313    ($name:ident, $body:block) => {
314        fn $name(_node: &mf_core::node::Node) -> Option<mf_core::node::Node> {
315            $body
316        }
317    };
318    ($name:ident, |$node:ident| $body:block) => {
319        fn $name($node: &mf_core::node::Node) -> Option<mf_core::node::Node> {
320            $body
321        }
322    };
323}