Skip to main content

runec/
parser.rs

1use crate::diagnostic_messages as msg;
2use crate::error::SyntaxError;
3use crate::lexer::Lexer;
4use crate::token::{ESCAPED_LT, Kind, Token};
5use crate::types::Type;
6use std::path::{Path, PathBuf};
7
8// ──────────────────────────── AST ────────────────────────────
9
10#[derive(Debug, Clone)]
11pub struct ScriptFile {
12    pub scripts: Vec<ScriptDeclaration>,
13}
14
15#[derive(Debug, Clone)]
16pub struct ScriptDeclaration {
17    pub annotations: Vec<Annotation>,
18    pub trigger: String,
19    pub name: String,
20    pub params: Vec<ParamDef>,
21    pub return_types: Vec<Type>,
22    pub body: Vec<Statement>,
23    pub line: usize,
24}
25
26#[derive(Debug, Clone)]
27pub struct Annotation {
28    pub name: String,
29    pub value: String,
30    pub line: usize,
31    pub column: usize,
32    pub value_line: usize,
33    pub value_column: usize,
34    pub end_line: usize,
35    pub end_column: usize,
36}
37
38pub const ANNOTATIONS: &[(&str, &[&str])] = &[
39    ("stack", &["component_last"]),
40    (
41        "signature",
42        &[
43            "fixed",
44            "hook",
45            "hook_component",
46            "enum",
47            "enum_output",
48            "param",
49        ],
50    ),
51];
52
53pub fn annotation_values(name: &str) -> Option<&'static [&'static str]> {
54    ANNOTATIONS
55        .iter()
56        .find(|(key, _)| *key == name)
57        .map(|(_, values)| *values)
58}
59
60#[derive(Debug, Clone)]
61pub struct ParamDef {
62    pub param_type: Type,
63    pub name: String,
64    /// What an array parameter holds.
65    pub value_type: Option<Type>,
66}
67
68/// The element type and number in an array's name, like `componentarray3`.
69pub(crate) fn array_name(name: &str) -> Option<(Type, i32)> {
70    let number = name.trim_start_matches(|ch: char| !ch.is_ascii_digit());
71    let element = name
72        .strip_suffix(number)?
73        .strip_suffix("array")
74        .and_then(Type::from_name)?;
75    Some((element, number.parse().ok()?))
76}
77
78#[derive(Debug, Clone)]
79pub enum Statement {
80    VarDeclaration {
81        var_type: Type,
82        name: String,
83        value: Option<Expr>,
84        line: usize,
85    },
86    ArrayDeclaration {
87        element_type: Type,
88        name: String,
89        size: Expr,
90        line: usize,
91    },
92    Assignment {
93        target: Expr,
94        value: Expr,
95        line: usize,
96    },
97    If {
98        condition: Expr,
99        body: Vec<Statement>,
100        else_if: Vec<(Expr, Vec<Statement>, usize)>,
101        else_body: Option<Vec<Statement>>,
102        /// Line of the `else` keyword (0 if no plain else block).
103        else_line: usize,
104        line: usize,
105    },
106    While {
107        condition: Expr,
108        body: Vec<Statement>,
109        line: usize,
110    },
111    Switch {
112        switch_type: String,
113        expr: Expr,
114        cases: Vec<SwitchCase>,
115        default: Option<Vec<Statement>>,
116        /// Index where `case default` appeared among all case entries in source order.
117        /// 0 = default was first, cases.len() = default was last (or absent).
118        /// Used to emit default body at the correct source position.
119        default_index: usize,
120        line: usize,
121    },
122    Return {
123        values: Vec<Expr>,
124        line: usize,
125    },
126    Expression {
127        expr: Expr,
128        line: usize,
129    },
130    /// A `case` that appeared outside of a switch statement.
131    /// Parsed for error recovery; the type checker emits CASE_WITHOUT_SWITCH.
132    OrphanCase {
133        case: SwitchCase,
134        line: usize,
135    },
136    Empty,
137}
138
139#[derive(Debug, Clone)]
140pub struct SwitchCase {
141    pub values: Vec<Expr>,
142    pub body: Vec<Statement>,
143}
144
145#[derive(Debug, Clone)]
146pub enum Expr {
147    IntLiteral(i32),
148    LongLiteral(i64),
149    StringLiteral(String),
150    BoolLiteral(bool),
151    NullLiteral,
152    CharLiteral(char),
153    CoordLiteral(i32),
154    Identifier(String),
155    LocalVar(String, usize),    // (name, source_line)
156    GameVar(String, usize),     // (name, source_line)
157    ConstantVar(String, usize), // (name, source_line)
158    ArrayAccess {
159        name: String,
160        index: Box<Expr>,
161    },
162    BinaryOp {
163        op: BinOp,
164        lhs: Box<Expr>,
165        rhs: Box<Expr>,
166    },
167    LogicalOp {
168        op: LogicOp,
169        lhs: Box<Expr>,
170        rhs: Box<Expr>,
171        /// Source line where the RHS starts (for per-line LineNumber emission).
172        rhs_line: usize,
173    },
174    Calc(Box<Expr>),
175    CommandCall {
176        name: String,
177        args: Vec<Expr>,
178        /// Source line of each argument (for per-line LineNumber emission).
179        arg_lines: Vec<usize>,
180        /// Source line of the call expression itself (for re-emission after multi-line args).
181        call_line: usize,
182    },
183    ProcCall {
184        name: String,
185        args: Vec<Expr>,
186        /// Source line of each argument (for per-line LineNumber emission).
187        arg_lines: Vec<usize>,
188        /// Source line of the call expression itself.
189        call_line: usize,
190    },
191    JumpCall {
192        name: String,
193        args: Vec<Expr>,
194        /// Source line of each argument (for per-line LineNumber emission).
195        arg_lines: Vec<usize>,
196        /// Source line of the call expression itself.
197        call_line: usize,
198    },
199    JoinedString {
200        parts: Vec<StringPart>,
201    },
202    /// Multiple assignment targets: $a, $b = multi_return_call(...)
203    /// Contains (targets, target_lines) for per-expression LineNumber emission.
204    MultiAssign(Vec<Expr>, Vec<usize>),
205    Tuple(Vec<Expr>),
206}
207
208#[derive(Debug, Clone)]
209pub enum StringPart {
210    Literal(String),
211    Expr(Expr),
212}
213
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub enum BinOp {
216    Add,
217    Sub,
218    Mul,
219    Div,
220    Mod,
221    Eq,
222    NotEq,
223    Lt,
224    Gt,
225    LtEq,
226    GtEq,
227    BitAnd,
228    BitOr,
229}
230
231#[derive(Debug, Clone, Copy, PartialEq)]
232pub enum LogicOp {
233    And,
234    Or,
235}
236
237// ──────────────────────────── Parser ────────────────────────────
238
239pub struct Parser {
240    tokens: Vec<Token>,
241    pos: usize,
242    file_path: PathBuf,
243    is_sub_parser: bool,
244    nesting: usize,
245    pub max_nesting: usize,
246    recovering: bool,
247    recovered_errors: Vec<SyntaxError>,
248}
249
250impl Parser {
251    pub fn new(mut tokens: Vec<Token>, file_name: &Path) -> Self {
252        if tokens
253            .last()
254            .is_none_or(|token| token.kind != Kind::EndOfFile)
255        {
256            tokens.push(Token::new(Kind::EndOfFile, String::new(), 1, 1));
257        }
258        Self {
259            tokens,
260            pos: 0,
261            file_path: file_name.to_path_buf(),
262            is_sub_parser: false,
263            nesting: 0,
264            max_nesting: 256,
265            recovering: false,
266            recovered_errors: Vec::new(),
267        }
268    }
269
270    // ── Token navigation ──
271
272    fn at(&self) -> &Token {
273        // Skip comments
274        let mut idx = self.pos;
275        while idx < self.tokens.len() {
276            match self.tokens[idx].kind {
277                Kind::SingleLineComment | Kind::MultiLineComment => idx += 1,
278                _ => return &self.tokens[idx],
279            }
280        }
281        self.tokens.last().unwrap() // EOF
282    }
283
284    fn peek_kind(&self) -> Kind {
285        self.at().kind
286    }
287
288    fn next(&mut self) -> Token {
289        loop {
290            if self.pos >= self.tokens.len() {
291                return self.tokens.last().unwrap().clone();
292            }
293            let token = &mut self.tokens[self.pos];
294            let tok = Token::new(
295                token.kind,
296                std::mem::take(&mut token.value),
297                token.line,
298                token.column,
299            );
300            self.pos += 1;
301            match tok.kind {
302                Kind::SingleLineComment | Kind::MultiLineComment => continue,
303                _ => return tok,
304            }
305        }
306    }
307
308    fn expect(&mut self, kind: Kind) -> Result<Token, SyntaxError> {
309        let tok = self.at();
310        if tok.kind != kind {
311            return Err(SyntaxError::from_token(
312                self.file_path.clone(),
313                tok,
314                format!("Expected {:?}, got {:?} '{}'", kind, tok.kind, tok.value),
315            ));
316        }
317        Ok(self.next())
318    }
319
320    fn is_eof(&self) -> bool {
321        self.at().kind == Kind::EndOfFile
322    }
323
324    /// A vararg command's `*` touches its name (`queue*(`); a spaced one multiplies.
325    fn star_suffix(&self, name: &Token) -> bool {
326        let star = self.at();
327        star.kind == Kind::BinaryOperator
328            && star.value == "*"
329            && star.line == name.line
330            && star.column == name.column + name.value.len()
331    }
332
333    fn line(&self) -> usize {
334        self.at().line
335    }
336
337    /// Peek at the nth non-comment token after the current position (0 = current).
338    fn peek_kind_ahead(&self, n: usize) -> Kind {
339        let mut idx = self.pos;
340        let mut count = 0;
341        loop {
342            if idx >= self.tokens.len() {
343                return Kind::EndOfFile;
344            }
345            match self.tokens[idx].kind {
346                Kind::SingleLineComment | Kind::MultiLineComment => {
347                    idx += 1;
348                    continue;
349                }
350                _ => {
351                    if count == n {
352                        return self.tokens[idx].kind;
353                    }
354                    count += 1;
355                    idx += 1;
356                }
357            }
358        }
359    }
360
361    // ── Top-level parsing ──
362
363    fn annotation_value(name: &str, value: &str) -> bool {
364        annotation_values(name).is_some_and(|values| values.contains(&value))
365    }
366
367    fn annotation_ahead(&self) -> bool {
368        let mut tokens = self.tokens[self.pos..].iter().filter(|token| {
369            !matches!(token.kind, Kind::SingleLineComment | Kind::MultiLineComment)
370        });
371        if tokens
372            .next()
373            .is_none_or(|token| token.kind != Kind::JumpCall)
374        {
375            return false;
376        }
377        let Some(name) = tokens.next() else {
378            return false;
379        };
380        if tokens.next().is_none_or(|token| token.kind != Kind::LParen) {
381            return false;
382        }
383        let Some(value) = tokens.next() else {
384            return false;
385        };
386        if value.kind != Kind::Identifier || !Self::annotation_value(&name.value, &value.value) {
387            return false;
388        }
389        if tokens.next().is_none_or(|token| token.kind != Kind::RParen) {
390            return false;
391        }
392        tokens
393            .next()
394            .is_none_or(|token| token.kind != Kind::Semicolon)
395    }
396
397    fn parse_annotations(&mut self) -> Result<Vec<Annotation>, SyntaxError> {
398        let mut annotations: Vec<Annotation> = Vec::new();
399        while self.peek_kind() == Kind::JumpCall {
400            let start = self.next();
401            let name = self.expect(Kind::Identifier)?;
402            if name.line != start.line || name.column != start.column + 1 {
403                return Err(SyntaxError::from_token(
404                    self.file_path.clone(),
405                    &name,
406                    "Annotation name must immediately follow '@'".into(),
407                ));
408            }
409            if annotation_values(&name.value).is_none() {
410                return Err(SyntaxError::from_token(
411                    self.file_path.clone(),
412                    &name,
413                    format!("Unknown compiler annotation @{}", name.value),
414                ));
415            }
416            if annotations
417                .iter()
418                .any(|annotation| annotation.name == name.value)
419            {
420                return Err(SyntaxError::from_token(
421                    self.file_path.clone(),
422                    &name,
423                    format!("Duplicate compiler annotation @{}", name.value),
424                ));
425            }
426            self.expect(Kind::LParen)?;
427            let value = self.expect(Kind::Identifier)?;
428            if !Self::annotation_value(&name.value, &value.value) {
429                return Err(SyntaxError::from_token(
430                    self.file_path.clone(),
431                    &value,
432                    format!("Unknown @{} value '{}'", name.value, value.value),
433                ));
434            }
435            let end = self.expect(Kind::RParen)?;
436            annotations.push(Annotation {
437                name: name.value,
438                value: value.value,
439                line: start.line,
440                column: start.column,
441                value_line: value.line,
442                value_column: value.column,
443                end_line: end.line,
444                end_column: end.column + 1,
445            });
446        }
447        if !annotations.is_empty() && self.peek_kind() != Kind::LBracket {
448            return Err(SyntaxError::from_token(
449                self.file_path.clone(),
450                self.at(),
451                "Compiler annotations must precede a command declaration".into(),
452            ));
453        }
454        Ok(annotations)
455    }
456
457    pub fn parse(&mut self) -> Result<ScriptFile, SyntaxError> {
458        let mut scripts = Vec::new();
459        while !self.is_eof() {
460            scripts.push(self.parse_script_declaration()?);
461        }
462        Ok(ScriptFile { scripts })
463    }
464
465    /// Keep valid declarations after an error, so one incomplete proc does not
466    /// hide diagnostics and symbols in the rest of an editor document.
467    pub fn parse_recovering(&mut self) -> (ScriptFile, Vec<SyntaxError>) {
468        self.recovering = true;
469        let mut scripts = Vec::new();
470        let mut errors = Vec::new();
471        while !self.is_eof() {
472            let start = self.pos;
473            match self.parse_script_declaration() {
474                Ok(script) => scripts.push(script),
475                Err(error) => {
476                    errors.push(error);
477                    if self.pos == start {
478                        self.next();
479                    }
480                    while !self.is_eof() {
481                        if self.annotation_ahead()
482                            || self.peek_kind() == Kind::LBracket
483                                && self.peek_kind_ahead(2) == Kind::Comma
484                        {
485                            break;
486                        }
487                        self.next();
488                    }
489                }
490            }
491        }
492        errors.append(&mut self.recovered_errors);
493        errors.sort_by_key(|error| (error.line, error.position));
494        self.recovering = false;
495        (ScriptFile { scripts }, errors)
496    }
497
498    fn parse_script_declaration(&mut self) -> Result<ScriptDeclaration, SyntaxError> {
499        let annotations = self.parse_annotations()?;
500        let line = self.line();
501
502        self.expect(Kind::LBracket)?;
503
504        // Parse trigger type
505        let trigger_tok = self.next();
506        if !annotations.is_empty() && trigger_tok.value != "command" {
507            return Err(SyntaxError::from_token(
508                self.file_path.clone(),
509                &trigger_tok,
510                "Compiler annotations are only valid on command declarations".into(),
511            ));
512        }
513        let trigger = trigger_tok.value;
514
515        self.expect(Kind::Comma)?;
516
517        // Parse script name (may contain underscores, identifiers, dots)
518        let name = self.parse_script_name()?;
519
520        self.expect(Kind::RBracket)?;
521
522        // Parse optional parameter list
523        let mut params = if self.peek_kind() == Kind::LParen {
524            self.parse_param_list()?
525        } else {
526            Vec::new()
527        };
528
529        // Parse optional return type list
530        let return_types = if self.peek_kind() == Kind::LParen {
531            self.parse_return_types()?
532        } else {
533            Vec::new()
534        };
535        if let Some(annotation) = annotations
536            .iter()
537            .find(|annotation| annotation.name == "stack")
538            && params.first().map(|param| param.param_type) != Some(Type::Component)
539        {
540            return Err(SyntaxError {
541                path: self.file_path.clone(),
542                message: "@stack(component_last) requires a component as the first parameter"
543                    .into(),
544                line: annotation.line,
545                position: annotation.column,
546            });
547        }
548
549        // Parse body statements until next script declaration or EOF
550        // Some scripts wrap the body in braces: [proc,name] { ... }
551        let has_brace = self.peek_kind() == Kind::LBrace;
552        if has_brace {
553            self.next(); // consume '{'
554        }
555        let mut body = Vec::new();
556        loop {
557            if self.is_eof() {
558                if has_brace {
559                    self.closing_brace()?;
560                }
561                break;
562            }
563            if has_brace && self.peek_kind() == Kind::RBrace {
564                self.next(); // consume '}'
565                break;
566            }
567            if (!has_brace || self.recovering)
568                && (self.peek_kind() == Kind::LBracket || self.annotation_ahead())
569            {
570                if has_brace {
571                    self.closing_brace()?;
572                }
573                break;
574            }
575            body.push(self.parse_statement()?);
576        }
577
578        // An array parameter is an int holding the array's number, and the array.
579        let mut arrays = Vec::new();
580        for param in &mut params {
581            if let Some(element_type) = param.value_type {
582                arrays.push(Statement::ArrayDeclaration {
583                    element_type,
584                    name: param.name.clone(),
585                    size: Expr::NullLiteral,
586                    line,
587                });
588                param.param_type = Type::Int;
589                param.name = format!("_{}", param.name);
590            }
591        }
592        body.splice(0..0, arrays);
593
594        Ok(ScriptDeclaration {
595            annotations,
596            trigger,
597            name,
598            params,
599            return_types,
600            body,
601            line,
602        })
603    }
604
605    fn parse_script_name(&mut self) -> Result<String, SyntaxError> {
606        let mut name = String::new();
607
608        // Allow optional leading dot for dot-prefixed names like .huntnext
609        if self.peek_kind() == Kind::Dot {
610            self.next();
611            name.push('.');
612        }
613
614        // First part can be identifier, number, underscore, or any keyword used as name
615        let tok = self.next();
616        match tok.kind {
617            Kind::Identifier
618            | Kind::Trigger
619            | Kind::Calc
620            | Kind::Command
621            | Kind::BooleanTrue
622            | Kind::BooleanFalse
623            | Kind::Null
624            | Kind::If
625            | Kind::While
626            | Kind::Else
627            | Kind::Switch
628            | Kind::Case
629            | Kind::Default
630            | Kind::Return
631            | Kind::Def
632            | Kind::Number
633            | Kind::CoordLiteral => {
634                name.push_str(&tok.value);
635            }
636            Kind::Underscore => {
637                name.push('_');
638            }
639            _ => {
640                return Err(SyntaxError::from_token(
641                    self.file_path.clone(),
642                    &tok,
643                    format!("Expected script name, got {:?}", tok.kind),
644                ));
645            }
646        }
647
648        // Continue reading name parts (identifiers, underscores, numbers, colons for component refs)
649        loop {
650            match self.peek_kind() {
651                Kind::Underscore => {
652                    self.next();
653                    name.push('_');
654                    // If next is an identifier or number, consume it as part of name
655                    match self.peek_kind() {
656                        Kind::Identifier
657                        | Kind::Trigger
658                        | Kind::Command
659                        | Kind::Calc
660                        | Kind::BooleanTrue
661                        | Kind::BooleanFalse
662                        | Kind::Null
663                        | Kind::If
664                        | Kind::While
665                        | Kind::Else
666                        | Kind::Switch
667                        | Kind::Case
668                        | Kind::Default
669                        | Kind::Return
670                        | Kind::Def
671                        | Kind::Number => {
672                            let tok = self.next();
673                            name.push_str(&tok.value);
674                        }
675                        _ => {}
676                    }
677                }
678                Kind::Identifier => {
679                    // Identifiers can follow numbers in names like: 0 + _45_152_lavafish
680                    // (the lexer splits them into separate tokens)
681                    let tok = self.next();
682                    name.push_str(&tok.value);
683                }
684                Kind::Colon => {
685                    // component:field style names like leather_crafting:com_88
686                    self.next();
687                    name.push(':');
688                    let part = self.next();
689                    name.push_str(&part.value);
690                }
691                Kind::BinaryOperator if self.at().value == "*" => {
692                    self.next();
693                    name.push('*');
694                }
695                Kind::BinaryOperator if self.at().value == "+" => {
696                    self.next();
697                    name.push('+');
698                }
699                _ => break,
700            }
701        }
702
703        Ok(name)
704    }
705
706    fn parse_param_list(&mut self) -> Result<Vec<ParamDef>, SyntaxError> {
707        self.expect(Kind::LParen)?;
708        let mut params = Vec::new();
709
710        while self.peek_kind() != Kind::RParen {
711            if !params.is_empty() {
712                self.expect(Kind::Comma)?;
713            }
714
715            // Parse type
716            let type_tok = self.next();
717            let value_type = type_tok
718                .value
719                .strip_suffix("array")
720                .and_then(Type::from_name);
721            let param_type = value_type
722                .map(|_| Type::IntArray)
723                .or_else(|| Type::from_name(&type_tok.value))
724                .ok_or_else(|| {
725                    SyntaxError::from_token(
726                        self.file_path.clone(),
727                        &type_tok,
728                        format!("Unknown parameter type: {}", type_tok.value),
729                    )
730                })?;
731
732            // Parse $name (optionally prefixed with _ to suppress unused warnings)
733            let underscore_prefix = if self.peek_kind() == Kind::Underscore {
734                self.next();
735                true
736            } else {
737                false
738            };
739            self.expect(Kind::LocalVar)?;
740            let name_tok = self.next();
741            let name = if underscore_prefix {
742                format!("_{}", name_tok.value)
743            } else {
744                name_tok.value.clone()
745            };
746
747            params.push(ParamDef {
748                param_type,
749                name,
750                value_type,
751            });
752        }
753
754        self.expect(Kind::RParen)?;
755        Ok(params)
756    }
757
758    fn parse_return_types(&mut self) -> Result<Vec<Type>, SyntaxError> {
759        self.expect(Kind::LParen)?;
760        let mut types = Vec::new();
761
762        while self.peek_kind() != Kind::RParen {
763            if !types.is_empty() {
764                self.expect(Kind::Comma)?;
765            }
766            let tok = self.next();
767            let ty = Type::from_name(&tok.value).ok_or_else(|| {
768                SyntaxError::from_token(
769                    self.file_path.clone(),
770                    &tok,
771                    format!("Unknown return type: {}", tok.value),
772                )
773            })?;
774            types.push(ty);
775        }
776
777        self.expect(Kind::RParen)?;
778        Ok(types)
779    }
780
781    // ── Statement parsing ──
782
783    fn parse_statement(&mut self) -> Result<Statement, SyntaxError> {
784        let start = self.pos;
785        self.enter_nesting()?;
786        let result = self.parse_statement_inner();
787        self.nesting -= 1;
788        if self.recovering
789            && let Err(error) = result
790        {
791            // A new header belongs to the enclosing declaration parser.
792            if self.pos == start && self.peek_kind() == Kind::LBracket {
793                return Err(error);
794            }
795            let line = error.line;
796            self.recovered_errors.push(error);
797            if self.pos == start && self.peek_kind() == Kind::RBrace {
798                self.next();
799            }
800            while !self.is_eof() {
801                match self.peek_kind() {
802                    Kind::Semicolon => {
803                        self.next();
804                        break;
805                    }
806                    Kind::RBrace | Kind::LBracket => break,
807                    Kind::Def | Kind::If | Kind::While | Kind::Return if self.line() > line => {
808                        break;
809                    }
810                    _ => {
811                        self.next();
812                    }
813                }
814            }
815            return Ok(Statement::Empty);
816        }
817        result
818    }
819
820    fn parse_statement_inner(&mut self) -> Result<Statement, SyntaxError> {
821        if self.annotation_ahead() {
822            return Err(SyntaxError::from_token(
823                self.file_path.clone(),
824                self.at(),
825                "Compiler annotations must precede a command declaration".into(),
826            ));
827        }
828        match self.peek_kind() {
829            // Empty statement (trailing semicolon after switch/if block, etc.)
830            Kind::Semicolon => {
831                self.next(); // consume ';'
832                Ok(Statement::Empty)
833            }
834            Kind::Def => self.parse_var_declaration(),
835            Kind::If => self.parse_if_statement(),
836            Kind::While => self.parse_while_statement(),
837            Kind::Switch => self.parse_switch_statement(),
838            Kind::Return => self.parse_return_statement(),
839            Kind::Case => self.parse_orphan_case(),
840            Kind::LocalVar | Kind::Underscore => self.parse_assignment_or_expression(),
841            Kind::GameVar => self.parse_game_var_assignment(),
842            // Dot-prefixed statements: .%var = value (secondary entity game var assignment)
843            // or .command(args) (secondary entity command call - expression statement).
844            Kind::Dot => self.parse_assignment_or_expression(),
845            _ => self.parse_expression_statement(),
846        }
847    }
848
849    fn parse_var_declaration(&mut self) -> Result<Statement, SyntaxError> {
850        let line = self.line();
851        let def_tok = self.next(); // consume def_xxx
852        let var_type = Type::from_def_str(&def_tok.value).ok_or_else(|| {
853            SyntaxError::from_token(
854                self.file_path.clone(),
855                &def_tok,
856                format!("Unknown type definition: {}", def_tok.value),
857            )
858        })?;
859
860        // Expect $varname (optionally prefixed with _ to suppress unused warnings)
861        let underscore_prefix = if self.peek_kind() == Kind::Underscore {
862            self.next();
863            true
864        } else {
865            false
866        };
867        self.expect(Kind::LocalVar)?;
868        let name_tok = self.next();
869        let name = if underscore_prefix {
870            format!("_{}", name_tok.value)
871        } else {
872            name_tok.value.clone()
873        };
874
875        // Check for array declaration: def_int $arr(size)
876        if self.peek_kind() == Kind::LParen {
877            self.expect(Kind::LParen)?;
878            let size = if self.peek_kind() == Kind::RParen {
879                Expr::NullLiteral
880            } else {
881                self.parse_expression()?
882            };
883            self.expect(Kind::RParen)?;
884            if self.peek_kind() == Kind::Semicolon {
885                self.next();
886            }
887            return Ok(Statement::ArrayDeclaration {
888                element_type: var_type,
889                name,
890                size,
891                line,
892            });
893        }
894
895        // Check for initialization
896        let value = if self.peek_kind() == Kind::Equals {
897            self.next(); // consume =
898            let expr = self.parse_expression()?;
899            Some(expr)
900        } else {
901            None
902        };
903
904        if self.peek_kind() == Kind::Semicolon {
905            self.next();
906        }
907
908        Ok(Statement::VarDeclaration {
909            var_type,
910            name,
911            value,
912            line,
913        })
914    }
915
916    fn parse_if_statement(&mut self) -> Result<Statement, SyntaxError> {
917        let line = self.line();
918        self.expect(Kind::If)?;
919        self.expect(Kind::LParen)?;
920        let condition = self.parse_expression()?;
921        self.expect(Kind::RParen)?;
922
923        let body = self.parse_block_or_stmt()?;
924
925        // Parse else-if and else chains
926        let mut else_if = Vec::new();
927        let mut else_body = None;
928        let mut else_line = 0usize;
929
930        while self.peek_kind() == Kind::Else {
931            let el = self.line();
932            self.next(); // consume 'else'
933            if self.peek_kind() == Kind::If {
934                // else if
935                self.next(); // consume 'if'
936                self.expect(Kind::LParen)?;
937                let cond = self.parse_expression()?;
938                self.expect(Kind::RParen)?;
939                let body = self.parse_block_or_stmt()?;
940                else_if.push((cond, body, el));
941            } else {
942                // else
943                else_line = el;
944                else_body = Some(self.parse_block_or_stmt()?);
945                break;
946            }
947        }
948
949        Ok(Statement::If {
950            condition,
951            body,
952            else_if,
953            else_body,
954            else_line,
955            line,
956        })
957    }
958
959    fn parse_while_statement(&mut self) -> Result<Statement, SyntaxError> {
960        let line = self.line();
961        self.expect(Kind::While)?;
962        self.expect(Kind::LParen)?;
963        let condition = self.parse_expression()?;
964        self.expect(Kind::RParen)?;
965        let body = self.parse_block_or_stmt()?;
966
967        Ok(Statement::While {
968            condition,
969            body,
970            line,
971        })
972    }
973
974    fn parse_switch_statement(&mut self) -> Result<Statement, SyntaxError> {
975        let line = self.line();
976        let switch_tok = self.next(); // consume switch_int/switch_str/etc.
977        let switch_type = switch_tok.value.clone();
978
979        self.expect(Kind::LParen)?;
980        let expr = self.parse_expression()?;
981        self.expect(Kind::RParen)?;
982        self.expect(Kind::LBrace)?;
983
984        let mut cases = Vec::new();
985        let mut default = None;
986        let mut default_index: usize = 0;
987
988        while self.peek_kind() != Kind::RBrace {
989            if self.peek_kind() == Kind::Case {
990                self.next(); // consume 'case'
991
992                // Handle `case default:` as the default case
993                if self.peek_kind() == Kind::Default {
994                    let default_tok = self.next(); // consume 'default'
995                    if default.is_some() {
996                        return Err(SyntaxError::from_token(
997                            self.file_path.clone(),
998                            &default_tok,
999                            msg::SWITCH_DUPLICATE_DEFAULT.to_string(),
1000                        ));
1001                    }
1002                    self.expect(Kind::Colon)?;
1003                    default = Some(self.parse_case_body()?);
1004                    default_index = cases.len();
1005                    continue;
1006                }
1007
1008                let mut values = Vec::new();
1009                loop {
1010                    let mut val = self.parse_expression()?;
1011                    // Handle component:name compound references in case values.
1012                    // Pattern: Identifier ':' Identifier (then ':' or ',' as separator)
1013                    // Only consume if after the second identifier there's ':' or ',' (not expression-start).
1014                    if let Expr::Identifier(ref name) = val
1015                        && self.peek_kind() == Kind::Colon
1016                    {
1017                        let after_colon = self.peek_kind_ahead(1);
1018                        let after_name = self.peek_kind_ahead(2);
1019                        // Form compound if followed by case separator ':' or next case value ','
1020                        if matches!(
1021                            after_colon,
1022                            Kind::Identifier | Kind::Number | Kind::Trigger | Kind::Command
1023                        ) && matches!(after_name, Kind::Colon | Kind::Comma)
1024                        {
1025                            let name = name.clone();
1026                            self.next(); // consume ':'
1027                            let part = self.next();
1028                            val = Expr::Identifier(format!("{}:{}", name, part.value));
1029                        }
1030                    }
1031                    values.push(val);
1032                    if self.peek_kind() == Kind::Comma {
1033                        self.next();
1034                    } else {
1035                        break;
1036                    }
1037                }
1038
1039                self.expect(Kind::Colon)?;
1040                let body = self.parse_case_body()?;
1041                cases.push(SwitchCase { values, body });
1042            } else if self.peek_kind() == Kind::Default {
1043                let default_tok = self.next(); // consume 'default'
1044                if default.is_some() {
1045                    return Err(SyntaxError::from_token(
1046                        self.file_path.clone(),
1047                        &default_tok,
1048                        msg::SWITCH_DUPLICATE_DEFAULT.to_string(),
1049                    ));
1050                }
1051                self.expect(Kind::Colon)?;
1052                default = Some(self.parse_case_body()?);
1053            } else {
1054                let tok = self.at().clone();
1055                return Err(SyntaxError::from_token(
1056                    self.file_path.clone(),
1057                    &tok,
1058                    format!("Expected 'case' or 'default' in switch, got {:?}", tok.kind),
1059                ));
1060            }
1061        }
1062
1063        self.expect(Kind::RBrace)?;
1064
1065        Ok(Statement::Switch {
1066            switch_type,
1067            expr,
1068            cases,
1069            default,
1070            default_index,
1071            line,
1072        })
1073    }
1074
1075    fn parse_case_body(&mut self) -> Result<Vec<Statement>, SyntaxError> {
1076        // Handle braced case bodies: case X : { stmt; stmt; }
1077        if self.peek_kind() == Kind::LBrace {
1078            return self.parse_block();
1079        }
1080        let mut stmts = Vec::new();
1081        while !self.is_eof()
1082            && self.peek_kind() != Kind::Case
1083            && self.peek_kind() != Kind::Default
1084            && self.peek_kind() != Kind::RBrace
1085        {
1086            stmts.push(self.parse_statement()?);
1087        }
1088        Ok(stmts)
1089    }
1090
1091    fn parse_orphan_case(&mut self) -> Result<Statement, SyntaxError> {
1092        let line = self.line();
1093        self.next(); // consume 'case'
1094
1095        let mut values = Vec::new();
1096        if self.peek_kind() == Kind::Default {
1097            self.next(); // consume 'default'
1098        } else {
1099            values.push(self.parse_expression()?);
1100            while self.peek_kind() == Kind::Comma {
1101                self.next();
1102                values.push(self.parse_expression()?);
1103            }
1104        }
1105
1106        if self.peek_kind() == Kind::Colon {
1107            self.next();
1108        }
1109
1110        let body = self.parse_case_body()?;
1111        Ok(Statement::OrphanCase {
1112            case: SwitchCase { values, body },
1113            line,
1114        })
1115    }
1116
1117    fn parse_return_statement(&mut self) -> Result<Statement, SyntaxError> {
1118        let line = self.line();
1119        self.expect(Kind::Return)?;
1120
1121        // return or return(expr, expr, ...)
1122        let mut values = Vec::new();
1123        if self.peek_kind() == Kind::LParen {
1124            self.expect(Kind::LParen)?;
1125            while self.peek_kind() != Kind::RParen {
1126                if !values.is_empty() {
1127                    self.expect(Kind::Comma)?;
1128                }
1129                values.push(self.parse_expression()?);
1130            }
1131            self.expect(Kind::RParen)?;
1132        }
1133
1134        if self.peek_kind() == Kind::Semicolon {
1135            self.next();
1136        }
1137
1138        Ok(Statement::Return { values, line })
1139    }
1140
1141    fn parse_assignment_value(&mut self) -> Result<Expr, SyntaxError> {
1142        let mut values = vec![self.parse_expression()?];
1143        while self.peek_kind() == Kind::Comma {
1144            self.next();
1145            values.push(self.parse_expression()?);
1146        }
1147        Ok(if values.len() == 1 {
1148            values.pop().unwrap()
1149        } else {
1150            Expr::Tuple(values)
1151        })
1152    }
1153
1154    fn parse_assignment_or_expression(&mut self) -> Result<Statement, SyntaxError> {
1155        let line = self.line();
1156        let expr = self.parse_primary()?;
1157
1158        // Multi-return assignment: $a, $b = expr
1159        if self.peek_kind() == Kind::Comma {
1160            let mut targets = vec![expr];
1161            let mut target_lines = vec![line];
1162            while self.peek_kind() == Kind::Comma {
1163                self.next(); // consume ','
1164                let tgt_line = self.line();
1165                let target = self.parse_primary()?;
1166                targets.push(target);
1167                target_lines.push(tgt_line);
1168            }
1169            if self.peek_kind() == Kind::Equals {
1170                self.next(); // consume '='
1171                let value = self.parse_assignment_value()?;
1172                if self.peek_kind() == Kind::Semicolon {
1173                    self.next();
1174                }
1175                return Ok(Statement::Assignment {
1176                    target: Expr::MultiAssign(targets, target_lines),
1177                    value,
1178                    line,
1179                });
1180            }
1181            // Not an assignment; this is unusual but handle gracefully
1182            if self.peek_kind() == Kind::Semicolon {
1183                self.next();
1184            }
1185            return Ok(Statement::Expression {
1186                expr: targets.remove(0),
1187                line,
1188            });
1189        }
1190
1191        if self.peek_kind() == Kind::Equals {
1192            self.next(); // consume =
1193            let value = self.parse_assignment_value()?;
1194            if self.peek_kind() == Kind::Semicolon {
1195                self.next();
1196            }
1197            return Ok(Statement::Assignment {
1198                target: expr,
1199                value,
1200                line,
1201            });
1202        }
1203
1204        if self.peek_kind() == Kind::Semicolon {
1205            self.next();
1206        }
1207
1208        Ok(Statement::Expression { expr, line })
1209    }
1210
1211    fn parse_game_var_assignment(&mut self) -> Result<Statement, SyntaxError> {
1212        let line = self.line();
1213        let expr = self.parse_primary()?;
1214
1215        // Multi-return assignment: %a, %b = expr  or  %a, $b = expr
1216        if self.peek_kind() == Kind::Comma {
1217            let mut targets = vec![expr];
1218            let mut target_lines = vec![line];
1219            while self.peek_kind() == Kind::Comma {
1220                self.next(); // consume ','
1221                let tgt_line = self.line();
1222                let target = self.parse_primary()?;
1223                targets.push(target);
1224                target_lines.push(tgt_line);
1225            }
1226            if self.peek_kind() == Kind::Equals {
1227                self.next();
1228                let value = self.parse_assignment_value()?;
1229                if self.peek_kind() == Kind::Semicolon {
1230                    self.next();
1231                }
1232                return Ok(Statement::Assignment {
1233                    target: Expr::MultiAssign(targets, target_lines),
1234                    value,
1235                    line,
1236                });
1237            }
1238            // Not an assignment — treat as expression statement with first target
1239            let first = targets.remove(0);
1240            if self.peek_kind() == Kind::Semicolon {
1241                self.next();
1242            }
1243            return Ok(Statement::Expression { expr: first, line });
1244        }
1245
1246        if self.peek_kind() == Kind::Equals {
1247            self.next(); // consume =
1248            let value = self.parse_assignment_value()?;
1249            if self.peek_kind() == Kind::Semicolon {
1250                self.next();
1251            }
1252            return Ok(Statement::Assignment {
1253                target: expr,
1254                value,
1255                line,
1256            });
1257        }
1258
1259        if self.peek_kind() == Kind::Semicolon {
1260            self.next();
1261        }
1262
1263        Ok(Statement::Expression { expr, line })
1264    }
1265
1266    fn parse_expression_statement(&mut self) -> Result<Statement, SyntaxError> {
1267        let line = self.line();
1268        let expr = self.parse_expression()?;
1269
1270        // Handle multi-return assignment: .%var1, .%var2 = expr, etc.
1271        if self.peek_kind() == Kind::Comma {
1272            let mut targets = vec![expr];
1273            let mut target_lines = vec![line];
1274            while self.peek_kind() == Kind::Comma {
1275                self.next(); // consume ','
1276                let tgt_line = self.line();
1277                targets.push(self.parse_primary()?);
1278                target_lines.push(tgt_line);
1279            }
1280            if self.peek_kind() == Kind::Equals {
1281                self.next();
1282                let value = self.parse_assignment_value()?;
1283                if self.peek_kind() == Kind::Semicolon {
1284                    self.next();
1285                }
1286                return Ok(Statement::Assignment {
1287                    target: Expr::MultiAssign(targets, target_lines),
1288                    value,
1289                    line,
1290                });
1291            }
1292            // Not an assignment; consume semicolon if present
1293            if self.peek_kind() == Kind::Semicolon {
1294                self.next();
1295            }
1296            return Ok(Statement::Expression {
1297                expr: targets.remove(0),
1298                line,
1299            });
1300        }
1301
1302        if self.peek_kind() == Kind::Semicolon {
1303            self.next();
1304        }
1305        Ok(Statement::Expression { expr, line })
1306    }
1307
1308    fn parse_block(&mut self) -> Result<Vec<Statement>, SyntaxError> {
1309        self.expect(Kind::LBrace)?;
1310        let mut stmts = Vec::new();
1311        while self.peek_kind() != Kind::RBrace
1312            && !self.is_eof()
1313            && !(self.recovering && self.peek_kind() == Kind::LBracket)
1314        {
1315            stmts.push(self.parse_statement()?);
1316        }
1317        self.closing_brace()?;
1318        Ok(stmts)
1319    }
1320
1321    fn closing_brace(&mut self) -> Result<(), SyntaxError> {
1322        match self.expect(Kind::RBrace) {
1323            Ok(_) => Ok(()),
1324            Err(error) if self.recovering => {
1325                self.recovered_errors.push(error);
1326                Ok(())
1327            }
1328            Err(error) => Err(error),
1329        }
1330    }
1331
1332    /// Parse either a braced block `{ ... }` or a single statement (braceless body).
1333    fn parse_block_or_stmt(&mut self) -> Result<Vec<Statement>, SyntaxError> {
1334        if self.peek_kind() == Kind::LBrace {
1335            self.parse_block()
1336        } else {
1337            let stmt = self.parse_statement()?;
1338            Ok(vec![stmt])
1339        }
1340    }
1341
1342    // ── Expression parsing (precedence climbing) ──
1343
1344    pub(crate) fn parse_hook(&mut self) -> Result<Vec<Expr>, SyntaxError> {
1345        let target = self.next();
1346        let name = match target.kind {
1347            Kind::Identifier | Kind::Command | Kind::Trigger => Expr::Identifier(target.value),
1348            Kind::Number => Expr::IntLiteral(target.value.parse().map_err(|_| {
1349                SyntaxError::from_token(self.file_path.clone(), &target, "Invalid hook ID".into())
1350            })?),
1351            _ => {
1352                return Err(SyntaxError::from_token(
1353                    self.file_path.clone(),
1354                    &target,
1355                    "Expected hook script name".into(),
1356                ));
1357            }
1358        };
1359        let args = if self.peek_kind() == Kind::LParen {
1360            self.parse_call_args()?.0
1361        } else {
1362            Vec::new()
1363        };
1364        let mut values = vec![name, Expr::Tuple(args)];
1365        if self.peek_kind() == Kind::LBrace {
1366            self.next();
1367            let mut transmits = Vec::new();
1368            while self.peek_kind() != Kind::RBrace {
1369                transmits.push(self.parse_expression()?);
1370                if self.peek_kind() != Kind::Comma {
1371                    break;
1372                }
1373                self.next();
1374            }
1375            self.expect(Kind::RBrace)?;
1376            values.push(Expr::Tuple(transmits));
1377        }
1378        self.expect(Kind::EndOfFile)?;
1379        Ok(values)
1380    }
1381
1382    fn parse_expression(&mut self) -> Result<Expr, SyntaxError> {
1383        self.enter_nesting()?;
1384        let result = self.parse_logical_or();
1385        self.nesting -= 1;
1386        result
1387    }
1388
1389    fn enter_nesting(&mut self) -> Result<(), SyntaxError> {
1390        if self.nesting >= self.max_nesting {
1391            return Err(SyntaxError::from_token(
1392                self.file_path.clone(),
1393                self.at(),
1394                format!(
1395                    "Source nesting exceeds the configured limit of {}",
1396                    self.max_nesting
1397                ),
1398            ));
1399        }
1400        self.nesting += 1;
1401        Ok(())
1402    }
1403
1404    fn parse_logical_or(&mut self) -> Result<Expr, SyntaxError> {
1405        let mut left = self.parse_logical_and()?;
1406        while self.peek_kind() == Kind::LogicalOr {
1407            self.next();
1408            let rhs_line = self.line();
1409            let right = self.parse_logical_and()?;
1410            left = Expr::LogicalOp {
1411                op: LogicOp::Or,
1412                lhs: Box::new(left),
1413                rhs: Box::new(right),
1414                rhs_line,
1415            };
1416        }
1417        Ok(left)
1418    }
1419
1420    fn parse_logical_and(&mut self) -> Result<Expr, SyntaxError> {
1421        let mut left = self.parse_comparison()?;
1422        while self.peek_kind() == Kind::LogicalAnd {
1423            self.next();
1424            let rhs_line = self.line();
1425            let right = self.parse_comparison()?;
1426            left = Expr::LogicalOp {
1427                op: LogicOp::And,
1428                lhs: Box::new(left),
1429                rhs: Box::new(right),
1430                rhs_line,
1431            };
1432        }
1433        Ok(left)
1434    }
1435
1436    fn parse_comparison(&mut self) -> Result<Expr, SyntaxError> {
1437        let mut left = self.parse_additive()?;
1438
1439        match self.peek_kind() {
1440            Kind::ComparisonOperator => {
1441                let tok = self.next();
1442                let op = match tok.value.as_str() {
1443                    "<" => BinOp::Lt,
1444                    ">" => BinOp::Gt,
1445                    "<=" => BinOp::LtEq,
1446                    ">=" => BinOp::GtEq,
1447                    _ => unreachable!(),
1448                };
1449                let right = self.parse_additive()?;
1450                left = Expr::BinaryOp {
1451                    op,
1452                    lhs: Box::new(left),
1453                    rhs: Box::new(right),
1454                };
1455            }
1456            Kind::Equals => {
1457                self.next();
1458                let right = self.parse_additive()?;
1459                left = Expr::BinaryOp {
1460                    op: BinOp::Eq,
1461                    lhs: Box::new(left),
1462                    rhs: Box::new(right),
1463                };
1464            }
1465            Kind::Not => {
1466                // ! or != operator (RuneScript uses both forms for not-equal)
1467                self.next(); // consume !
1468                // Optional '=' for != form
1469                if self.peek_kind() == Kind::Equals {
1470                    self.next();
1471                }
1472                let right = self.parse_additive()?;
1473                left = Expr::BinaryOp {
1474                    op: BinOp::NotEq,
1475                    lhs: Box::new(left),
1476                    rhs: Box::new(right),
1477                };
1478            }
1479            _ => {}
1480        }
1481
1482        Ok(left)
1483    }
1484
1485    fn parse_additive(&mut self) -> Result<Expr, SyntaxError> {
1486        let mut left = self.parse_multiplicative()?;
1487
1488        while self.peek_kind() == Kind::BinaryOperator {
1489            let tok = self.at().clone();
1490            match tok.value.as_str() {
1491                "+" | "-" => {
1492                    self.next();
1493                    let op = if tok.value == "+" {
1494                        BinOp::Add
1495                    } else {
1496                        BinOp::Sub
1497                    };
1498                    let right = self.parse_multiplicative()?;
1499                    left = Expr::BinaryOp {
1500                        op,
1501                        lhs: Box::new(left),
1502                        rhs: Box::new(right),
1503                    };
1504                }
1505                _ => break,
1506            }
1507        }
1508
1509        Ok(left)
1510    }
1511
1512    fn parse_multiplicative(&mut self) -> Result<Expr, SyntaxError> {
1513        let mut left = self.parse_primary()?;
1514
1515        loop {
1516            let tok = self.at().clone();
1517            match (tok.kind, tok.value.as_str()) {
1518                (Kind::BinaryOperator, "*") => {
1519                    self.next();
1520                    let right = self.parse_primary()?;
1521                    left = Expr::BinaryOp {
1522                        op: BinOp::Mul,
1523                        lhs: Box::new(left),
1524                        rhs: Box::new(right),
1525                    };
1526                }
1527                (Kind::BinaryOperator, "/") => {
1528                    self.next();
1529                    let right = self.parse_primary()?;
1530                    left = Expr::BinaryOp {
1531                        op: BinOp::Div,
1532                        lhs: Box::new(left),
1533                        rhs: Box::new(right),
1534                    };
1535                }
1536                (Kind::BinaryOperator, "%") => {
1537                    // % is the modulo operator in arithmetic contexts (inside calc)
1538                    self.next();
1539                    let right = self.parse_primary()?;
1540                    left = Expr::BinaryOp {
1541                        op: BinOp::Mod,
1542                        lhs: Box::new(left),
1543                        rhs: Box::new(right),
1544                    };
1545                }
1546                _ => break,
1547            }
1548        }
1549
1550        Ok(left)
1551    }
1552
1553    fn parse_primary(&mut self) -> Result<Expr, SyntaxError> {
1554        match self.peek_kind() {
1555            Kind::Number => {
1556                let tok = self.next();
1557                let value: i32 = tok.value.parse().map_err(|_| {
1558                    SyntaxError::from_token(
1559                        self.file_path.clone(),
1560                        &tok,
1561                        format!("Invalid integer literal: {}", tok.value),
1562                    )
1563                })?;
1564                if self.peek_kind() == Kind::Colon
1565                    && self.peek_kind_ahead(1) == Kind::Number
1566                    && matches!(
1567                        self.peek_kind_ahead(2),
1568                        Kind::Comma | Kind::RParen | Kind::Semicolon | Kind::RBrace
1569                    )
1570                {
1571                    self.next();
1572                    let component = self.expect(Kind::Number)?;
1573                    let component: u16 = component.value.parse().map_err(|_| {
1574                        SyntaxError::from_token(
1575                            self.file_path.clone(),
1576                            &component,
1577                            "Invalid component ID".into(),
1578                        )
1579                    })?;
1580                    let interface = u16::try_from(value).map_err(|_| {
1581                        SyntaxError::from_token(
1582                            self.file_path.clone(),
1583                            &tok,
1584                            "Invalid interface ID".into(),
1585                        )
1586                    })?;
1587                    return Ok(Expr::IntLiteral(
1588                        ((interface as i32) << 16) | component as i32,
1589                    ));
1590                }
1591                Ok(Expr::IntLiteral(value))
1592            }
1593
1594            Kind::LongLiteral => {
1595                let tok = self.next();
1596                let value: i64 = tok.value.parse().map_err(|_| {
1597                    SyntaxError::from_token(
1598                        self.file_path.clone(),
1599                        &tok,
1600                        format!("Invalid long literal: {}", tok.value),
1601                    )
1602                })?;
1603                Ok(Expr::LongLiteral(value))
1604            }
1605
1606            Kind::RawStringLiteral => Ok(Expr::StringLiteral(self.next().value)),
1607            Kind::StringLiteral => {
1608                let tok = self.next();
1609                // Check if string contains interpolation markers (<expr>)
1610                if tok.value.contains('<') && tok.value.contains('>') {
1611                    Ok(self.parse_interpolated_string(&tok.value))
1612                } else {
1613                    Ok(Expr::StringLiteral(tok.value.replace(ESCAPED_LT, "<")))
1614                }
1615            }
1616
1617            Kind::CharLiteral => {
1618                let tok = self.next();
1619                let ch = tok.value.chars().next().unwrap_or('\0');
1620                Ok(Expr::CharLiteral(ch))
1621            }
1622
1623            Kind::CoordLiteral => {
1624                let tok = self.next();
1625                // Parse coord literal: level_bx_bz_lx_lz
1626                // Packed as: (level << 28) | ((bx*64 + lx) << 14) | (bz*64 + lz)
1627                let parts: Vec<&str> = tok.value.split('_').collect();
1628                let coord_val = if parts.len() == 5 {
1629                    let level: i32 = parts[0].parse().unwrap_or(0);
1630                    let bx: i32 = parts[1].parse().unwrap_or(0);
1631                    let bz: i32 = parts[2].parse().unwrap_or(0);
1632                    let lx: i32 = parts[3].parse().unwrap_or(0);
1633                    let lz: i32 = parts[4].parse().unwrap_or(0);
1634                    let x = bx * 64 + lx;
1635                    let z = bz * 64 + lz;
1636                    (level << 28) | (x << 14) | z
1637                } else {
1638                    0
1639                };
1640                Ok(Expr::CoordLiteral(coord_val))
1641            }
1642
1643            Kind::BooleanTrue => {
1644                self.next();
1645                Ok(Expr::BoolLiteral(true))
1646            }
1647
1648            Kind::BooleanFalse => {
1649                self.next();
1650                Ok(Expr::BoolLiteral(false))
1651            }
1652
1653            Kind::Null => {
1654                self.next();
1655                Ok(Expr::NullLiteral)
1656            }
1657
1658            Kind::Underscore if self.peek_kind_ahead(1) == Kind::LocalVar => {
1659                self.next(); // consume _
1660                self.next(); // consume $
1661                let name_tok = self.next();
1662                let name = format!("_{}", name_tok.value);
1663
1664                if self.peek_kind() == Kind::LParen {
1665                    self.expect(Kind::LParen)?;
1666                    let index = self.parse_expression()?;
1667                    self.expect(Kind::RParen)?;
1668                    return Ok(Expr::ArrayAccess {
1669                        name,
1670                        index: Box::new(index),
1671                    });
1672                }
1673
1674                Ok(Expr::LocalVar(name, self.line()))
1675            }
1676
1677            Kind::LocalVar => {
1678                self.next(); // consume $
1679                let name_tok = self.next();
1680                let name = name_tok.value.clone();
1681
1682                // Check for array access: $arr($idx)
1683                if self.peek_kind() == Kind::LParen {
1684                    self.expect(Kind::LParen)?;
1685                    let index = self.parse_expression()?;
1686                    self.expect(Kind::RParen)?;
1687                    return Ok(Expr::ArrayAccess {
1688                        name,
1689                        index: Box::new(index),
1690                    });
1691                }
1692
1693                Ok(Expr::LocalVar(name, self.line()))
1694            }
1695
1696            Kind::GameVar => {
1697                self.next(); // consume %
1698                let name_tok = self.next();
1699                Ok(Expr::GameVar(name_tok.value.clone(), self.line()))
1700            }
1701
1702            Kind::ConstantVar => {
1703                let const_line = self.line();
1704                self.next(); // consume ^
1705                let name_tok = self.next();
1706                Ok(Expr::ConstantVar(name_tok.value.clone(), const_line))
1707            }
1708
1709            Kind::Calc => {
1710                self.next(); // consume 'calc'
1711                self.expect(Kind::LParen)?;
1712                let expr = self.parse_expression()?;
1713                self.expect(Kind::RParen)?;
1714                Ok(Expr::Calc(Box::new(expr)))
1715            }
1716
1717            Kind::ScriptCall => {
1718                let call_line = if self.is_sub_parser { 0 } else { self.line() };
1719                self.next(); // consume ~
1720                // Allow optional leading dot for ~.name
1721                let dot = if self.peek_kind() == Kind::Dot {
1722                    self.next();
1723                    "."
1724                } else {
1725                    ""
1726                };
1727                let name_tok = self.next();
1728                let name = format!("{}{}", dot, name_tok.value);
1729
1730                let (args, arg_lines) = if self.peek_kind() == Kind::LParen {
1731                    self.parse_call_args()?
1732                } else {
1733                    (Vec::new(), Vec::new())
1734                };
1735
1736                Ok(Expr::ProcCall {
1737                    name,
1738                    args,
1739                    arg_lines,
1740                    call_line,
1741                })
1742            }
1743
1744            Kind::JumpCall => {
1745                let call_line = if self.is_sub_parser { 0 } else { self.line() };
1746                self.next(); // consume @
1747                // Allow optional leading dot for @.name
1748                let dot = if self.peek_kind() == Kind::Dot {
1749                    self.next();
1750                    "."
1751                } else {
1752                    ""
1753                };
1754                let name_tok = self.next();
1755                let name = format!("{}{}", dot, name_tok.value);
1756
1757                let (args, arg_lines) = if self.peek_kind() == Kind::LParen {
1758                    self.parse_call_args()?
1759                } else {
1760                    (Vec::new(), Vec::new())
1761                };
1762
1763                Ok(Expr::JumpCall {
1764                    name,
1765                    args,
1766                    arg_lines,
1767                    call_line,
1768                })
1769            }
1770
1771            Kind::Dot => {
1772                self.next(); // consume '.'
1773                match self.peek_kind() {
1774                    Kind::GameVar => {
1775                        // .%varname — dot-prefixed game var (secondary pointer)
1776                        self.next(); // consume %
1777                        let name_tok = self.next();
1778                        Ok(Expr::GameVar(format!(".{}", name_tok.value), self.line()))
1779                    }
1780                    Kind::LocalVar => {
1781                        // .$varname — dot-prefixed local var (unusual but handle it)
1782                        self.next(); // consume $
1783                        let name_tok = self.next();
1784                        Ok(Expr::LocalVar(format!(".{}", name_tok.value), self.line()))
1785                    }
1786                    _ => {
1787                        // Dot-prefixed command call: .huntnext(args)
1788                        let call_line = if self.is_sub_parser { 0 } else { self.line() };
1789                        let name_tok = self.next();
1790                        let mut name = format!(".{}", name_tok.value);
1791                        if self.star_suffix(&name_tok) {
1792                            self.next();
1793                            name.push('*');
1794                        }
1795                        let (mut args, mut arg_lines) = if self.peek_kind() == Kind::LParen {
1796                            self.parse_call_args()?
1797                        } else {
1798                            (Vec::new(), Vec::new())
1799                        };
1800                        // Handle second arg group for vararg commands
1801                        if self.peek_kind() == Kind::LParen {
1802                            let (extra_args, extra_lines) = self.parse_call_args()?;
1803                            args.extend(extra_args);
1804                            arg_lines.extend(extra_lines);
1805                        }
1806                        Ok(Expr::CommandCall {
1807                            name,
1808                            args,
1809                            arg_lines,
1810                            call_line,
1811                        })
1812                    }
1813                }
1814            }
1815
1816            Kind::Identifier | Kind::Command | Kind::Trigger => {
1817                let tok = self.next();
1818                let mut name = tok.value.clone();
1819
1820                if self.star_suffix(&tok) {
1821                    self.next();
1822                    name.push('*');
1823                }
1824
1825                // Check if this is a command call: name(args) or name(args)(extra_args)
1826                if self.peek_kind() == Kind::LParen {
1827                    let call_line = if self.is_sub_parser { 0 } else { self.line() };
1828                    let (mut args, mut arg_lines) = self.parse_call_args()?;
1829                    // Handle second arg group for vararg commands: queue*(a,b)(extra_args)
1830                    if self.peek_kind() == Kind::LParen {
1831                        let (extra_args, extra_lines) = self.parse_call_args()?;
1832                        args.extend(extra_args);
1833                        arg_lines.extend(extra_lines);
1834                    }
1835                    return Ok(Expr::CommandCall {
1836                        name,
1837                        args,
1838                        arg_lines,
1839                        call_line,
1840                    });
1841                }
1842
1843                // Handle component:field compound identifiers (e.g., duel_confirm:before_rule_line1)
1844                // Only consume when the token AFTER the compound is a value terminator
1845                // (RParen, Comma, Semicolon) — not ':' (case separator) or '(' (statement start).
1846                if self.peek_kind() == Kind::Colon {
1847                    let after_colon = self.peek_kind_ahead(1);
1848                    let after_compound = self.peek_kind_ahead(2);
1849                    if matches!(
1850                        after_colon,
1851                        Kind::Identifier | Kind::Number | Kind::Trigger | Kind::Command
1852                    ) && matches!(
1853                        after_compound,
1854                        Kind::RParen
1855                            | Kind::Comma
1856                            | Kind::Semicolon
1857                            | Kind::RBrace
1858                            | Kind::Colon
1859                            | Kind::ComparisonOperator
1860                            | Kind::LogicalAnd
1861                            | Kind::LogicalOr
1862                            | Kind::BinaryOperator
1863                    ) {
1864                        self.next(); // consume ':'
1865                        let part = self.next();
1866                        return Ok(Expr::Identifier(format!("{}:{}", name, part.value)));
1867                    }
1868                }
1869
1870                if let Some((_, array)) = array_name(&name) {
1871                    return Ok(Expr::IntLiteral(array));
1872                }
1873                Ok(Expr::Identifier(name))
1874            }
1875
1876            Kind::LParen => {
1877                self.next(); // consume (
1878                let expr = self.parse_expression()?;
1879                self.expect(Kind::RParen)?;
1880                Ok(expr)
1881            }
1882
1883            Kind::BinaryOperator if self.at().value == "-" => {
1884                // Unary negation - constant fold numeric literals
1885                self.next();
1886                if self.peek_kind() == Kind::Number && self.at().value == "2147483648" {
1887                    self.next();
1888                    return Ok(Expr::IntLiteral(i32::MIN));
1889                }
1890                let expr = self.parse_primary()?;
1891                match expr {
1892                    Expr::IntLiteral(n) => Ok(Expr::IntLiteral(-n)),
1893                    Expr::LongLiteral(n) => Ok(Expr::LongLiteral(-n)),
1894                    other => Ok(Expr::BinaryOp {
1895                        op: BinOp::Sub,
1896                        lhs: Box::new(Expr::IntLiteral(0)),
1897                        rhs: Box::new(other),
1898                    }),
1899                }
1900            }
1901
1902            _ => {
1903                let tok = self.at().clone();
1904                Err(SyntaxError::from_token(
1905                    self.file_path.clone(),
1906                    &tok,
1907                    format!("Unexpected token: {:?} '{}'", tok.kind, tok.value),
1908                ))
1909            }
1910        }
1911    }
1912
1913    fn parse_call_args(&mut self) -> Result<(Vec<Expr>, Vec<usize>), SyntaxError> {
1914        self.expect(Kind::LParen)?;
1915        let mut args = Vec::new();
1916        let mut arg_lines = Vec::new();
1917        while self.peek_kind() != Kind::RParen {
1918            if !args.is_empty() {
1919                self.expect(Kind::Comma)?;
1920            }
1921            let arg_line = if self.is_sub_parser { 0 } else { self.line() };
1922            let expr = self.parse_expression()?;
1923            // Handle component:field or table:column compound reference inside call args.
1924            // This is only valid in argument position, not in switch cases or conditions.
1925            let expr = if let Expr::Identifier(ref name) = expr {
1926                if self.peek_kind() == Kind::Colon {
1927                    let after_colon = self.peek_kind_ahead(1);
1928                    if matches!(
1929                        after_colon,
1930                        Kind::Identifier | Kind::Number | Kind::Trigger | Kind::Command
1931                    ) {
1932                        let name = name.clone();
1933                        self.next(); // consume ':'
1934                        let second = self.next();
1935                        let compound = format!("{}:{}", name, second.value);
1936                        if self.peek_kind() == Kind::LParen {
1937                            let call_line = if self.is_sub_parser { 0 } else { self.line() };
1938                            let (inner_args, inner_arg_lines) = self.parse_call_args()?;
1939                            Expr::CommandCall {
1940                                name: compound,
1941                                args: inner_args,
1942                                arg_lines: inner_arg_lines,
1943                                call_line,
1944                            }
1945                        } else {
1946                            Expr::Identifier(compound)
1947                        }
1948                    } else {
1949                        expr
1950                    }
1951                } else {
1952                    expr
1953                }
1954            } else {
1955                expr
1956            };
1957            args.push(expr);
1958            arg_lines.push(arg_line);
1959        }
1960        self.expect(Kind::RParen)?;
1961        Ok((args, arg_lines))
1962    }
1963
1964    /// Parse a single expression from a string slice, returning an Expr.
1965    /// Used for embedded expressions in string templates like `<tostring($var)>`.
1966    fn parse_string_embedded_expr(&self, expr_str: &str) -> Expr {
1967        let escaped = expr_str.replace(ESCAPED_LT, "\\<");
1968        let expr_str = escaped.as_str();
1969        if let Some(stripped) = expr_str.strip_prefix('$') {
1970            return Expr::LocalVar(stripped.to_string(), 0);
1971        }
1972        if let Some(stripped) = expr_str.strip_prefix('%') {
1973            return Expr::GameVar(stripped.to_string(), 0);
1974        }
1975        if let Some(stripped) = expr_str.strip_prefix('^') {
1976            return Expr::ConstantVar(stripped.to_string(), 0);
1977        }
1978        // Try to parse as a full expression using a sub-parser.
1979        let dummy_path = self.file_path.clone();
1980        let mut lexer = Lexer::new(expr_str, &dummy_path);
1981        if let Ok(tokens) = lexer.tokenize()
1982            && !tokens.is_empty()
1983        {
1984            let mut sub = Parser::new(tokens, &dummy_path);
1985            sub.is_sub_parser = true;
1986            if let Ok(expr) = sub.parse_expression() {
1987                return expr;
1988            }
1989        }
1990        // Fallback: treat as plain identifier
1991        Expr::Identifier(expr_str.to_string())
1992    }
1993
1994    fn parse_interpolated_string(&self, raw: &str) -> Expr {
1995        let mut parts = Vec::new();
1996        let mut current = String::new();
1997        let chars = raw.chars().peekable();
1998        let mut depth = 0;
1999        let mut in_expr = false;
2000        let mut expr_str = String::new();
2001        let mut quote = None;
2002        let mut escaped = false;
2003
2004        for ch in chars {
2005            if in_expr {
2006                if escaped {
2007                    escaped = false;
2008                    expr_str.push(ch);
2009                    continue;
2010                }
2011                if quote.is_some() && ch == '\\' {
2012                    escaped = true;
2013                    expr_str.push(ch);
2014                    continue;
2015                }
2016                if Some(ch) == quote {
2017                    quote = None;
2018                } else if quote.is_none() && matches!(ch, '"' | '\'') {
2019                    quote = Some(ch);
2020                }
2021                if ch == '>' && depth == 0 && quote.is_none() {
2022                    in_expr = false;
2023                    // Treat as a code expression if it looks like RS2 code:
2024                    // starts with $/%/^/~ OR contains ( (function call).
2025                    // Otherwise it's a literal formatting tag like <p,neutral> or <col=ff0000>.
2026                    // A tag is "code" if it looks like RS2 code rather than an HTML-like
2027                    // formatting tag. Variable/constant/proc prefixes and function calls are
2028                    // obviously code. A bare identifier like <displayname> or <npc_name> is
2029                    // also code (it refers to a command call), while tags containing commas,
2030                    // equals signs, spaces, or colons are formatting tags like <p,neutral> or
2031                    // <col=ff0000>.
2032                    // A plain identifier or .identifier (dot-prefixed for secondary entity)
2033                    // like <displayname> or <.displayname> is a command call.
2034                    let stripped = expr_str.strip_prefix('.').unwrap_or(expr_str.as_str());
2035                    let is_plain_identifier = !stripped.is_empty()
2036                        && !matches!(
2037                            stripped,
2038                            "br" | "lt"
2039                                | "gt"
2040                                | "nbsp"
2041                                | "shy"
2042                                | "times"
2043                                | "euro"
2044                                | "copy"
2045                                | "reg"
2046                                | "u"
2047                                | "str"
2048                                | "shad"
2049                                | "trans"
2050                                | "col"
2051                        )
2052                        && stripped
2053                            .chars()
2054                            .all(|c| c.is_ascii_alphanumeric() || c == '_');
2055                    // A number is a piece of literal text.
2056                    if !expr_str.is_empty() && expr_str.bytes().all(|byte| byte.is_ascii_digit()) {
2057                        parts.push(StringPart::Literal(expr_str.clone()));
2058                        expr_str.clear();
2059                        continue;
2060                    }
2061                    let is_code = !is_string_tag(&expr_str)
2062                        && (expr_str.starts_with('$')
2063                            || expr_str.starts_with('"')
2064                            || expr_str.starts_with('%')
2065                            || expr_str.starts_with('^')
2066                            || expr_str.starts_with('~')
2067                            || expr_str.contains('(')
2068                            || is_plain_identifier);
2069                    if is_code {
2070                        let expr = self.parse_string_embedded_expr(&expr_str);
2071                        parts.push(StringPart::Expr(expr));
2072                    } else {
2073                        // Literal tag: push "<tag>" as a separate literal string part
2074                        let tag_lit = format!("<{}>", expr_str);
2075                        parts.push(StringPart::Literal(tag_lit));
2076                    }
2077                    expr_str.clear();
2078                } else {
2079                    if ch == '(' && quote.is_none() {
2080                        depth += 1;
2081                    }
2082                    if ch == ')' && quote.is_none() {
2083                        depth -= 1;
2084                    }
2085                    expr_str.push(ch);
2086                }
2087            } else if ch == ESCAPED_LT {
2088                current.push('<');
2089            } else if ch == '<' {
2090                if !current.is_empty() {
2091                    parts.push(StringPart::Literal(current.clone()));
2092                    current.clear();
2093                }
2094                in_expr = true;
2095                depth = 0;
2096                quote = None;
2097            } else {
2098                current.push(ch);
2099            }
2100        }
2101
2102        if !current.is_empty() {
2103            parts.push(StringPart::Literal(current));
2104        }
2105
2106        if parts.len() == 1 {
2107            match &parts[0] {
2108                StringPart::Literal(s) => return Expr::StringLiteral(s.clone()),
2109                // Single expression part (e.g., "<oc_name($obj)>") needs no JoinString.
2110                StringPart::Expr(e) => return e.clone(),
2111            }
2112        }
2113
2114        Expr::JoinedString { parts }
2115    }
2116}
2117
2118/// Whether `inner`, the text between a string's `<` and `>`, is a formatting
2119/// tag rather than code: Neptune's lexer (`RuneScriptLexer.g4`, `STRING_TAG`
2120/// and `STRING_CLOSE_TAG`) reads `<` Tag (`=` value)? `>` and `</` Tag `>` as
2121/// tags, with Tag one of br, col, str, shad, u, img, gt, lt. So `<br>` is a
2122/// line break, not a call to a command named `br`.
2123fn is_string_tag(inner: &str) -> bool {
2124    const TAGS: [&str; 8] = ["br", "col", "str", "shad", "u", "img", "gt", "lt"];
2125    let (name, closing) = match inner.strip_prefix('/') {
2126        Some(rest) => (rest, true),
2127        None => (inner, false),
2128    };
2129    let (name, has_value) = match name.split_once('=') {
2130        Some((name, value)) => (name, !value.is_empty()),
2131        None => (name, false),
2132    };
2133    TAGS.contains(&name) && !(closing && has_value)
2134}