Skip to main content

runec/
parser.rs

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