Skip to main content

runec/
parser.rs

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