s2s2lua 0.1.0

Transpile Stranded II .s2s scripts to Lua for OpenStranded
Documentation
// s2s2lua – transpile Stranded II .s2s scripts to Lua for OpenStranded
// Copyright (C) 2025  s2s2lua contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Lua code generator.
//!
//! Traverses the AST and emits Lua code that uses the `core_api.*` namespace.
//! All s2s commands become `core_api.command_name(args)`.

use crate::ast::*;
use crate::error::S2sResult;

mod cmd;
mod expr;
mod stmt;

/// Lua code generator configuration.
#[derive(Clone)]
pub struct GenOptions {
    /// Prefix for all emitted commands (default: "core_api.")
    pub command_prefix: String,
}

impl Default for GenOptions {
    fn default() -> Self {
        Self {
            command_prefix: "core_api.".to_string(),
        }
    }
}

/// Lua code generator.
pub struct LuaGenerator {
    options: GenOptions,
    indent: usize,
    output: String,
    /// Track if we're inside a loop callback (for exit -> return true)
    inside_loop: bool,
}

impl LuaGenerator {
    /// Generate Lua source from an AST.
    pub fn generate(script: &Script, options: GenOptions) -> S2sResult<String> {
        let mut g = Self {
            options,
            indent: 0,
            output: String::new(),
            inside_loop: false,
        };
        g.emit("-- Generated by s2s2lua (s2s -> lua)\n");
        g.emit("-- https://github.com/AvengerAnubis/openstranded-s2mod-tool\n\n");

        for stmt in &script.statements {
            g.emit_statement(stmt)?;
        }

        Ok(g.output)
    }

    // ── Statement emission ────────────────────────────────

    pub(super) fn emit_statement(&mut self, stmt: &Stmt) -> S2sResult<()> {
        match stmt {
            Stmt::EventHandler { event, body } => self.emit_event_handler(event, body),
            Stmt::If {
                condition,
                then_body,
                else_ifs,
                else_body,
            } => self.emit_if(condition, then_body, else_ifs, else_body),
            Stmt::Loop { mode, arg, body } => self.emit_loop(mode, arg, body),
            Stmt::Command {
                name,
                args,
                suppress,
            } => self.emit_command(name, args, *suppress),
            Stmt::Assign { var, value } => self.emit_assign(var, value),
            Stmt::CompoundAssign { var, op, value } => self.emit_compound_assign(var, op, value),
            Stmt::IncDec { var, inc } => self.emit_inc_dec(var, *inc),
            Stmt::Exit => self.emit_exit(),
            Stmt::Skip => self.emit_skip(),
            Stmt::SkipEvent => self.emit_skipevent(),
            Stmt::Comment(text) => self.emit_comment(text),
        }
    }

    // ── Helpers ───────────────────────────────────────────

    fn emit_indent(&mut self) {
        for _ in 0..self.indent {
            self.output.push_str("    ");
        }
    }

    fn emit(&mut self, s: &str) {
        self.output.push_str(s);
    }

    /// Rename commands that conflict with Lua reserved keywords.
    pub(super) fn escape_command_name<'a>(&self, name: &'a str) -> &'a str {
        match name {
            "type" => "type_of",
            "local" => "local_vars",
            "repeat" => "repeat_combo",
            "end" => "end_lua",
            "function" => "fn_lua",
            "nil" => "nil_lua",
            "until" => "until_lua",
            "while" => "while_lua",
            "for" => "for_lua",
            "in" => "in_lua",
            "goto" => "goto_lua",
            _ => name,
        }
    }
}

#[cfg(test)]
mod tests;