pasta_lua 0.2.2

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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Lua Transpiler for Pasta DSL.
//!
//! This module provides the main transpiler interface for converting
//! Pasta AST to Lua code.

use pasta_dsl::parser::{ActorScope, FileItem, GlobalSceneScope, KeyWords, PastaFile};
use pasta_core::registry::SceneRegistry;

use super::code_gen::LuaCodeGenerator;
use super::code_gen::source_map::SourceMapSink;
use super::config::TranspilerConfig;
use super::context::TranspileContext;
use super::error::TranspileError;
use super::normalize::{LineShift, normalize_output_with_shift};

use std::io::Write;

/// Lua transpiler for Pasta DSL.
///
/// Converts Pasta AST to Lua source code.
pub struct LuaTranspiler {
    /// Transpiler configuration
    config: TranspilerConfig,
}

impl Default for LuaTranspiler {
    fn default() -> Self {
        Self::new(TranspilerConfig::default())
    }
}

impl LuaTranspiler {
    /// Create a new transpiler with the given configuration.
    pub fn new(config: TranspilerConfig) -> Self {
        Self { config }
    }

    /// Create a transpiler with default configuration.
    pub fn with_defaults() -> Self {
        Self::default()
    }

    /// Transpile PastaFile to Lua code (MAJOR-2).
    ///
    /// Processes FileItems in document order, accumulating file attributes
    /// and generating code for actors and scenes.
    ///
    /// # Arguments
    /// * `file` - The parsed PastaFile AST
    /// * `writer` - Output writer
    ///
    /// # Returns
    /// * `Ok(TranspileContext)` - Transpilation successful, context contains registries
    /// * `Err(TranspileError)` - Transpilation failed
    ///
    /// # Post-processing
    /// - Output is normalized: trailing blank lines removed, ends with exactly one newline
    ///
    /// # Source-map seam (Requirements 1.1, 3.1, 7.1)
    ///
    /// This is the thin, sink-less wrapper around [`transpile_with_sink`](Self::transpile_with_sink).
    /// It is the production transpile path: no source-map sink is attached, so the
    /// `code_gen` recording seam is inert and the generated `.lua` bytes are unchanged
    /// (Requirement 7.1, byte-invariant when source-map generation is disabled).
    pub fn transpile<W: Write>(
        &self,
        file: &PastaFile,
        writer: &mut W,
    ) -> Result<TranspileContext, TranspileError> {
        self.transpile_with_sink(file, writer, None)
    }

    /// Transpile PastaFile to Lua code, optionally recording into a source-map sink.
    ///
    /// This is the source-map receiving port (design.md "TranspileSinkPort"): it threads
    /// an optional `&mut dyn SourceMapSink` into the [`LuaCodeGenerator`] so the production
    /// loader can attach a recording sink. When `sink` is `Some`, the generator records
    /// `(generated_lua_line -> .pasta span)` correspondences for span-bearing constructs
    /// (Requirement 1.1) into the caller-owned, in-memory sink (Requirement 3.1, no
    /// mandatory intermediate file). When `sink` is `None` the seam is inert and the
    /// generated bytes are byte-identical to the sink-less path (Requirement 7.1).
    ///
    /// `code_gen` does not depend on `debug`: the sink is the always-compiled
    /// `code_gen::source_map::SourceMapSink` trait, preserving the `debug -> code_gen`
    /// dependency direction.
    ///
    /// # Arguments
    /// * `file` - The parsed PastaFile AST
    /// * `writer` - Output writer
    /// * `sink` - Optional source-map recording sink (production loader attaches one)
    pub fn transpile_with_sink<W: Write>(
        &self,
        file: &PastaFile,
        writer: &mut W,
        sink: Option<&mut dyn SourceMapSink>,
    ) -> Result<TranspileContext, TranspileError> {
        // The `LineShift` is only needed by the source-map build path
        // (`transpile_with_source_map`); the sink-bearing/sink-less callers here
        // discard it. The output bytes are identical either way (see
        // `transpile_with_source_map` for the byte-safety argument).
        let (context, _shift) = self.transpile_with_source_map(file, writer, sink)?;
        Ok(context)
    }

    /// Transpile PastaFile to Lua code, recording into a source-map sink and
    /// returning the normalize [`LineShift`] (source-map build path).
    ///
    /// This is the loader-side integration entry for `pasta-source-map` task 4.3:
    /// it is the SAME code-generation + normalize pipeline as
    /// [`transpile_with_sink`](Self::transpile_with_sink), but it additionally
    /// returns the [`LineShift`] produced by output normalization so the loader can
    /// rebase the sink's pre-normalize records onto the final `.lua` line numbers
    /// (`MapBuilderSink::finish(&shift)` — Requirement 2.1) and complete the
    /// per-chunk [`crate::debug::source_map::ChunkSourceMap`].
    ///
    /// # Byte-invariance (Requirement 7.1)
    ///
    /// The only difference from the legacy path is that normalization goes through
    /// [`normalize_output_with_shift`] instead of `normalize_output`. The two are
    /// byte-identical by contract (`normalize_output(input)` is a thin wrapper over
    /// `normalize_output_with_shift(input).0`), so the bytes written to `writer` are
    /// unchanged whether or not a sink is attached. When `sink` is `None` the
    /// producer seam is inert and the output equals the disabled (debug-off) output
    /// exactly.
    ///
    /// # Arguments
    /// * `file` - The parsed PastaFile AST
    /// * `writer` - Output writer
    /// * `sink` - Optional source-map recording sink (production loader attaches one)
    pub fn transpile_with_source_map<W: Write>(
        &self,
        file: &PastaFile,
        writer: &mut W,
        sink: Option<&mut dyn SourceMapSink>,
    ) -> Result<(TranspileContext, LineShift), TranspileError> {
        let mut context = TranspileContext::new();

        // Use intermediate buffer for code generation
        let mut intermediate_buffer: Vec<u8> = Vec::new();
        let mut codegen =
            LuaCodeGenerator::with_line_ending(&mut intermediate_buffer, self.config.line_ending);

        // Attach the source-map sink (producer side) when provided. When `None`, the
        // generator's seam stays inert and the output bytes are unchanged (7.1).
        if let Some(sink) = sink {
            codegen.set_source_map(sink);
        }

        // Write header
        codegen.write_header()?;

        // Process FileItems in document order (MAJOR-2)
        for item in &file.items {
            match item {
                FileItem::FileAttr(attr) => context.accumulate_file_attr(attr),
                FileItem::GlobalWord(word) => {
                    Self::process_global_word(&mut context, &mut codegen, word)?;
                }
                FileItem::GlobalSceneScope(scene) => {
                    Self::process_global_scene(&mut context, &mut codegen, scene)?;
                }
                FileItem::ActorScope(actor) => {
                    Self::process_actor(&mut context, &mut codegen, actor)?;
                }
            }
        }

        // Convert intermediate buffer to UTF-8 string and normalize. Use the
        // shift-returning normalize so the caller can rebase recorded pre-normalize
        // lines onto final `.lua` lines (2.1). `.0` is byte-identical to the legacy
        // `normalize_output`, so the bytes written below are unchanged (7.1).
        let raw_output = String::from_utf8(intermediate_buffer)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        let (normalized_output, shift) = normalize_output_with_shift(&raw_output);

        // Write normalized output to final writer
        writer.write_all(normalized_output.as_bytes())?;

        Ok((context, shift))
    }

    /// Process GlobalWord: register in WordDefRegistry and generate Lua code.
    fn process_global_word<W: Write>(
        context: &mut TranspileContext,
        codegen: &mut LuaCodeGenerator<W>,
        word: &KeyWords,
    ) -> Result<(), TranspileError> {
        for name in &word.names {
            context.word_registry.register_global(name, word.words.clone());
        }
        codegen.generate_global_word(word)?;
        Ok(())
    }

    /// Process GlobalSceneScope: register scene/words, merge attrs, generate code, register locals.
    fn process_global_scene<W: Write>(
        context: &mut TranspileContext,
        codegen: &mut LuaCodeGenerator<W>,
        scene: &GlobalSceneScope,
    ) -> Result<(), TranspileError> {
        let (_, counter) = context.register_global_scene(scene);

        // Register scene-level word definitions in WordDefRegistry
        let module_name = format!("{}{}", SceneRegistry::sanitize_name(&scene.name), counter);
        for kw in &scene.words {
            for name in &kw.names {
                context
                    .word_registry
                    .register_local(&module_name, name, kw.words.clone());
            }
        }

        // Merge file attrs with scene attrs, generate Lua code
        let merged_attrs = context.merge_attrs(&scene.attrs);
        codegen.generate_global_scene(scene, counter, context, &merged_attrs)?;

        // Register named local scenes (start scene is part of global)
        for (local_idx, local_scene) in scene.local_scenes.iter().enumerate() {
            if local_scene.name.is_some() {
                context.register_local_scene(
                    local_scene,
                    &scene.name,
                    counter,
                    local_idx + 1,
                );
            }
        }

        Ok(())
    }

    /// Process ActorScope: register actor words and generate Lua code.
    fn process_actor<W: Write>(
        context: &mut TranspileContext,
        codegen: &mut LuaCodeGenerator<W>,
        actor: &ActorScope,
    ) -> Result<(), TranspileError> {
        for word_def in &actor.words {
            for name in &word_def.names {
                context
                    .word_registry
                    .register_actor(&actor.name, name, word_def.words.clone());
            }
        }
        codegen.generate_actor(actor)?;
        Ok(())
    }

    /// Get the transpiler configuration.
    pub fn config(&self) -> &TranspilerConfig {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pasta_dsl::parser::{ActorScope, GlobalSceneScope, KeyWords, LocalSceneScope, Span};
    use std::path::PathBuf;

    fn create_simple_actor(name: &str) -> ActorScope {
        ActorScope {
            name: name.to_string(),
            attrs: vec![],
            words: vec![KeyWords {
                names: vec!["通常".to_string()],
                words: vec!["\\s[0]".to_string()],
                span: Span::default(),
            }],
            var_sets: vec![],
            code_blocks: vec![],
            span: Span::default(),
        }
    }

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

    fn create_scene_with_words(
        name: &str,
        word_name: &str,
        word_values: Vec<&str>,
    ) -> GlobalSceneScope {
        GlobalSceneScope {
            name: name.to_string(),
            is_continuation: false,
            attrs: vec![],
            words: vec![KeyWords {
                names: vec![word_name.to_string()],
                words: word_values.iter().map(|s| s.to_string()).collect(),
                span: Span::default(),
            }],
            actors: vec![],
            code_blocks: vec![],
            local_scenes: vec![LocalSceneScope::start()],
            span: Span::default(),
        }
    }

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

    /// Create a PastaFile with actors and scenes
    fn create_pasta_file(actors: Vec<ActorScope>, scenes: Vec<GlobalSceneScope>) -> PastaFile {
        let mut items: Vec<FileItem> = Vec::new();
        for actor in actors {
            items.push(FileItem::ActorScope(actor));
        }
        for scene in scenes {
            items.push(FileItem::GlobalSceneScope(scene));
        }
        PastaFile {
            path: PathBuf::from("test.pasta"),
            items,
            span: Span::default(),
        }
    }

    #[test]
    fn test_transpiler_default() {
        let transpiler = LuaTranspiler::default();
        assert!(transpiler.config().comment_mode);
    }

    #[test]
    fn test_transpile_empty() {
        let transpiler = LuaTranspiler::default();
        let mut output = Vec::new();
        let file = create_pasta_file(vec![], vec![]);

        let result = transpiler.transpile(&file, &mut output);
        assert!(result.is_ok());

        let lua_code = String::from_utf8(output).unwrap();
        assert!(lua_code.contains("local PASTA = require \"pasta\""));
    }

    #[test]
    fn test_transpile_actor() {
        let transpiler = LuaTranspiler::default();
        let actors = vec![create_simple_actor("さくら")];
        let file = create_pasta_file(actors, vec![]);
        let mut output = Vec::new();

        let result = transpiler.transpile(&file, &mut output);
        assert!(result.is_ok());

        let lua_code = String::from_utf8(output).unwrap();
        assert!(lua_code.contains("PASTA.create_actor(\"さくら\")"));
        // Symmetric API: ACTOR:create_word(key):entry(...) (actor-word-dictionary)
        assert!(lua_code.contains("ACTOR:create_word(\"通常\"):entry([=[\\s[0]]=])"));
    }

    #[test]
    fn test_transpile_scene() {
        let transpiler = LuaTranspiler::default();
        let scenes = vec![create_simple_scene("メイン")];
        let file = create_pasta_file(vec![], scenes);
        let mut output = Vec::new();

        let result = transpiler.transpile(&file, &mut output);
        assert!(result.is_ok());

        let lua_code = String::from_utf8(output).unwrap();
        // Counter is now assigned by Lua runtime, not transpiler (Requirement 8.5)
        assert!(lua_code.contains("PASTA.create_scene(\"メイン\")"));
        assert!(lua_code.contains("function SCENE.__start__(act, ...)"));
    }

    #[test]
    fn test_transpile_multiple_scenes() {
        let transpiler = LuaTranspiler::default();
        let scenes = vec![
            create_simple_scene("メイン"),
            create_simple_scene("会話分岐"),
        ];
        let file = create_pasta_file(vec![], scenes);
        let mut output = Vec::new();

        let result = transpiler.transpile(&file, &mut output);
        assert!(result.is_ok());

        let lua_code = String::from_utf8(output).unwrap();
        // Counter is now assigned by Lua runtime, not transpiler (Requirement 8.5)
        // Both scenes use base name only - Lua will add counters at runtime
        assert!(lua_code.contains("PASTA.create_scene(\"メイン\")"));
        assert!(lua_code.contains("PASTA.create_scene(\"会話分岐\")"));
    }

    // Task 3.1: SceneRegistry integration tests
    #[test]
    fn test_transpile_registers_global_scene() {
        let transpiler = LuaTranspiler::default();
        let scenes = vec![create_simple_scene("メイン")];
        let file = create_pasta_file(vec![], scenes);
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

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

    #[test]
    fn test_transpile_registers_local_scene() {
        let transpiler = LuaTranspiler::default();
        let scenes = vec![create_scene_with_local("メイン", "自己紹介")];
        let file = create_pasta_file(vec![], scenes);
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let registered_scenes = context.scene_registry.all_scenes();
        assert_eq!(registered_scenes.len(), 2); // global + local
        assert_eq!(registered_scenes[1].name, "自己紹介");
    }

    // Task 3.2: WordDefRegistry integration tests
    #[test]
    fn test_transpile_registers_local_words() {
        let transpiler = LuaTranspiler::default();
        let scenes = vec![create_scene_with_words(
            "メイン",
            "場所",
            vec!["東京", "大阪"],
        )];
        let file = create_pasta_file(vec![], scenes);
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let entries = context.word_registry.all_entries();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].key.contains("場所"));
    }

    // MAJOR-2.2: GlobalWord processing test
    #[test]
    fn test_transpile_with_global_words() {
        let transpiler = LuaTranspiler::default();
        let global_words = KeyWords {
            names: vec!["挨拶".to_string()],
            words: vec!["こんにちは".to_string(), "やあ".to_string()],
            span: Span::default(),
        };
        let scenes = vec![create_simple_scene("メイン")];

        // Create PastaFile with GlobalWord item
        let file = PastaFile {
            path: PathBuf::from("test.pasta"),
            items: vec![
                FileItem::GlobalWord(global_words),
                FileItem::GlobalSceneScope(scenes.into_iter().next().unwrap()),
            ],
            span: Span::default(),
        };
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let entries = context.word_registry.all_entries();
        // グローバル単語 + シーン内ローカル単語はないので1つ
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].key, "挨拶");
    }

    // Task 2.3: ActorScope word registration test
    #[test]
    fn test_transpile_registers_actor_words() {
        let transpiler = LuaTranspiler::default();
        let actor = ActorScope {
            name: "さくら".to_string(),
            attrs: vec![],
            words: vec![
                KeyWords {
                    names: vec!["通常".to_string()],
                    words: vec!["\\s[0]".to_string(), "\\s[1]".to_string()],
                    span: Span::default(),
                },
                KeyWords {
                    names: vec!["照れ".to_string()],
                    words: vec!["\\s[2]".to_string()],
                    span: Span::default(),
                },
            ],
            var_sets: vec![],
            code_blocks: vec![],
            span: Span::default(),
        };
        let file = create_pasta_file(vec![actor], vec![]);
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let entries = context.word_registry.all_entries();
        assert_eq!(entries.len(), 2, "Expected 2 actor word entries");
        // Check key format: :__actor_{name}__:{word}
        assert_eq!(entries[0].key, ":__actor_さくら__:通常");
        assert_eq!(entries[1].key, ":__actor_さくら__:照れ");
        // Check values
        assert_eq!(entries[0].values, vec!["\\s[0]", "\\s[1]"]);
        assert_eq!(entries[1].values, vec!["\\s[2]"]);
    }

    // word-multi-key: 複数キーの統合テスト
    #[test]
    fn test_transpile_multi_key_global_word_registration() {
        let transpiler = LuaTranspiler::default();
        let global_words = KeyWords {
            names: vec!["女性".to_string(), "水の妖精".to_string()],
            words: vec!["水無灯里".to_string(), "アリス・キャロル".to_string()],
            span: Span::default(),
        };

        let file = PastaFile {
            path: PathBuf::from("test.pasta"),
            items: vec![FileItem::GlobalWord(global_words)],
            span: Span::default(),
        };
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let entries = context.word_registry.all_entries();
        assert_eq!(entries.len(), 2, "複数キーでそれぞれ登録されること");
        assert_eq!(entries[0].key, "女性");
        assert_eq!(entries[1].key, "水の妖精");
        assert_eq!(entries[0].values, vec!["水無灯里", "アリス・キャロル"]);
        assert_eq!(entries[1].values, vec!["水無灯里", "アリス・キャロル"]);
    }

    #[test]
    fn test_transpile_multi_key_actor_word_registration() {
        let transpiler = LuaTranspiler::default();
        let actor = ActorScope {
            name: "さくら".to_string(),
            attrs: vec![],
            words: vec![KeyWords {
                names: vec!["通常".to_string(), "普通".to_string()],
                words: vec!["\\s[0]".to_string()],
                span: Span::default(),
            }],
            var_sets: vec![],
            code_blocks: vec![],
            span: Span::default(),
        };
        let file = create_pasta_file(vec![actor], vec![]);
        let mut output = Vec::new();

        let context = transpiler.transpile(&file, &mut output).unwrap();

        let entries = context.word_registry.all_entries();
        assert_eq!(entries.len(), 2, "複数キーでそれぞれ登録されること");
        assert_eq!(entries[0].key, ":__actor_さくら__:通常");
        assert_eq!(entries[1].key, ":__actor_さくら__:普通");
    }

    #[test]
    fn test_transpile_multi_key_global_word_lua_output() {
        let transpiler = LuaTranspiler::default();
        let global_words = KeyWords {
            names: vec!["女性".to_string(), "水の妖精".to_string()],
            words: vec!["水無灯里".to_string(), "アリス・キャロル".to_string()],
            span: Span::default(),
        };

        let file = PastaFile {
            path: PathBuf::from("test.pasta"),
            items: vec![FileItem::GlobalWord(global_words)],
            span: Span::default(),
        };
        let mut output = Vec::new();

        transpiler.transpile(&file, &mut output).unwrap();
        let lua_code = String::from_utf8(output).unwrap();

        // 各キーに対して create_word が出力されること
        assert!(
            lua_code.contains("PASTA.create_word(\"女性\"):entry(\"水無灯里\", \"アリス・キャロル\")"),
            "女性キーの create_word が出力されること: {lua_code}"
        );
        assert!(
            lua_code.contains("PASTA.create_word(\"水の妖精\"):entry(\"水無灯里\", \"アリス・キャロル\")"),
            "水の妖精キーの create_word が出力されること: {lua_code}"
        );
    }

    #[test]
    fn test_transpile_multi_key_actor_word_lua_output() {
        let transpiler = LuaTranspiler::default();
        let actor = ActorScope {
            name: "さくら".to_string(),
            attrs: vec![],
            words: vec![KeyWords {
                names: vec!["通常".to_string(), "普通".to_string()],
                words: vec!["\\s[0]".to_string()],
                span: Span::default(),
            }],
            var_sets: vec![],
            code_blocks: vec![],
            span: Span::default(),
        };
        let file = create_pasta_file(vec![actor], vec![]);
        let mut output = Vec::new();

        transpiler.transpile(&file, &mut output).unwrap();
        let lua_code = String::from_utf8(output).unwrap();

        assert!(
            lua_code.contains("ACTOR:create_word(\"通常\"):entry([=[\\s[0]]=])"),
            "通常キーの create_word: {lua_code}"
        );
        assert!(
            lua_code.contains("ACTOR:create_word(\"普通\"):entry([=[\\s[0]]=])"),
            "普通キーの create_word: {lua_code}"
        );
    }

    #[test]
    fn test_transpile_single_key_backward_compat_lua_output() {
        let transpiler = LuaTranspiler::default();
        let global_words = KeyWords {
            names: vec!["挨拶".to_string()],
            words: vec!["こんにちは".to_string()],
            span: Span::default(),
        };

        let file = PastaFile {
            path: PathBuf::from("test.pasta"),
            items: vec![FileItem::GlobalWord(global_words)],
            span: Span::default(),
        };
        let mut output = Vec::new();

        transpiler.transpile(&file, &mut output).unwrap();
        let lua_code = String::from_utf8(output).unwrap();

        // 単一キーでも従来と同一の出力
        assert!(
            lua_code.contains("PASTA.create_word(\"挨拶\"):entry(\"こんにちは\")"),
            "単一キーの出力: {lua_code}"
        );
    }
}