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