moduforge-macros-derive 0.7.0

ModuForge-RS 宏扩展模块,提供 Node 和 Mark 的派生宏
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# ModuForge-RS 派生宏使用指南


本文档详细说明了 ModuForge-RS 框架中 `#[derive(Node)]` 和 `#[derive(Mark)]` 派生宏的使用方法。

## 目录


- [概述]#概述
- [Node 派生宏]#node-派生宏
- [Mark 派生宏]#mark-派生宏
- [属性说明]#属性说明
- [字段类型支持]#字段类型支持
- [完整示例]#完整示例
- [常见错误]#常见错误
- [最佳实践]#最佳实践

## 概述


ModuForge-RS 提供了两个主要的派生宏:

- `#[derive(Node)]` - 用于定义节点类型
- `#[derive(Mark)]` - 用于定义标记类型

这些宏自动生成必要的转换方法,简化了节点和标记的定义过程。

## Node 派生宏


### 基本用法


```rust
use mf_derive::Node;

#[derive(Node)]

#[node_type = "paragraph"]

#[desc = "段落节点"]

pub struct ParagraphNode {
    #[attr]
    content: String,
}
```

### 生成的方法


`#[derive(Node)]` 会为结构体生成以下方法:

1. **`node_definition() -> mf_core::node::Node`** - 静态方法,返回节点定义
2. **`to_node(&self) -> mf_model::node::Node`** - 实例方法,将结构体转换为节点实例
3. **`from(node: &mf_model::node::Node) -> Result<Self, String>`** - 静态方法,从节点创建结构体
4. **`default_instance() -> Self`** - 私有方法,创建默认实例(错误恢复用)

### 使用示例


```rust
// 创建节点定义(用于 lazy_static)
lazy_static! {
    pub static ref PARAGRAPH: mf_core::node::Node = ParagraphNode::node_definition();
}

// 从结构体创建节点实例
let paragraph = ParagraphNode {
    content: "Hello World".to_string(),
};
let node_instance = paragraph.to_node();

// 从节点实例创建结构体
let paragraph_back = ParagraphNode::from(&node_instance)?;
```

## Mark 派生宏


### 基本用法


```rust
use mf_derive::Mark;

#[derive(Mark)]

#[mark_type = "bold"]

pub struct BoldMark {
    #[attr]
    weight: String,
}
```

### 生成的方法


`#[derive(Mark)]` 会为结构体生成以下方法:

1. **`mark_definition() -> mf_core::mark::Mark`** - 静态方法,返回标记定义
2. **`to_mark(&self) -> mf_model::mark::Mark`** - 实例方法,将结构体转换为标记实例
3. **`from(mark: &mf_model::mark::Mark) -> Result<Self, String>`** - 静态方法,从标记创建结构体

## 属性说明


### 结构体级属性


#### Node 属性


| 属性 | 必需 | 描述 | 示例 |
|------|------|------|------|
| `node_type` || 节点类型标识符 | `#[node_type = "paragraph"]` |
| `desc` || 节点描述 | `#[desc = "段落节点"]` |
| `content` || 内容约束表达式 | `#[content = "text*"]` |
| `marks` || 支持的标记列表 | `#[marks = "bold italic"]` |

#### Mark 属性


| 属性 | 必需 | 描述 | 示例 |
|------|------|------|------|
| `mark_type` || 标记类型标识符 | `#[mark_type = "bold"]` |

### 字段级属性


| 属性 | 描述 | 示例 |
|------|------|------|
| `#[attr]` | 标记字段作为节点/标记属性 | `#[attr] content: String` |
| `#[attr(default="value")]` | 指定默认值 | `#[attr(default="Hello")] text: String` |
| `#[id]` | 标记字段作为节点ID | `#[id] node_id: String` |

## 字段类型支持


### 基本类型


```rust
#[derive(Node)]

#[node_type = "example"]

pub struct ExampleNode {
    #[attr] text: String,           // 字符串
    #[attr] count: i32,             // 整数
    #[attr] price: f64,             // 浮点数
    #[attr] enabled: bool,          // 布尔值
}
```

### 可选类型


```rust
#[derive(Node)]

#[node_type = "example"]

pub struct ExampleNode {
    #[attr] title: Option<String>,   // 可选字符串
    #[attr] size: Option<i32>,       // 可选整数
    #[attr] ratio: Option<f64>,      // 可选浮点数
}
```

### 默认值支持


```rust
#[derive(Node)]

#[node_type = "example"]

pub struct ExampleNode {
    #[attr(default="默认标题")]
    title: String,
    
    #[attr(default=42)]
    count: i32,
    
    #[attr(default=3.14)]
    ratio: f64,
    
    #[attr(default=true)]
    enabled: bool,
}
```

### ID 字段


```rust
#[derive(Node)]

#[node_type = "example"]

pub struct ExampleNode {
    #[id]
    node_id: String,  // 映射到 Node.id
    
    #[attr]
    content: String,  // 映射到 Node.attrs
}
```

## 完整示例


### 复杂节点定义


```rust
use mf_derive::Node;

/// 项目节点 - 支持多种标记和内容约束
#[derive(Node)]

#[node_type = "project"]

#[desc = "项目管理节点"]

#[content = "(task|milestone)*"]
#[marks = "priority status"]
pub struct ProjectNode {
    /// 项目ID - 映射到节点ID
    #[id]
    project_id: String,
    
    /// 项目名称
    #[attr]
    name: String,
    
    /// 项目描述(可选)
    #[attr]
    description: Option<String>,
    
    /// 项目状态,默认为"active"
    #[attr(default="active")]
    status: String,
    
    /// 优先级,默认为1
    #[attr(default=1)]
    priority: i32,
    
    /// 完成百分比,默认为0.0
    #[attr(default=0.0)]
    progress: f64,
    
    /// 是否启用,默认为true
    #[attr(default=true)]
    enabled: bool,
    
    // 非属性字段 - 不会映射到节点属性
    created_at: std::time::SystemTime,
    internal_data: Vec<u8>,
}

impl Default for ProjectNode {
    fn default() -> Self {
        Self {
            project_id: "default_project".to_string(),
            name: String::new(),
            description: None,
            status: "active".to_string(),
            priority: 1,
            progress: 0.0,
            enabled: true,
            created_at: std::time::SystemTime::now(),
            internal_data: Vec::new(),
        }
    }
}

// 使用示例
lazy_static! {
    pub static ref PROJECT: mf_core::node::Node = ProjectNode::node_definition();
}

pub fn create_project_nodes() -> Vec<mf_core::node::Node> {
    vec![PROJECT.clone()]
}
```

### 标记定义示例


```rust
use mf_derive::Mark;

/// 优先级标记
#[derive(Mark)]

#[mark_type = "priority"]

pub struct PriorityMark {
    #[attr(default=1)]
    level: i32,
    
    #[attr(default="normal")]
    label: String,
    
    #[attr]
    color: Option<String>,
}

impl Default for PriorityMark {
    fn default() -> Self {
        Self {
            level: 1,
            label: "normal".to_string(),
            color: None,
        }
    }
}
```

## 常见错误


### 1. 缺少必需属性


```rust
// ❌ 错误:缺少 node_type
#[derive(Node)]

pub struct BadNode {
    content: String,
}

// ✅ 正确:包含必需属性
#[derive(Node)]

#[node_type = "good"]

pub struct GoodNode {
    #[attr]
    content: String,
}
```

### 2. 不支持的字段类型


```rust
// ❌ 错误:不支持 Vec<String> 作为属性
#[derive(Node)]

#[node_type = "bad"]

pub struct BadNode {
    #[attr]
    items: Vec<String>,
}

// ✅ 正确:使用支持的类型
#[derive(Node)]

#[node_type = "good"]

pub struct GoodNode {
    #[attr]
    item_count: i32,
    
    // 或者不标记为属性
    items: Vec<String>,
}
```

### 3. 无效的默认值


```rust
// ❌ 错误:类型不匹配
#[derive(Node)]

#[node_type = "bad"]

pub struct BadNode {
    #[attr(default="not_a_number")]
    count: i32,
}

// ✅ 正确:匹配的类型
#[derive(Node)]

#[node_type = "good"]

pub struct GoodNode {
    #[attr(default=42)]
    count: i32,
}
```

## 最佳实践


### 1. 结构体组织


```rust
// 推荐:将相关字段分组
#[derive(Node)]

#[node_type = "document"]

pub struct DocumentNode {
    // ID 字段放在最前面
    #[id]
    doc_id: String,
    
    // 必需的属性
    #[attr]
    title: String,
    
    // 可选的属性
    #[attr]
    author: Option<String>,
    
    #[attr]
    tags: Option<String>,
    
    // 带默认值的属性
    #[attr(default="draft")]
    status: String,
    
    #[attr(default=0)]
    version: i32,
    
    // 非属性字段放在最后
    internal_metadata: serde_json::Value,
}
```

### 2. 文档注释


```rust
/// 文档节点 - 表示一个可编辑的文档
/// 
/// 支持的标记:bold, italic, underline
/// 内容约束:可包含段落和标题
#[derive(Node)]

#[node_type = "document"]

#[desc = "可编辑文档"]

#[content = "(paragraph|heading)*"]
#[marks = "bold italic underline"]
pub struct DocumentNode {
    /// 文档唯一标识符
    #[id]
    doc_id: String,
    
    /// 文档标题
    #[attr]
    title: String,
    
    /// 文档作者(可选)
    #[attr]
    author: Option<String>,
}
```

### 3. 错误处理


```rust
pub fn create_document_from_node(node: &mf_model::node::Node) -> Result<DocumentNode, String> {
    DocumentNode::from(node).map_err(|e| {
        format!("创建文档失败: {}", e)
    })
}
```

### 4. 类型安全


```rust
// 推荐:使用枚举而不是字符串表示状态
#[derive(Debug, Clone)]

pub enum DocumentStatus {
    Draft,
    Review,
    Published,
}

impl Default for DocumentStatus {
    fn default() -> Self {
        DocumentStatus::Draft
    }
}

#[derive(Node)]

#[node_type = "document"]

pub struct DocumentNode {
    #[attr]
    title: String,
    
    // 非属性字段,使用强类型
    status: DocumentStatus,
    
    // 如果需要序列化为属性,使用字符串
    #[attr(default="draft")]
    status_str: String,
}
```

## 总结


ModuForge-RS 的派生宏提供了一种声明式、类型安全的方式来定义节点和标记。通过正确使用这些宏,可以:

1. **简化代码** - 自动生成转换方法
2. **提高类型安全** - 编译时检查类型兼容性
3. **改善可维护性** - 清晰的结构体定义
4. **减少错误** - 自动处理复杂的转换逻辑

遵循本文档中的最佳实践,可以充分发挥派生宏的优势,构建高质量的 ModuForge-RS 应用。