pasta_lua 0.2.4

Pasta Lua - Lua integration for Pasta DSL
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
//! Transpile context for Lua code generation.
//!
//! This module provides context management for the transpilation process.

use pasta_core::registry::{SceneRegistry, WordDefRegistry};
use pasta_dsl::parser::{Attr, AttrValue, GlobalSceneScope, LocalSceneScope};
use std::collections::HashMap;

/// Transpile context for sharing state during transpilation.
#[derive(Default)]
pub struct TranspileContext {
    /// Scene registry for global/local scene registration
    pub scene_registry: SceneRegistry,
    /// Word definition registry for global/local word registration
    pub word_registry: WordDefRegistry,
    /// Current module name being processed
    pub current_module: Option<String>,
    /// File-level attributes accumulated from FileAttr items (MAJOR-1)
    file_attrs: HashMap<String, AttrValue>,
}

impl TranspileContext {
    /// Create a new transpile context.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the current module name.
    pub fn set_current_module(&mut self, module: String) {
        self.current_module = Some(module);
    }

    /// Get the current module name.
    pub fn get_current_module(&self) -> Option<&str> {
        self.current_module.as_deref()
    }

    /// Register a global scene (Task 3.1).
    ///
    /// Registers the scene in SceneRegistry and returns (id, counter).
    pub fn register_global_scene(&mut self, scene: &GlobalSceneScope) -> (i64, usize) {
        let attrs: HashMap<String, String> = scene
            .attrs
            .iter()
            .map(|a| (a.key.clone(), a.value.to_string()))
            .collect();
        self.scene_registry.register_global(&scene.name, attrs)
    }

    /// Register a local scene (Task 3.1).
    ///
    /// Registers the local scene under the parent global scene.
    /// Returns the assigned scene ID.
    pub fn register_local_scene(
        &mut self,
        local_scene: &LocalSceneScope,
        parent_name: &str,
        parent_counter: usize,
        local_index: usize,
    ) -> i64 {
        let attrs: HashMap<String, String> = local_scene
            .attrs
            .iter()
            .map(|a| (a.key.clone(), a.value.to_string()))
            .collect();

        // Use scene name if present, otherwise use "__start__"
        let name = local_scene.name.as_deref().unwrap_or("__start__");

        self.scene_registry
            .register_local(name, parent_name, parent_counter, local_index, attrs)
    }

    // =========================================================================
    // MAJOR-1: ファイル属性累積・マージ機能
    // =========================================================================

    /// Accumulate file-level attribute (MAJOR-1).
    ///
    /// Multiple FileAttr items are processed in order. If the same key
    /// appears multiple times, the later value overwrites the earlier one
    /// (shadowing semantics).
    pub fn accumulate_file_attr(&mut self, attr: &Attr) {
        self.file_attrs.insert(attr.key.clone(), attr.value.clone());
    }

    /// Get accumulated file-level attributes.
    pub fn file_attrs(&self) -> &HashMap<String, AttrValue> {
        &self.file_attrs
    }

    /// Merge scene attributes with file attributes (MAJOR-1).
    ///
    /// Merge rules:
    /// 1. Start with all keys from file_attrs as the base
    /// 2. Overwrite with each key from scene_attrs (scene takes priority)
    /// 3. Return the merged result as HashMap<String, AttrValue>
    pub fn merge_attrs(&self, scene_attrs: &[Attr]) -> HashMap<String, AttrValue> {
        let mut result = self.file_attrs.clone();

        for attr in scene_attrs {
            result.insert(attr.key.clone(), attr.value.clone());
        }

        result
    }

    /// Merge registries from another TranspileContext.
    ///
    /// Used by PastaLoader to combine contexts from multiple files.
    /// File attributes are not merged (they are file-specific).
    pub fn merge_from(&mut self, other: TranspileContext) {
        // Merge scene registry
        self.scene_registry.merge_from(other.scene_registry);

        // Merge word registry
        self.word_registry.merge_from(other.word_registry);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pasta_dsl::parser::{KeyWords, Span};

    fn create_test_scene(name: &str) -> GlobalSceneScope {
        GlobalSceneScope {
            name: name.to_string(),
            is_continuation: false,
            attrs: vec![],
            words: vec![],
            actors: vec![],
            code_blocks: vec![],
            local_scenes: vec![],
            span: Span::default(),
        }
    }

    fn create_test_local_scene(name: &str) -> LocalSceneScope {
        LocalSceneScope::named(name.to_string())
    }

    #[test]
    fn test_context_new() {
        let ctx = TranspileContext::new();
        assert!(ctx.current_module.is_none());
    }

    #[test]
    fn test_context_set_module() {
        let mut ctx = TranspileContext::new();
        ctx.set_current_module("メイン1".to_string());
        assert_eq!(ctx.get_current_module(), Some("メイン1"));
    }

    #[test]
    fn test_register_global_scene() {
        let mut ctx = TranspileContext::new();
        let scene = create_test_scene("メイン");

        let (id, counter) = ctx.register_global_scene(&scene);
        assert_eq!(id, 1);
        assert_eq!(counter, 1);

        let scenes = ctx.scene_registry.all_scenes();
        assert_eq!(scenes.len(), 1);
        assert_eq!(scenes[0].name, "メイン");
    }

    #[test]
    fn test_register_local_scene() {
        let mut ctx = TranspileContext::new();

        // First register parent
        let parent = create_test_scene("メイン");
        let (_, parent_counter) = ctx.register_global_scene(&parent);

        // Then register local scene
        let local = create_test_local_scene("自己紹介");
        let id = ctx.register_local_scene(&local, "メイン", parent_counter, 1);

        assert_eq!(id, 2);
        let scenes = ctx.scene_registry.all_scenes();
        assert_eq!(scenes.len(), 2);
    }

    #[test]
    fn test_register_global_words() {
        let mut ctx = TranspileContext::new();
        // 単一キー: word_registry 直接呼び出し
        ctx.word_registry
            .register_global("挨拶", vec!["こんにちは".to_string(), "やあ".to_string()]);

        let entries = ctx.word_registry.all_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].key, "挨拶");
    }

    #[test]
    fn test_register_global_words_multi_key() {
        let mut ctx = TranspileContext::new();
        // 複数キー: 各キーに対して登録
        let kw = KeyWords {
            names: vec!["女性".to_string(), "水の妖精".to_string()],
            words: vec!["水無灯里".to_string(), "アリス・キャロル".to_string()],
            span: Span::default(),
        };
        for name in &kw.names {
            ctx.word_registry.register_global(name, kw.words.clone());
        }

        let entries = ctx.word_registry.all_entries();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].key, "女性");
        assert_eq!(entries[1].key, "水の妖精");
    }

    #[test]
    fn test_register_local_words() {
        let mut ctx = TranspileContext::new();
        // 単一キー: word_registry 直接呼び出し
        ctx.word_registry.register_local(
            "メイン_1",
            "場所",
            vec!["東京".to_string(), "大阪".to_string()],
        );

        let entries = ctx.word_registry.all_entries();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].key.contains(":メイン_1:場所"));
    }

    #[test]
    fn test_register_local_words_multi_key() {
        let mut ctx = TranspileContext::new();
        // 複数キー: 各キーに対して登録
        let kw = KeyWords {
            names: vec!["場所".to_string(), "地名".to_string()],
            words: vec!["東京".to_string(), "大阪".to_string()],
            span: Span::default(),
        };
        for name in &kw.names {
            ctx.word_registry
                .register_local("メイン_1", name, kw.words.clone());
        }

        let entries = ctx.word_registry.all_entries();
        assert_eq!(entries.len(), 2);
        assert!(entries[0].key.contains(":メイン_1:場所"));
        assert!(entries[1].key.contains(":メイン_1:地名"));
    }

    // =========================================================================
    // MAJOR-1: ファイル属性累積・マージ機能のテスト
    // =========================================================================

    use pasta_dsl::parser::{Attr, AttrValue};

    fn create_attr(key: &str, value: &str) -> Attr {
        Attr {
            key: key.to_string(),
            value: AttrValue::AttrString(value.to_string()),
            span: Span::default(),
        }
    }

    #[test]
    fn test_accumulate_file_attr_basic() {
        let mut ctx = TranspileContext::new();
        let attr1 = create_attr("author", "Alice");
        let attr2 = create_attr("version", "1.0");

        ctx.accumulate_file_attr(&attr1);
        ctx.accumulate_file_attr(&attr2);

        let attrs = ctx.file_attrs();
        assert_eq!(attrs.len(), 2);
        assert_eq!(
            attrs.get("author"),
            Some(&AttrValue::AttrString("Alice".to_string()))
        );
        assert_eq!(
            attrs.get("version"),
            Some(&AttrValue::AttrString("1.0".to_string()))
        );
    }

    #[test]
    fn test_accumulate_file_attr_shadowing() {
        // シャドーイング: 同じキーの属性が再出現すると上書きされる
        let mut ctx = TranspileContext::new();
        let attr1 = create_attr("author", "Alice");
        let attr2 = create_attr("author", "Bob"); // Alice を上書き

        ctx.accumulate_file_attr(&attr1);
        ctx.accumulate_file_attr(&attr2);

        let attrs = ctx.file_attrs();
        assert_eq!(attrs.len(), 1);
        assert_eq!(
            attrs.get("author"),
            Some(&AttrValue::AttrString("Bob".to_string()))
        );
    }

    #[test]
    fn test_merge_attrs_file_only() {
        let mut ctx = TranspileContext::new();
        ctx.accumulate_file_attr(&create_attr("author", "Alice"));

        let merged = ctx.merge_attrs(&[]);
        assert_eq!(merged.len(), 1);
        assert_eq!(
            merged.get("author"),
            Some(&AttrValue::AttrString("Alice".to_string()))
        );
    }

    #[test]
    fn test_merge_attrs_scene_overrides_file() {
        let mut ctx = TranspileContext::new();
        ctx.accumulate_file_attr(&create_attr("author", "Alice"));
        ctx.accumulate_file_attr(&create_attr("version", "1.0"));

        // シーン属性がファイル属性を上書き
        let scene_attrs = vec![create_attr("author", "Bob")];
        let merged = ctx.merge_attrs(&scene_attrs);

        assert_eq!(merged.len(), 2);
        assert_eq!(
            merged.get("author"),
            Some(&AttrValue::AttrString("Bob".to_string()))
        );
        assert_eq!(
            merged.get("version"),
            Some(&AttrValue::AttrString("1.0".to_string()))
        );
    }

    #[test]
    fn test_get_current_module_none_by_default() {
        let ctx = TranspileContext::new();
        assert_eq!(ctx.get_current_module(), None);
    }

    #[test]
    fn test_merge_from_combines_scene_and_word_registries() {
        let mut ctx1 = TranspileContext::new();
        ctx1.register_global_scene(&create_test_scene("メイン"));
        ctx1.word_registry
            .register_global("挨拶", vec!["こんにちは".to_string()]);

        let mut ctx2 = TranspileContext::new();
        ctx2.register_global_scene(&create_test_scene("サブ"));
        ctx2.word_registry
            .register_global("別れ", vec!["さようなら".to_string()]);

        ctx1.merge_from(ctx2);

        let scenes = ctx1.scene_registry.all_scenes();
        assert_eq!(scenes.len(), 2, "scenes from both contexts must be merged");
        let names: Vec<&str> = scenes.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"メイン"));
        assert!(names.contains(&"サブ"));

        let entries = ctx1.word_registry.all_entries();
        assert_eq!(entries.len(), 2, "words from both contexts must be merged");
        let keys: Vec<&str> = entries.iter().map(|e| e.key.as_str()).collect();
        assert!(keys.contains(&"挨拶"));
        assert!(keys.contains(&"別れ"));
    }

    #[test]
    fn test_merge_from_does_not_merge_file_attrs() {
        // File attributes are file-specific and must NOT leak across contexts.
        let mut ctx1 = TranspileContext::new();
        ctx1.accumulate_file_attr(&create_attr("author", "Alice"));

        let mut ctx2 = TranspileContext::new();
        ctx2.accumulate_file_attr(&create_attr("version", "2.0"));

        ctx1.merge_from(ctx2);

        let attrs = ctx1.file_attrs();
        assert_eq!(attrs.len(), 1, "other context's file attrs must be dropped");
        assert!(attrs.contains_key("author"));
        assert!(!attrs.contains_key("version"));
    }

    #[test]
    fn test_merge_attrs_scene_adds_new_key() {
        let mut ctx = TranspileContext::new();
        ctx.accumulate_file_attr(&create_attr("author", "Alice"));

        let scene_attrs = vec![create_attr("title", "MyScene")];
        let merged = ctx.merge_attrs(&scene_attrs);

        assert_eq!(merged.len(), 2);
        assert_eq!(
            merged.get("author"),
            Some(&AttrValue::AttrString("Alice".to_string()))
        );
        assert_eq!(
            merged.get("title"),
            Some(&AttrValue::AttrString("MyScene".to_string()))
        );
    }
}