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
//! Element-level code generation: variables, calls, actions, expressions, words.

use super::LuaCodeGenerator;
use crate::error::TranspileError;
use crate::string_literalizer::StringLiteralizer;
use pasta_dsl::parser::{
    Action, ActionLine, Args, CallScene, CodeBlock, ContinueAction, Expr, KeyWords, SetValue,
    Span, VarScope, VarSet,
};
use std::io::Write;

/// Format optional arguments suffix: empty when no args, otherwise ", arg1, arg2, ..."
fn format_args_suffix(args_str: &str) -> String {
    if args_str.is_empty() {
        String::new()
    } else {
        format!(", {}", args_str)
    }
}

/// Extract the `.pasta` [`Span`] carried by every [`Action`] variant.
///
/// Source-map seam helper (R4): used to thread the originating `.pasta` location to
/// the output-line recording point. Defined here (not on the `pasta_dsl` AST) to keep
/// the change within the `code_gen` boundary.
fn action_span(action: &Action) -> Span {
    match action {
        Action::Talk { span, .. }
        | Action::WordRef { span, .. }
        | Action::VarRef { span, .. }
        | Action::FnCall { span, .. }
        | Action::SakuraScript { span, .. }
        | Action::Escape { span, .. } => *span,
    }
}

impl<'a, W: Write> LuaCodeGenerator<'a, W> {
    /// Resolve a VarScope to its Lua variable path (e.g., `var.x`, `save.x`, `args[1]`).
    ///
    /// Returns an error for `VarScope::Property`, which must be handled separately
    /// by callers before reaching this function.
    fn resolve_var_path(name: &str, scope: &VarScope) -> Result<String, TranspileError> {
        match scope {
            VarScope::Local => Ok(format!("var.{}", name)),
            VarScope::Global => Ok(format!("save.{}", name)),
            VarScope::Args(index) => Ok(format!("args[{}]", index + 1)),
            VarScope::Property => Err(TranspileError::property_in_expression()),
        }
    }

    /// Generate variable assignment (Requirement 3d).
    ///
    /// Local: `var.変数名 = 値`
    /// Global: `save.変数名 = 値`
    ///
    /// Source-map wiring (Requirements 1.1, 1.3): records the assignment's `.pasta`
    /// [`Span`] against the output line(s) it emits, following `generate_action`'s
    /// `out_line` delta-detection pattern. Every branch emits exactly one line, but
    /// the delta check makes recording robust to non-emitting paths (e.g. the error
    /// branch). The `Property` branch delegates to `generate_property_set`, which is
    /// covered by the same surrounding delta.
    pub fn generate_var_set(&mut self, var_set: &VarSet) -> Result<(), TranspileError> {
        let out_line_before = self.out_line();
        match &var_set.name {
            Some(name) => {
                let var_path = match var_set.scope {
                    VarScope::Local => format!("var.{}", name),
                    VarScope::Global => format!("save.{}", name),
                    VarScope::Property => {
                        self.generate_property_set(name, &var_set.value)?;
                        if self.out_line() > out_line_before {
                            self.record_span(var_set.span);
                        }
                        return Ok(());
                    }
                    VarScope::Args(_) => {
                        // Cannot assign to scene arguments
                        return Err(TranspileError::invalid_ast(
                            &var_set.span,
                            "Cannot assign to scene argument",
                        ));
                    }
                };

                // GET代入: 右辺が単一Property参照なら直接代入
                if let SetValue::Expr(Expr::VarRef {
                    name: ref prop_name,
                    scope: VarScope::Property,
                }) = var_set.value
                {
                    let prop_literal = StringLiteralizer::literalize(prop_name)?;
                    self.writeln(&format!(
                        "{} = act:get_property({})",
                        var_path, prop_literal
                    ))?;
                    if self.out_line() > out_line_before {
                        self.record_span(var_set.span);
                    }
                    return Ok(());
                }

                match &var_set.value {
                    SetValue::Expr(expr) => {
                        self.write_indent()?;
                        self.write_raw(&format!("{} = ", var_path))?;
                        self.generate_expr(expr)?;
                        self.write_line_terminator()?;
                    }
                    SetValue::WordRef { name } => {
                        // Generate: var.変数名 = act:word("単語名") or save.変数名 = act:word("単語名")
                        let word_literal = StringLiteralizer::literalize(name)?;
                        self.writeln(&format!("{} = act:word({})", var_path, word_literal))?;
                    }
                }
            }
            None => {
                // Expression statement: evaluate expression without assignment
                match &var_set.value {
                    SetValue::Expr(expr) => {
                        self.write_indent()?;
                        self.generate_expr(expr)?;
                        self.write_line_terminator()?;
                    }
                    SetValue::WordRef { name } => {
                        let word_literal = StringLiteralizer::literalize(name)?;
                        self.writeln(&format!("act:word({})", word_literal))?;
                    }
                }
            }
        }

        // Record the (out_line -> span) correspondence for the line just emitted
        // (Requirement 1.1). Skipped when no line was emitted or no sink is attached.
        if self.out_line() > out_line_before {
            self.record_span(var_set.span);
        }

        Ok(())
    }

    /// Generate property SET assignment.
    ///
    /// `SetValue::Expr` → `act:set_property("name", expr)`
    /// `SetValue::WordRef` → `act:set_property("name", act:word("word"))`
    fn generate_property_set(
        &mut self,
        name: &str,
        value: &SetValue,
    ) -> Result<(), TranspileError> {
        let name_literal = StringLiteralizer::literalize(name)?;
        match value {
            SetValue::Expr(expr) => {
                let mut buf = Vec::new();
                self.generate_expr_to_buffer(expr, &mut buf)?;
                let expr_str = String::from_utf8(buf).unwrap_or_default();
                self.writeln(&format!("act:set_property({}, {})", name_literal, expr_str))?;
            }
            SetValue::WordRef { name: word_name } => {
                let word_literal = StringLiteralizer::literalize(word_name)?;
                self.writeln(&format!(
                    "act:set_property({}, act:word({}))",
                    name_literal, word_literal
                ))?;
            }
        }
        Ok(())
    }

    /// Generate scene call (Requirement 3d, 3g).
    ///
    /// Generates: `act:call("モジュール名", "ラベル名", {}, table.unpack(args))`
    ///
    /// When `is_tail_call` is true, prepends `return` to enable Lua TCO.
    ///
    /// Source-map wiring (Requirement 1.1): records the call's `.pasta` [`Span`]
    /// against the single output line it emits, following `generate_action`'s
    /// `out_line` delta-detection pattern.
    pub(super) fn generate_call_scene(
        &mut self,
        call_scene: &CallScene,
        is_tail_call: bool,
    ) -> Result<(), TranspileError> {
        let out_line_before = self.out_line();
        // Generate argument list
        let args_str = if let Some(ref args) = call_scene.args {
            let mut parts = Vec::new();
            for arg in &args.items {
                match arg {
                    pasta_dsl::parser::Arg::Positional(expr) => {
                        let mut buf = Vec::new();
                        self.generate_expr_to_buffer(expr, &mut buf)?;
                        parts.push(String::from_utf8(buf).unwrap_or_default());
                    }
                    pasta_dsl::parser::Arg::Keyword { key: _, value } => {
                        let mut buf = Vec::new();
                        self.generate_expr_to_buffer(value, &mut buf)?;
                        parts.push(String::from_utf8(buf).unwrap_or_default());
                    }
                }
            }
            if parts.is_empty() {
                "table.unpack(args)".to_string()
            } else {
                format!("{}, table.unpack(args)", parts.join(", "))
            }
        } else {
            "table.unpack(args)".to_string()
        };

        // Generate call statement based on target type
        let call_stmt = match &call_scene.target {
            pasta_dsl::parser::CallTarget::Static(name) => {
                format!(
                    "act:call(SCENE.__global_name__, \"{}\", {{}}, {})",
                    name, args_str
                )
            }
            pasta_dsl::parser::CallTarget::Dynamic(expr) => {
                let mut buf = Vec::new();
                self.generate_expr_to_buffer(expr, &mut buf)?;
                let expr_str = String::from_utf8(buf).unwrap_or_default();
                format!(
                    "act:call(SCENE.__global_name__, tostring({}), {{}}, {})",
                    expr_str, args_str
                )
            }
        };

        // Tail call optimization: prepend 'return' for the last callable item
        if is_tail_call {
            self.writeln(&format!("return {}", call_stmt))?;
        } else {
            self.writeln(&call_stmt)?;
        }

        // Record the (out_line -> span) correspondence for the line just emitted
        // (Requirement 1.1).
        if self.out_line() > out_line_before {
            self.record_span(call_scene.span);
        }

        Ok(())
    }

    /// Generate action line (with speaker).
    pub(super) fn generate_action_line(
        &mut self,
        action_line: &ActionLine,
        last_actor: &mut Option<String>,
    ) -> Result<(), TranspileError> {
        let actor = &action_line.actor;
        *last_actor = Some(actor.clone());

        // Generate actions
        for action in &action_line.actions {
            self.generate_action(action, actor)?;
        }

        Ok(())
    }

    /// Generate continue action line (without speaker).
    pub(super) fn generate_continue_action(
        &mut self,
        continue_action: &ContinueAction,
        last_actor: &Option<String>,
    ) -> Result<(), TranspileError> {
        let actor = match last_actor {
            Some(a) => a,
            None => {
                return Err(TranspileError::invalid_continuation(&continue_action.span));
            }
        };

        // Generate actions (speaker is inherited)
        for action in &continue_action.actions {
            self.generate_action(action, actor)?;
        }

        Ok(())
    }

    /// Generate a single action (Requirement 3d, 3e).
    ///
    /// Source-map seam (R4): this is the representative span-bearing path. The
    /// action's `.pasta` [`Span`](pasta_dsl::parser::Span) is recorded against the
    /// generated Lua line via [`record_span`](Self::record_span) when a sink is
    /// attached (otherwise inert / byte-identical). Every variant emits exactly one
    /// line except the rare empty-escape case, so we detect actual emission by the
    /// `out_line` delta before recording, ensuring the span maps to the line that was
    /// actually written.
    pub fn generate_action(&mut self, action: &Action, actor: &str) -> Result<(), TranspileError> {
        let span = action_span(action);
        let out_line_before = self.out_line();
        match action {
            Action::Talk { text, .. } => {
                // act.アクター:talk("文字列")
                let literal = StringLiteralizer::literalize(text)?;
                self.writeln(&format!("act.{}:talk({})", actor, literal))?;
            }
            Action::WordRef {
                name: word_name, ..
            } => {
                // act.アクター:talk(act.アクター:word("単語名"))
                let word_literal = StringLiteralizer::literalize(word_name)?;
                self.writeln(&format!(
                    "act.{}:talk(act.{}:word({}))",
                    actor, actor, word_literal
                ))?;
            }
            Action::VarRef { name, scope, .. } => {
                // Variable interpolation: generate talk with concatenation
                match scope {
                    VarScope::Property => {
                        let prop_literal = StringLiteralizer::literalize(name)?;
                        self.writeln(&format!(
                            "act.{}:talk(tostring(act:get_property({})))",
                            actor, prop_literal
                        ))?;
                    }
                    _ => {
                        // SAFETY: VarScope::Property is handled in the arm above;
                        // resolve_var_path returns Err for Property as a defensive guard.
                        let var_path = Self::resolve_var_path(name, scope)?;
                        self.writeln(&format!("act.{}:talk(tostring({}))", actor, var_path))?;
                    }
                }
            }
            Action::FnCall {
                name, args, scope, ..
            } => {
                let args_str = self.generate_args_string(args)?;
                match scope {
                    pasta_dsl::parser::FnScope::Local => {
                        // act.アクター:expr_fn("関数名", 引数...)
                        let name_literal = StringLiteralizer::literalize(name)?;
                        self.writeln(&format!(
                            "act.{}:talk(tostring(act.{}:expr_fn({}{})))",
                            actor,
                            actor,
                            name_literal,
                            format_args_suffix(&args_str)
                        ))?;
                    }
                    pasta_dsl::parser::FnScope::Global => {
                        // GLOBAL.関数名(act, 引数...)
                        self.writeln(&format!(
                            "act.{}:talk(tostring(GLOBAL.{}(act{})))",
                            actor,
                            name,
                            format_args_suffix(&args_str)
                        ))?;
                    }
                }
            }
            Action::SakuraScript { script, .. } => {
                // SakuraScript is output as act.{actor}:sakura_script()
                let literal = StringLiteralizer::literalize(script)?;
                self.writeln(&format!("act.{}:sakura_script({})", actor, literal))?;
            }
            Action::Escape {
                sequence: escape, ..
            } => {
                // Extract the escaped character (second char) and literalize
                if let Some(c) = escape.chars().nth(1) {
                    let literal = StringLiteralizer::literalize(&c.to_string())?;
                    self.writeln(&format!("act.{}:talk({})", actor, literal))?;
                }
            }
        }

        // Record the (out_line -> span) correspondence for the line(s) just emitted.
        // Skipped automatically when no line was emitted (empty escape) or no sink is
        // attached. `record_span` uses the current `out_line`, which now points at the
        // last line written by this action.
        if self.out_line() > out_line_before {
            self.record_span(span);
        }

        Ok(())
    }

    /// Generate an expression (delegates to `generate_expr_to_buffer`).
    fn generate_expr(&mut self, expr: &Expr) -> Result<(), TranspileError> {
        let mut buf = Vec::new();
        self.generate_expr_to_buffer(expr, &mut buf)?;
        self.writer.write_all(&buf)?;
        Ok(())
    }

    /// Generate expression to a separate buffer.
    fn generate_expr_to_buffer(
        &self,
        expr: &Expr,
        buf: &mut Vec<u8>,
    ) -> Result<(), TranspileError> {
        match expr {
            Expr::Integer(n) => {
                write!(buf, "{}", n)?;
            }
            Expr::Float(f) => {
                write!(buf, "{}", f)?;
            }
            Expr::String(s) => {
                let literal = StringLiteralizer::literalize(s)?;
                write!(buf, "{}", literal)?;
            }
            Expr::BlankString => {
                write!(buf, "\"\"")?;
            }
            Expr::VarRef { name, scope } => {
                write!(buf, "{}", Self::resolve_var_path(name, scope)?)?;
            }
            Expr::FnCall { name, args, scope } => {
                let args_str = self.generate_args_string(args)?;
                match scope {
                    pasta_dsl::parser::FnScope::Local => {
                        // act:expr_fn("関数名", 引数...)
                        let name_literal = StringLiteralizer::literalize(name)?;
                        write!(
                            buf,
                            "act:expr_fn({}{})",
                            name_literal,
                            format_args_suffix(&args_str)
                        )?;
                    }
                    pasta_dsl::parser::FnScope::Global => {
                        // GLOBAL.関数名(act, 引数...)
                        write!(
                            buf,
                            "GLOBAL.{}(act{})",
                            name,
                            format_args_suffix(&args_str)
                        )?;
                    }
                }
            }
            Expr::Paren(inner) => {
                write!(buf, "(")?;
                self.generate_expr_to_buffer(inner, buf)?;
                write!(buf, ")")?;
            }
            Expr::Binary { op, lhs, rhs } => {
                self.generate_expr_to_buffer(lhs, buf)?;
                let op_str = match op {
                    pasta_dsl::parser::BinOp::Add => " + ",
                    pasta_dsl::parser::BinOp::Sub => " - ",
                    pasta_dsl::parser::BinOp::Mul => " * ",
                    pasta_dsl::parser::BinOp::Div => " / ",
                    pasta_dsl::parser::BinOp::Mod => " % ",
                };
                write!(buf, "{}", op_str)?;
                self.generate_expr_to_buffer(rhs, buf)?;
            }
        }

        Ok(())
    }

    /// Generate arguments as a string.
    fn generate_args_string(&self, args: &Args) -> Result<String, TranspileError> {
        let mut parts = Vec::new();
        for arg in &args.items {
            match arg {
                pasta_dsl::parser::Arg::Positional(expr) => {
                    let mut buf = Vec::new();
                    self.generate_expr_to_buffer(expr, &mut buf)?;
                    parts.push(String::from_utf8(buf).unwrap_or_default());
                }
                pasta_dsl::parser::Arg::Keyword { key: _, value } => {
                    let mut buf = Vec::new();
                    self.generate_expr_to_buffer(value, &mut buf)?;
                    parts.push(String::from_utf8(buf).unwrap_or_default());
                }
            }
        }
        Ok(parts.join(", "))
    }

    /// Generate code block (Requirement 3f).
    ///
    /// Outputs the code block content directly without transformation.
    ///
    /// Source-map wiring (Requirements 1.1, 1.3): the block is emitted one `.lua`
    /// line per `.pasta` content line (1:1 line correspondence — `content.lines()`
    /// is each emitted via exactly one `writeln`). Each output line is mapped
    /// INDIVIDUALLY to its originating `.pasta` line so in-block breakpoints resolve
    /// precisely, instead of collapsing the whole block onto a single span line.
    ///
    /// # Line offset
    ///
    /// `block.span.start_line` is the `.pasta` line of the OPENING fence
    /// (` ```lang `, the `code_open` grammar rule). The block `content`
    /// (`code_contents`) begins on the line immediately AFTER the fence. Therefore
    /// content line `offset` (0-based) originates from
    /// `block.span.start_line + 1 + offset` — a constant `+1` correction for the
    /// fence line. The closing fence is not part of `content`, so no trailing
    /// adjustment is needed.
    pub fn generate_code_block(&mut self, block: &CodeBlock) -> Result<(), TranspileError> {
        // The opening fence occupies `span.start_line`; content starts on the next
        // line. `+ 1` skips the fence; `+ offset` walks each content line. Only map
        // when the span is valid, mirroring `record_span`'s guard so default/
        // synthetic spans (start_line == 0) do not pollute the map.
        let content_start_line = if block.span.is_valid() {
            block.span.start_line as u32 + 1
        } else {
            0 // sentinel: record_block_line skips pasta_line == 0 (and subsequent)
        };
        // Output code content with proper indentation
        for (offset, line) in block.content.lines().enumerate() {
            self.writeln(line)?;
            if content_start_line > 0 {
                self.record_block_line(content_start_line + offset as u32);
            }
        }
        Ok(())
    }

    /// Shared word definition generator parameterized by prefix.
    ///
    /// Generates: `{prefix}:entry("value1", "value2", ...)`
    ///
    /// The `prefix` includes the full method call syntax, e.g.:
    /// - `PASTA.create_word("key")` for global words (dot syntax)
    /// - `SCENE:create_word("key")` for scene-local words (colon syntax)
    ///
    /// Source-map wiring (Requirements 1.1, 1.3): one `.pasta` word definition with
    /// multiple key names emits one `.lua` line per name; ALL of those output lines
    /// map to the same definition `.pasta` [`Span`]. Recording happens per emitted
    /// line (following `generate_action`'s per-line delta pattern), so every line is
    /// covered, not just the last.
    fn generate_word_definition(
        &mut self,
        word: &KeyWords,
        receiver: &str,
        separator: &str,
    ) -> Result<(), TranspileError> {
        if word.words.is_empty() {
            return Ok(());
        }

        let values: Vec<String> = word
            .words
            .iter()
            .map(|w| StringLiteralizer::literalize(w))
            .collect::<Result<Vec<_>, _>>()?;
        let entry = values.join(", ");

        for name in &word.names {
            let out_line_before = self.out_line();
            self.writeln(&format!(
                "{}{}create_word({}):entry({})",
                receiver,
                separator,
                StringLiteralizer::literalize(name)?,
                entry
            ))?;
            // Map this output line to the word definition's `.pasta` span. Every name
            // line maps to the same span (Requirement 1.3).
            if self.out_line() > out_line_before {
                self.record_span(word.span);
            }
        }

        Ok(())
    }

    /// Generate global word definition (Requirement 2.1, Task 4.2).
    ///
    /// Generates: `PASTA.create_word("key"):entry("value1", "value2", ...)`
    ///
    /// Called at file level, outside of any do block.
    pub fn generate_global_word(&mut self, word: &KeyWords) -> Result<(), TranspileError> {
        self.generate_word_definition(word, "PASTA", ".")
    }

    /// Generate local word definition for a scene (Requirement 2.2, Task 4.3).
    ///
    /// Generates: `SCENE:create_word("key"):entry("value1", "value2", ...)`
    ///
    /// Called inside a local scene function, after init_scene.
    pub fn generate_local_word(&mut self, word: &KeyWords) -> Result<(), TranspileError> {
        self.generate_word_definition(word, "SCENE", ":")
    }
}