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