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
//! Scope-level code generation: actors, global scenes, local scenes.
use super::LuaCodeGenerator;
use crate::context::TranspileContext;
use crate::error::TranspileError;
use crate::string_literalizer::StringLiteralizer;
use pasta_core::registry::SceneRegistry;
use pasta_dsl::parser::{
ActorScope, AttrValue, GlobalSceneScope, LocalSceneItem, LocalSceneScope, SceneActorItem,
};
use std::collections::HashMap;
use std::io::Write;
impl<'a, W: Write> LuaCodeGenerator<'a, W> {
/// Generate actor definition block (Requirement 3a, actor-word-dictionary).
///
/// Generates:
/// ```lua
/// do
/// local ACTOR = PASTA.create_actor("アクター名")
/// ACTOR.通常 = { [=[\s[0]]=], [=[\s[100]]=] }
///
/// function ACTOR.時刻(act)
/// -- Lua関数定義
/// end
/// end
/// ```
pub fn generate_actor(&mut self, actor: &ActorScope) -> Result<(), TranspileError> {
// do block for scope separation (Requirement 1)
self.writeln("do")?;
self.indent();
// Create actor — this is the scope definition HEADER line.
// Source-map wiring (Requirements 1.1, 1.4, 1.5): record the actor scope's
// `.pasta` span at the header `.lua` line so `span.start_line` (the `.pasta`
// `%アクター` definition header line) becomes a breakpoint target. Follows
// `generate_action`'s `out_line` delta-detection pattern.
let out_line_before = self.out_line();
self.writeln(&format!(
"local ACTOR = PASTA.create_actor(\"{}\")",
actor.name
))?;
if self.out_line() > out_line_before {
self.record_span(actor.span);
}
// Generate word definitions (Requirement 2, actor-word-dictionary Task 3.1)
// ACTOR:create_word() registers both in word.lua (L2 prefix search) and as actor attribute (L1 exact match)
for word_def in &actor.words {
if word_def.words.is_empty() {
continue;
}
// Literalize all words in the array
let literals: Result<Vec<String>, _> = word_def
.words
.iter()
.map(|w| StringLiteralizer::literalize_with_span(w, &word_def.span))
.collect();
let literals = literals?;
// Use symmetric API: ACTOR:create_word(key):entry(...)
// This pattern matches SCENE:create_word(key):entry(...)
let entry_args = literals.join(", ");
for name in &word_def.names {
self.writeln(&format!(
"ACTOR:create_word(\"{}\"):entry({})",
name, entry_args
))?;
}
}
// Generate code blocks (Requirement 4.関数定義)
for code_block in &actor.code_blocks {
// Only expand Lua code blocks
if code_block.language.as_deref() == Some("lua") {
self.write_blank_line()?;
self.generate_code_block(code_block)?;
}
}
self.end_block()?;
Ok(())
}
/// Generate global scene block (Requirement 3b, MAJOR-3).
///
/// Generates:
/// ```lua
/// do
/// local SCENE = PASTA.create_scene("モジュール名_N")
///
/// function SCENE.__start__(ctx, ...)
/// local args = { ... }
/// local act, save, var = PASTA.create_session(SCENE, ctx)
/// -- ...
/// end
///
/// function SCENE.__シーン名_1__(ctx, ...)
/// -- ...
/// end
/// end
/// ```
///
/// # Arguments
/// * `scene` - The global scene scope
/// * `scene_counter` - Scene counter for name uniqueness
/// * `_context` - Transpile context (currently unused)
/// * `_file_attrs` - Merged file+scene attributes (MAJOR-3, currently unused for future extension)
#[allow(unused_variables)]
pub fn generate_global_scene(
&mut self,
scene: &GlobalSceneScope,
_scene_counter: usize,
_context: &TranspileContext,
_file_attrs: &HashMap<String, AttrValue>,
) -> Result<(), TranspileError> {
let sanitized_name = SceneRegistry::sanitize_name(&scene.name);
// Use base name only - counter is assigned by Lua runtime (Requirement 8.5)
let base_name = sanitized_name;
// do block for scope separation (Requirement 1)
self.writeln("do")?;
self.indent();
// Create scene with base name - Lua side assigns counter (Requirement 8.2, 8.5).
// This is the global scene definition HEADER line.
// Source-map wiring (Requirements 1.1, 1.4, 1.5): record the global scene's
// `.pasta` span at the header `.lua` line so `span.start_line` (the `.pasta`
// `*シーン` definition header line) becomes a breakpoint target. Follows
// `generate_action`'s `out_line` delta-detection pattern.
let out_line_before = self.out_line();
self.writeln(&format!(
"local SCENE = PASTA.create_scene(\"{}\")",
base_name
))?;
if self.out_line() > out_line_before {
self.record_span(scene.span);
}
self.write_blank_line()?;
// Generate scene-level word definitions (Requirement 2.2, Task 4.3)
// These are registered under the current global scene name
for word in &scene.words {
self.generate_local_word(word)?;
}
if !scene.words.is_empty() {
self.write_blank_line()?;
}
// Generate local scenes with per-name counters
// Same-name scenes get incrementing numbers (_1, _2, ...)
let mut name_counters: HashMap<String, usize> = HashMap::new();
for local_scene in &scene.local_scenes {
let counter = if let Some(ref name) = local_scene.name {
let count = name_counters.entry(name.clone()).or_insert(0);
*count += 1;
*count
} else {
0 // start scene doesn't use counter
};
self.generate_local_scene(local_scene, counter, &scene.actors)?;
}
// Generate code blocks at module level (after all local scene functions)
// First: global scene level code blocks
for code_block in &scene.code_blocks {
self.generate_code_block(code_block)?;
}
// Second: code blocks from local scenes (these are stored in local scenes but should
// appear at the global scene level, after all function definitions)
for local_scene in &scene.local_scenes {
for code_block in &local_scene.code_blocks {
self.generate_code_block(code_block)?;
}
}
self.end_block()?;
Ok(())
}
/// Generate local scene function (Requirement 3c).
///
/// Generates:
/// ```lua
/// function SCENE.__シーン名_N__(ctx, ...)
/// local args = { ... }
/// local act, save, var = PASTA.create_session(SCENE, ctx)
/// -- items...
/// end
/// ```
///
/// The `counter` parameter is the per-name counter (1, 2, 3... for same-name scenes).
/// For start scenes (name is None), counter is ignored.
///
/// Note: Code blocks associated with local scenes are NOT generated here.
/// They are generated at the global scene level by generate_global_scene.
pub fn generate_local_scene(
&mut self,
scene: &LocalSceneScope,
counter: usize,
actors: &[SceneActorItem],
) -> Result<(), TranspileError> {
let fn_name = if let Some(ref name) = scene.name {
let sanitized = SceneRegistry::sanitize_name(name);
format!("{}_{}", sanitized, counter)
} else {
"__start__".to_string()
};
// This is the local scene definition HEADER line.
// Source-map wiring (Requirements 1.1, 1.4, 1.5): record the local scene's
// `.pasta` span at the function header `.lua` line so `span.start_line` (the
// `.pasta` `・シーン` definition header line, or the enclosing global scene
// header for the anonymous start scene) becomes a breakpoint target. Follows
// `generate_action`'s `out_line` delta-detection pattern.
let out_line_before = self.out_line();
self.writeln(&format!("function SCENE.{}(act, ...)", fn_name))?;
if self.out_line() > out_line_before {
self.record_span(scene.span);
}
self.indent();
// Session initialization: args and init_scene come first
self.writeln("local args = { ... }")?;
self.writeln("local save, var = act:init_scene(SCENE)")?;
// Generate actor initialization block for __start__ only (counter == 0)
// Order: init_scene -> clear_spot -> set_spot(s)
if counter == 0 && !actors.is_empty() {
// clear_spot at the start of actor initialization block (Requirement 2.1)
self.writeln("act:clear_spot()")?;
// set_spot with new format: act:set_spot("name", number) (Requirement 3.1, 3.2)
for actor in actors {
self.writeln(&format!(
r#"act:set_spot("{}", {})"#,
actor.name, actor.number
))?;
}
}
self.write_blank_line()?;
// Generate local scene items
self.generate_local_scene_items(&scene.items)?;
// Code blocks are NOT generated here - they are generated at global scene level
// This ensures code blocks appear after all local scene function definitions
self.end_block()?;
Ok(())
}
/// Check if a LocalSceneItem is a "callable" item (TCO optimization target).
///
/// Currently only `CallScene` is considered callable. When new variants like
/// `FnCall` are added in the future, simply extend the `matches!` condition:
///
/// ```ignore
/// // Future extension example:
/// // matches!(item, LocalSceneItem::CallScene(_) | LocalSceneItem::FnCall(_))
/// ```
fn is_callable_item(item: &LocalSceneItem) -> bool {
matches!(item, LocalSceneItem::CallScene(_))
}
/// Generate local scene items (action lines, var sets, calls).
///
/// Tail call optimization: The last item in the list gets a `return` prefix
/// if it is a CallScene, enabling Lua TCO.
fn generate_local_scene_items(
&mut self,
items: &[LocalSceneItem],
) -> Result<(), TranspileError> {
// Calculate the index of the last callable item for TCO
// TCO only applies if the last item itself is callable
let last_index = items.len().saturating_sub(1);
let last_is_callable = items.last().is_some_and(Self::is_callable_item);
let mut last_actor: Option<String> = None;
for (index, item) in items.iter().enumerate() {
match item {
LocalSceneItem::VarSet(var_set) => {
self.generate_var_set(var_set)?;
}
LocalSceneItem::CallScene(call_scene) => {
let is_tail_call = last_is_callable && index == last_index;
self.generate_call_scene(call_scene, is_tail_call)?;
}
LocalSceneItem::ActionLine(action_line) => {
self.generate_action_line(action_line, &mut last_actor)?;
}
LocalSceneItem::ContinueAction(continue_action) => {
self.generate_continue_action(continue_action, &last_actor)?;
}
LocalSceneItem::CueCommand(cmd) => {
if cmd.command == "select" {
self.generate_choice_timeout(cmd)?;
}
// 他のキューコマンドは Lua コード生成の対象外(dola 側で処理)
}
LocalSceneItem::Choice(choice) => {
self.generate_choice(choice)?;
}
}
}
Ok(())
}
/// Generate `act:choice("target", "display")` Lua call for a choice node.
///
/// Source-map wiring (Requirements 1.1, 1.4): records the choice's `.pasta`
/// [`Span`](pasta_dsl::parser::Span) against the single output line it emits,
/// following `generate_action`'s `out_line` delta-detection pattern. Choice is a
/// branch construct (分岐), one of the major syntax kinds required by 1.4.
fn generate_choice(
&mut self,
choice: &pasta_dsl::parser::ChoiceNode,
) -> Result<(), TranspileError> {
let display = choice.label.as_deref().unwrap_or(&choice.target);
let target_lit = StringLiteralizer::literalize_with_span(&choice.target, &choice.span)?;
let display_lit = StringLiteralizer::literalize_with_span(display, &choice.span)?;
let out_line_before = self.out_line();
self.writeln(&format!("act:choice({}, {})", target_lit, display_lit))?;
if self.out_line() > out_line_before {
self.record_span(choice.span);
}
Ok(())
}
/// Generate `act:choice_timeout(seconds)` or `act:choice_timeout(nil)` for `!select` cue command.
///
/// Source-map wiring (Requirements 1.1, 1.4): records the cue command's `.pasta`
/// [`Span`](pasta_dsl::parser::Span) against the single output line it emits,
/// following `generate_action`'s `out_line` delta-detection pattern. The `!select`
/// cue drives branch (分岐) timeout behavior, part of the major syntax kinds (1.4).
fn generate_choice_timeout(
&mut self,
cmd: &pasta_dsl::parser::CueCommandNode,
) -> Result<(), TranspileError> {
use pasta_dsl::parser::CueArgToken;
let arg = match cmd.args.first() {
Some(CueArgToken::Integer(n)) => n.to_string(),
Some(CueArgToken::Float(f)) => {
// Emit as integer if the value has no fractional part
if f.fract() == 0.0 {
(*f as i64).to_string()
} else {
f.to_string()
}
}
_ => "nil".to_string(),
};
let out_line_before = self.out_line();
self.writeln(&format!("act:choice_timeout({})", arg))?;
if self.out_line() > out_line_before {
self.record_span(cmd.span);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::LineEnding;
use pasta_dsl::parser::{
Action, ActionLine, CallScene, CallTarget, ChoiceNode, CodeBlock, CueArgToken,
CueCommandNode, KeyWords, Span,
};
fn gen_to_string<F>(f: F) -> String
where
F: FnOnce(&mut LuaCodeGenerator<'_, Vec<u8>>) -> Result<(), TranspileError>,
{
let mut output = Vec::new();
{
let mut cg = LuaCodeGenerator::with_line_ending(&mut output, LineEnding::Lf);
f(&mut cg).unwrap();
}
String::from_utf8(output).unwrap()
}
fn talk_line(actor: &str, text: &str) -> LocalSceneItem {
LocalSceneItem::ActionLine(ActionLine {
actor: actor.to_string(),
actions: vec![Action::Talk {
text: text.to_string(),
span: Span::default(),
}],
span: Span::default(),
})
}
fn call_item(target: &str) -> LocalSceneItem {
LocalSceneItem::CallScene(CallScene {
target: CallTarget::Static(target.to_string()),
args: None,
span: Span::default(),
})
}
// ------------------------------------------------------------------
// generate_actor filters
// ------------------------------------------------------------------
/// Actor generation skips empty word definitions and expands ONLY
/// `lua`-language code blocks (other languages are silently dropped).
#[test]
fn actor_skips_empty_words_and_non_lua_code_blocks() {
let actor = ActorScope {
name: "さくら".to_string(),
attrs: vec![],
words: vec![
KeyWords {
names: vec!["空".to_string()],
words: vec![], // empty -> skipped entirely
span: Span::default(),
},
KeyWords {
names: vec!["通常".to_string()],
words: vec!["\\s[0]".to_string()],
span: Span::default(),
},
],
var_sets: vec![],
code_blocks: vec![
CodeBlock {
language: Some("rust".to_string()),
content: "fn ignored() {}".to_string(),
span: Span::default(),
},
CodeBlock {
language: Some("lua".to_string()),
content: "function ACTOR.時刻(act)\nend".to_string(),
span: Span::default(),
},
CodeBlock {
language: None,
content: "also ignored".to_string(),
span: Span::default(),
},
],
span: Span::default(),
};
let text = gen_to_string(|cg| cg.generate_actor(&actor));
assert!(
text.contains("local ACTOR = PASTA.create_actor(\"さくら\")"),
"actor header missing: {}",
text
);
assert!(
!text.contains("ACTOR:create_word(\"空\")"),
"empty word definition must be skipped: {}",
text
);
assert!(
text.contains("ACTOR:create_word(\"通常\")"),
"non-empty word definition must be emitted: {}",
text
);
assert!(
text.contains("function ACTOR.時刻(act)"),
"lua code block must be expanded: {}",
text
);
assert!(
!text.contains("fn ignored") && !text.contains("also ignored"),
"non-lua code blocks must be dropped: {}",
text
);
assert!(text.ends_with("end\n\n"), "block closed via end_block: {}", text);
}
// ------------------------------------------------------------------
// generate_local_scene: naming and spot initialization
// ------------------------------------------------------------------
fn local_scene(name: Option<&str>) -> LocalSceneScope {
LocalSceneScope {
name: name.map(|s| s.to_string()),
attrs: vec![],
items: vec![],
code_blocks: vec![],
span: Span::default(),
}
}
fn scene_actors() -> Vec<SceneActorItem> {
vec![
SceneActorItem {
name: "さくら".to_string(),
number: 0,
span: Span::default(),
},
SceneActorItem {
name: "うにゅう".to_string(),
number: 10,
span: Span::default(),
},
]
}
/// The anonymous start scene (name=None, counter=0) is named `__start__`
/// and emits actor initialization: `clear_spot` THEN each `set_spot` in
/// declaration order with the precomputed numbers.
#[test]
fn start_scene_emits_clear_spot_then_set_spots_in_order() {
let text =
gen_to_string(|cg| cg.generate_local_scene(&local_scene(None), 0, &scene_actors()));
assert!(
text.contains("function SCENE.__start__(act, ...)"),
"start scene fn name: {}",
text
);
let clear = text.find("act:clear_spot()").expect("clear_spot present");
let spot1 = text
.find("act:set_spot(\"さくら\", 0)")
.expect("first set_spot present");
let spot2 = text
.find("act:set_spot(\"うにゅう\", 10)")
.expect("second set_spot present");
assert!(
clear < spot1 && spot1 < spot2,
"order must be clear_spot -> set_spot(さくら) -> set_spot(うにゅう): {}",
text
);
}
/// A named local scene uses `{sanitized}_{counter}` and does NOT emit the
/// spot-initialization block even when actors exist (counter != 0).
#[test]
fn named_scene_uses_counter_suffix_and_skips_spot_init() {
let text = gen_to_string(|cg| {
cg.generate_local_scene(&local_scene(Some("会話")), 2, &scene_actors())
});
assert!(
text.contains("function SCENE.会話_2(act, ...)"),
"per-name counter suffix: {}",
text
);
assert!(
!text.contains("clear_spot") && !text.contains("set_spot"),
"spot init is __start__-only: {}",
text
);
// Session initialization is always present.
assert!(text.contains("local args = { ... }"), "{}", text);
assert!(text.contains("local save, var = act:init_scene(SCENE)"), "{}", text);
}
/// A start scene with NO actors emits no spot block at all.
#[test]
fn start_scene_without_actors_emits_no_spot_block() {
let text = gen_to_string(|cg| cg.generate_local_scene(&local_scene(None), 0, &[]));
assert!(
!text.contains("clear_spot") && !text.contains("set_spot"),
"no actors -> no spot init: {}",
text
);
}
// ------------------------------------------------------------------
// Tail call optimization in generate_local_scene_items
// ------------------------------------------------------------------
/// When the LAST item is a scene call, it gets the `return ` TCO prefix;
/// a scene call in non-tail position does not.
#[test]
fn tco_return_only_for_trailing_call_scene() {
let tail = gen_to_string(|cg| {
cg.generate_local_scene_items(&[talk_line("さくら", "やあ"), call_item("次")])
});
assert!(
tail.contains("return act:call(SCENE.__global_name__, \"次\""),
"trailing call must be a tail call: {}",
tail
);
let non_tail = gen_to_string(|cg| {
cg.generate_local_scene_items(&[call_item("次"), talk_line("さくら", "やあ")])
});
assert!(
non_tail.contains("act:call(SCENE.__global_name__, \"次\"")
&& !non_tail.contains("return act:call"),
"non-trailing call must NOT get return prefix: {}",
non_tail
);
}
// ------------------------------------------------------------------
// Choice and !select cue command
// ------------------------------------------------------------------
fn choice_item(target: &str, label: Option<&str>) -> LocalSceneItem {
LocalSceneItem::Choice(ChoiceNode {
target: target.to_string(),
label: label.map(|s| s.to_string()),
span: Span::new(1, 1, 1, 5, 0, 9),
})
}
/// Choice display text: explicit label wins; otherwise the target id is
/// reused as the display string.
#[test]
fn choice_uses_label_or_falls_back_to_target() {
let labeled =
gen_to_string(|cg| cg.generate_local_scene_items(&[choice_item("はい", Some("Yes"))]));
assert_eq!(labeled, "act:choice(\"はい\", \"Yes\")\n");
let fallback =
gen_to_string(|cg| cg.generate_local_scene_items(&[choice_item("はい", None)]));
assert_eq!(fallback, "act:choice(\"はい\", \"はい\")\n");
}
fn select_cmd(command: &str, args: Vec<CueArgToken>) -> LocalSceneItem {
LocalSceneItem::CueCommand(CueCommandNode {
command: command.to_string(),
scope: None,
args,
span: Span::new(1, 1, 1, 8, 0, 12),
})
}
/// `!select` argument rendering: a float WITH a fractional part is kept
/// as-is (`2.5`), while a non-numeric first arg renders as `nil`.
/// (Integer and fract==0 float cases are covered by the transpile
/// integration tests.)
#[test]
fn choice_timeout_keeps_fractional_float_and_defaults_to_nil() {
let fractional = gen_to_string(|cg| {
cg.generate_local_scene_items(&[select_cmd("select", vec![CueArgToken::Float(2.5)])])
});
assert_eq!(fractional, "act:choice_timeout(2.5)\n");
let ident_arg = gen_to_string(|cg| {
cg.generate_local_scene_items(&[select_cmd(
"select",
vec![CueArgToken::Ident("fast".to_string())],
)])
});
assert_eq!(ident_arg, "act:choice_timeout(nil)\n");
}
/// Non-`select` cue commands generate NO Lua output (handled elsewhere).
#[test]
fn non_select_cue_command_emits_nothing() {
let text = gen_to_string(|cg| {
cg.generate_local_scene_items(&[select_cmd(
"emote",
vec![CueArgToken::Ident("smile".to_string())],
)])
});
assert!(text.is_empty(), "non-select cue must emit nothing: {:?}", text);
}
}