pasta_lua 0.2.0

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
//! 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,
    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)
    }
}

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.変数名 = 値`
    pub fn generate_var_set(&mut self, var_set: &VarSet) -> Result<(), TranspileError> {
        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 => {
                        return self.generate_property_set(name, &var_set.value);
                    }
                    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
                    ))?;
                    return Ok(());
                }

                match &var_set.value {
                    SetValue::Expr(expr) => {
                        self.write_indent()?;
                        self.write_raw(&format!("{} = ", var_path))?;
                        self.generate_expr(expr)?;
                        writeln!(self.writer)?;
                    }
                    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)?;
                        writeln!(self.writer)?;
                    }
                    SetValue::WordRef { name } => {
                        let word_literal = StringLiteralizer::literalize(name)?;
                        self.writeln(&format!("act:word({})", word_literal))?;
                    }
                }
            }
        }

        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.
    pub(super) fn generate_call_scene(
        &mut self,
        call_scene: &CallScene,
        is_tail_call: bool,
    ) -> Result<(), TranspileError> {
        // 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)?;
        }

        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).
    pub fn generate_action(&mut self, action: &Action, actor: &str) -> Result<(), TranspileError> {
        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))?;
                }
            }
        }

        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.
    pub fn generate_code_block(&mut self, block: &CodeBlock) -> Result<(), TranspileError> {
        // Output code content with proper indentation
        for line in block.content.lines() {
            self.writeln(line)?;
        }
        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)
    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 {
            self.writeln(&format!(
                "{}{}create_word({}):entry({})",
                receiver,
                separator,
                StringLiteralizer::literalize(name)?,
                entry
            ))?;
        }

        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", ":")
    }
}