s2s2lua 0.1.1

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/>.

//! Recursive descent parser for .s2s scripts.
//!
//! Grammar (simplified):
//!
//! ```text
//! script = { statement }
//! statement = event_handler | if_stmt | loop_stmt | command_stmt
//!           | assign_stmt | compound_assign | inc_dec | exit | skip
//!           | skipevent
//! event_handler = "on" ":" ident "{" { statement } "}"
//! if_stmt = "if" "(" condition ")" "{" { statement } "}"
//!           { "elseif" "(" condition ")" "{" { statement } "}" }
//!           [ "else" "{" { statement } "}" ]
//! loop_stmt = "loop" ident "," arg "{" { statement } "}"
//! command_stmt = ["@"] ident { "," arg } ";"
//! assign_stmt = variable "=" expr ";"
//! compound_assign = variable ("+=" | "-=") expr ";"
//! inc_dec = variable ("++" | "--") ";"
//! arg = string | number | variable | command_call
//! condition = "(" expr ")" { ("&&" | "||" | "xor") "(" expr ")" }
//! ```

use crate::ast::*;
use crate::error::{S2sError, S2sResult};
use crate::token::{S2sLexer, Token};
use std::ops::Range;

mod block;
mod expr;
mod stmt;

/// The .s2s parser.
pub struct S2sParser;

impl S2sParser {
    /// Parse a complete .s2s source string into an AST.
    pub fn parse(source: &str) -> S2sResult<Script> {
        let mut lexer = S2sLexer::new(source);
        let mut statements = Vec::new();

        while lexer.peek().is_some() {
            statements.push(Self::parse_statement(&mut lexer)?);
        }

        Ok(Script { statements })
    }

    // ── Helper: get line:col for error from peek ──────────

    /// Get (line, col) from the current peek position, or (1, 1) if none.
    fn peek_linecol(lexer: &mut S2sLexer) -> (usize, usize) {
        lexer.peek_offset()
            .map(|off| lexer.offset_to_linecol(off))
            .unwrap_or((1, 1))
    }

    /// Skip any consecutive comment tokens (line or block).
    fn skip_comments(lexer: &mut S2sLexer) {
        while let Some((Token::LineComment, _)) | Some((Token::BlockComment, _)) = lexer.peek() {
            let _ = lexer.next_token();
        }
    }

    fn error(lexer: &S2sLexer, offset: usize, msg: &str) -> S2sError {
        let (line, col) = lexer.offset_to_linecol(offset);
        S2sError::Parse {
            line,
            column: col,
            message: msg.to_string(),
        }
    }

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

    fn expect_token(lexer: &mut S2sLexer, expected: Token) -> S2sResult<(Token, Range<usize>)> {
        match lexer.next_token() {
            Some((tok, span)) if tok == expected => Ok((tok, span)),
            Some((actual, _)) => {
                let (line, col) = Self::peek_linecol(lexer);
                Err(S2sError::Parse {
                    line,
                    column: col,
                    message: format!("expected '{}', got '{}'", expected.name(), actual.name()),
                })
            }
            None => {
                let (line, col) = Self::peek_linecol(lexer);
                Err(S2sError::Parse {
                    line,
                    column: col,
                    message: format!("expected '{}'", expected.name()),
                })
            }
        }
    }

    fn expect_semicolon(lexer: &mut S2sLexer) -> S2sResult<()> {
        let _ = Self::expect_token(lexer, Token::Semicolon)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests;