mortar_compiler 0.5.1

Mortar language compiler core library
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
//! # branch_test.rs
//!
//! # branch_test.rs 文件
//!
//! ## Module Overview
//!
//! ## 模块概述
//!
//! Tests for branching and variable interpolation logic.
//!
//! 分支和变量插值逻辑的测试。
//!
//! ## Source File Overview
//!
//! ## 源文件概述
//!
//! Tests parsing of branch definitions, variable declarations, and interpolated strings.
//!
//! 测试分支定义、变量声明和插值字符串的解析。

use crate::ast::{NodeStmt, StringPart, TopLevel, VarValue};
use crate::parser::ParseHandler;

#[test]
fn test_parse_placeholder_in_text() {
    let source = r#"
        node Test {
            text: $"Hello {name}!"
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[0] {
        TopLevel::NodeDef(node) => match &node.body[0] {
            NodeStmt::InterpolatedText(interp) => {
                assert_eq!(interp.parts.len(), 3);
                assert!(matches!(&interp.parts[0], StringPart::Text(_)));
                assert!(matches!(&interp.parts[1], StringPart::Placeholder(_)));
                assert!(matches!(&interp.parts[2], StringPart::Text(_)));

                if let StringPart::Placeholder(name) = &interp.parts[1] {
                    assert_eq!(name, "name");
                }
            }
            _ => panic!("Expected InterpolatedText"),
        },
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_parse_simple_branch() {
    let source = r#"
        let is_forest: Bool
        
        node Test {
            text: $"Location: {place}"
            
            place: branch [
                is_forest, "森林"
                is_city, "城市"
            ]
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[1] {
        TopLevel::NodeDef(node) => {
            // Should have text and branch
            assert_eq!(node.body.len(), 2);

            match &node.body[1] {
                NodeStmt::Branch(branch) => {
                    assert_eq!(branch.name, "place");
                    assert!(branch.enum_type.is_none());
                    assert_eq!(branch.cases.len(), 2);
                    assert_eq!(branch.cases[0].condition, "is_forest");
                    assert_eq!(branch.cases[0].text, "森林");
                    assert_eq!(branch.cases[1].condition, "is_city");
                    assert_eq!(branch.cases[1].text, "城市");
                }
                _ => panic!("Expected Branch"),
            }
        }
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_parse_branch_with_enum() {
    let source = r#"
        enum GameState { active, paused, stopped }
        
        node Test {
            text: $"Status: {status}"
            
            status: branch<GameState> [
                active, "运行中"
                paused, "已暂停"
                stopped, "已停止"
            ]
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[1] {
        TopLevel::NodeDef(node) => match &node.body[1] {
            NodeStmt::Branch(branch) => {
                assert_eq!(branch.name, "status");
                assert_eq!(branch.enum_type.as_ref().unwrap(), "GameState");
                assert_eq!(branch.cases.len(), 3);
            }
            _ => panic!("Expected Branch"),
        },
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_parse_branch_with_events() {
    let source = r#"
        enum Color { red, blue }
        
        node Test {
            text: $"Color: {color}"
            
            color: branch<Color> [
                red, "红色", events: [
                    0, set_color("red")
                ]
                blue, "蓝色", events: [
                    0, set_color("blue")
                ]
            ]
        }
        
        fn set_color(c: String)
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[1] {
        TopLevel::NodeDef(node) => {
            match &node.body[1] {
                NodeStmt::Branch(branch) => {
                    assert_eq!(branch.name, "color");
                    assert_eq!(branch.cases.len(), 2);

                    // Check that events are captured
                    assert!(branch.cases[0].events.is_some());
                    assert!(branch.cases[1].events.is_some());

                    let events = branch.cases[0].events.as_ref().unwrap();
                    assert_eq!(events.len(), 1);
                }
                _ => panic!("Expected Branch"),
            }
        }
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_multiple_placeholders() {
    let source = r#"
        node Test {
            text: $"Hello {name}, you are in {place}."
            
            name: branch [
                is_male, "先生"
                is_female, "女士"
            ]
            
            place: branch [
                is_forest, "森林"
                is_city, "城市"
            ]
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[0] {
        TopLevel::NodeDef(node) => {
            // Should have 1 text and 2 branches
            assert_eq!(node.body.len(), 3);

            match &node.body[0] {
                NodeStmt::InterpolatedText(interp) => {
                    // Count placeholders
                    let placeholder_count = interp
                        .parts
                        .iter()
                        .filter(|p| matches!(p, StringPart::Placeholder(_)))
                        .count();
                    assert_eq!(placeholder_count, 2);
                }
                _ => panic!("Expected InterpolatedText"),
            }
        }
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_serialize_branch() {
    use crate::Serializer;
    use serde_json::Value;

    let source = r#"
        enum Status { online, offline }
        
        node Test {
            text: $"Status: {status}"
            
            status: branch<Status> [
                online, "在线"
                offline, "离线"
            ]
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    let json_str = Serializer::serialize_to_json(&program, false).unwrap();
    let json: Value = serde_json::from_str(&json_str).unwrap();

    // Check branches in JSON
    assert!(json["nodes"][0]["branches"].is_array());

    let branches = json["nodes"][0]["branches"].as_array().unwrap();
    assert_eq!(branches.len(), 1);

    let branch = &branches[0];
    assert_eq!(branch["name"], "status");
    assert_eq!(branch["enum_type"], "Status");

    let cases = branch["cases"].as_array().unwrap();
    assert_eq!(cases.len(), 2);
    assert_eq!(cases[0]["condition"], "online");
    assert_eq!(cases[0]["text"], "在线");
}

#[test]
fn test_branch_without_enum_type() {
    let source = r#"
        let flag: Bool
        
        node Test {
            text: $"Value: {value}"
            
            value: branch [
                flag, "是"
            ]
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    match &program.body[1] {
        TopLevel::NodeDef(node) => match &node.body[1] {
            NodeStmt::Branch(branch) => {
                assert!(branch.enum_type.is_none());
            }
            _ => panic!("Expected Branch"),
        },
        _ => panic!("Expected NodeDef"),
    }
}

#[test]
fn test_parse_branch_variable_with_enum() {
    let source = r#"
        enum GameState {
            start
            playing
            game_over
        }
        
        let current_state: GameState
        
        let status: branch<current_state> [
            start, "游戏开始"
            playing, "游戏进行中"
            game_over, "游戏结束"
        ]
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();

    // Should have: enum, variable, branch variable
    assert_eq!(program.body.len(), 3);

    // Check branch variable
    match &program.body[2] {
        TopLevel::VarDecl(var_decl) => {
            assert_eq!(var_decl.name, "status");
            assert_eq!(var_decl.type_name, "Branch");

            if let Some(VarValue::Branch(branch_value)) = &var_decl.value {
                assert_eq!(branch_value.enum_type.as_ref().unwrap(), "current_state");
                assert_eq!(branch_value.cases.len(), 3);
                assert_eq!(branch_value.cases[0].condition, "start");
                assert_eq!(branch_value.cases[0].text, "游戏开始");
            } else {
                panic!("Expected Branch value");
            }
        }
        _ => panic!("Expected VarDecl"),
    }
}

#[test]
fn test_parse_branch_variable_with_bool() {
    let source = r#"
        let is_forest: Bool
        
        let place: branch [
            is_forest, "森林"
            is_city, "城市"
        ]
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();

    // Check branch variable
    match &program.body[1] {
        TopLevel::VarDecl(var_decl) => {
            assert_eq!(var_decl.name, "place");
            assert_eq!(var_decl.type_name, "Branch");

            if let Some(VarValue::Branch(branch_value)) = &var_decl.value {
                assert!(branch_value.enum_type.is_none());
                assert_eq!(branch_value.cases.len(), 2);
            } else {
                panic!("Expected Branch value");
            }
        }
        _ => panic!("Expected VarDecl"),
    }
}

#[test]
fn test_serialize_branch_variable() {
    use crate::Serializer;
    use serde_json::Value;

    let source = r#"
        enum Status { online, offline }
        let current_status: Status
        
        let status_text: branch<current_status> [
            online, "在线"
            offline, "离线"
        ]
        
        node Test {
            text: $"状态: {status_text}"
        }
    "#;

    let result = ParseHandler::parse_source_code(source, false);
    assert!(result.is_ok());

    let program = result.unwrap();
    let json_str = Serializer::serialize_to_json(&program, false).unwrap();
    let json: Value = serde_json::from_str(&json_str).unwrap();

    // Check that branch variable is in variables array
    let variables = json["variables"].as_array().unwrap();
    let branch_var = variables
        .iter()
        .find(|v| v["name"] == "status_text")
        .unwrap();

    assert_eq!(branch_var["type"], "Branch");
    assert_eq!(branch_var["value"]["enum_type"], "current_status");

    let cases = branch_var["value"]["cases"].as_array().unwrap();
    assert_eq!(cases.len(), 2);
    assert_eq!(cases[0]["condition"], "online");
    assert_eq!(cases[0]["text"], "在线");
}