Skip to main content

runec/
compiler.rs

1use crate::bytecode::*;
2use crate::parser::*;
3use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
4use crate::types::{BaseVarType, Type};
5
6/// Code generator that transforms parsed AST into bytecode instructions.
7pub struct Compiler {
8    pub registry: SymbolRegistry,
9    /// Return types of the currently-compiling script (used for type hints in return statements).
10    current_return_types: Vec<Type>,
11    /// The line number of the currently-compiling statement.
12    current_stmt_line: usize,
13}
14
15impl Compiler {
16    pub fn new(registry: SymbolRegistry) -> Self {
17        Compiler {
18            registry,
19            current_return_types: Vec::new(),
20            current_stmt_line: 0,
21        }
22    }
23
24    /// Compile a single script declaration into bytecode.
25    pub fn compile_script(&mut self, script: &ScriptDeclaration) -> CompiledScript {
26        let id = self
27            .registry
28            .script_id_for_trigger(&script.trigger, &script.name)
29            .or_else(|| self.registry.script_id(&script.name))
30            .unwrap_or(-1);
31        let full_name = format!("[{},{}]", script.trigger, script.name);
32        let mut compiled = CompiledScript::new(full_name, id);
33        compiled.trigger = script.trigger.clone();
34        compiled.lookup_key =
35            Self::compute_lookup_key(&script.trigger, &script.name, &self.registry);
36        compiled.param_types = script.params.iter().map(|p| p.param_type).collect();
37        let mut locals = SymbolTable::new();
38
39        // Register parameters — push to LocalTable AND define in SymbolTable
40        for param in &script.params {
41            let slot = compiled
42                .local_table
43                .push_param(param.name.clone(), param.param_type);
44            locals.define(
45                param.name.clone(),
46                SymbolKind::ScriptParam {
47                    param_type: param.param_type,
48                    slot,
49                },
50            );
51        }
52
53        // Compile body statements
54        self.current_return_types = script.return_types.clone();
55        for stmt in &script.body {
56            self.compile_statement(stmt, &mut compiled, &mut locals);
57        }
58
59        // Always emit a fallthrough return at the end
60        for ret_type in &script.return_types {
61            match ret_type.base_type() {
62                BaseVarType::Integer => {
63                    compiled.push(Instruction::push_int(ret_type.default_return_value()))
64                }
65                BaseVarType::String => compiled.push(Instruction::push_string(String::new())),
66                BaseVarType::Long => compiled.push(Instruction::push_long(0)),
67            }
68        }
69        compiled.push(Instruction::simple(Opcode::Return));
70
71        // Set local variable counts from LocalTable (matching TS getLocalCount/getParameterCount)
72        compiled.int_local_count = compiled.local_table.get_local_count(BaseVarType::Integer);
73        compiled.string_local_count = compiled.local_table.get_local_count(BaseVarType::String);
74        compiled.long_local_count = compiled.local_table.get_local_count(BaseVarType::Long);
75        compiled.int_arg_count = compiled.local_table.get_param_count(BaseVarType::Integer);
76        compiled.string_arg_count = compiled.local_table.get_param_count(BaseVarType::String);
77        compiled.long_arg_count = compiled.local_table.get_param_count(BaseVarType::Long);
78
79        compiled
80    }
81
82    fn emit_line(line: usize, out: &mut CompiledScript) {
83        out.push(Instruction::new(
84            Opcode::LineNumber,
85            Operand::Int(line as i32),
86        ));
87    }
88
89    fn emit_comparison_value(
90        branch_opcode: Opcode,
91        fallthrough_value: i32,
92        branch_value: i32,
93        out: &mut CompiledScript,
94    ) {
95        let branch_pos = out.len();
96        out.push(Instruction::new(branch_opcode, Operand::JumpTarget(0)));
97        out.push(Instruction::push_int(fallthrough_value));
98        let jump_pos = out.len();
99        out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
100        let branch_target = out.len();
101        out.push(Instruction::push_int(branch_value));
102        let end_pos = out.len();
103        out.patch_jump(branch_pos, branch_target);
104        out.patch_jump(jump_pos, end_pos);
105    }
106
107    fn compile_statement(
108        &mut self,
109        stmt: &Statement,
110        out: &mut CompiledScript,
111        locals: &mut SymbolTable,
112    ) {
113        // Track the statement's line for re-emission after multi-line call arguments.
114        match stmt {
115            Statement::VarDeclaration { line, .. }
116            | Statement::ArrayDeclaration { line, .. }
117            | Statement::Assignment { line, .. }
118            | Statement::If { line, .. }
119            | Statement::While { line, .. }
120            | Statement::Switch { line, .. }
121            | Statement::Return { line, .. }
122            | Statement::Expression { line, .. }
123            | Statement::OrphanCase { line, .. } => {
124                self.current_stmt_line = *line;
125            }
126            Statement::Empty => {}
127        }
128        match stmt {
129            Statement::VarDeclaration {
130                var_type,
131                name,
132                value,
133                line,
134            } => {
135                // Push to LocalTable for slot assignment (matching TS locals.all.push)
136                let slot = out.local_table.push_local(name.clone(), *var_type, false);
137                // Also define in SymbolTable for scoped name resolution
138                locals.define(
139                    name.clone(),
140                    SymbolKind::LocalVar {
141                        var_type: *var_type,
142                        slot,
143                        is_array: false,
144                    },
145                );
146
147                if let Some(init) = value {
148                    // With initial value: LineNumber BEFORE the expression.
149                    // The arg-based LineNumber emission in calls may override this via writer
150                    // deduplication (same-PC rule keeps the last line number).
151                    Self::emit_line(*line, out);
152                    // Use the declared var type as a hint so identifiers resolve to the
153                    // correct entity ID (e.g. `def_npc_stat $x = magic` → npc_stat id=5, not stat id=6).
154                    self.compile_expr_hinted(init, out, locals, Some(*var_type));
155                    // Emit LineNumber(stmt_line) again before the pop instruction.
156                    // For multi-line init calls, this re-anchors the pop to the statement's line.
157                    // Writer deduplication handles same-line cases (no extra entry emitted).
158                    Self::emit_line(*line, out);
159                } else {
160                    // No initial value: Java pushes default BEFORE the LineNumber
161                    match var_type.base_type() {
162                        BaseVarType::Integer => {
163                            out.push(Instruction::push_int(var_type.default_int_value()))
164                        }
165                        BaseVarType::String => out.push(Instruction::push_string(String::new())),
166                        BaseVarType::Long => out.push(Instruction::push_long(0)),
167                    }
168                    Self::emit_line(*line, out);
169                }
170
171                // Pop into local variable slot
172                let pop_opcode = match var_type.base_type() {
173                    BaseVarType::Integer => Opcode::PopIntLocal,
174                    BaseVarType::String => Opcode::PopStringLocal,
175                    BaseVarType::Long => Opcode::PopLongLocal,
176                };
177                out.push(Instruction::new(pop_opcode, Operand::Int(slot)));
178            }
179
180            Statement::ArrayDeclaration {
181                element_type,
182                name,
183                size,
184                line,
185            } => {
186                Self::emit_line(*line, out);
187                let slot = out
188                    .local_table
189                    .push_local(name.clone(), *element_type, true);
190                locals.define(
191                    name.clone(),
192                    SymbolKind::LocalVar {
193                        var_type: *element_type,
194                        slot,
195                        is_array: true,
196                    },
197                );
198
199                // Push array size
200                self.compile_expr(size, out, locals);
201                out.push(Instruction::pop_int_local(slot));
202
203                // Emit define array
204                let type_char = match element_type.base_type() {
205                    BaseVarType::Integer => b'i',
206                    BaseVarType::String => b's',
207                    BaseVarType::Long => b'l',
208                };
209                out.push(Instruction::new(
210                    Opcode::DefineArray,
211                    Operand::ArrayDef(slot, type_char),
212                ));
213
214                let _ = line;
215            }
216
217            Statement::Assignment {
218                target,
219                value,
220                line,
221            } => {
222                Self::emit_line(*line, out);
223                // Infer the target type to use as a hint when compiling the value.
224                let target_type_hint = self.infer_target_type(target, locals);
225                self.compile_expr_hinted(value, out, locals, target_type_hint);
226                self.compile_store(target, out, locals);
227            }
228
229            Statement::If {
230                condition,
231                body,
232                else_if,
233                else_body,
234                else_line,
235                line,
236            } => {
237                Self::emit_line(*line, out);
238                self.compile_if(condition, body, else_if, else_body, *else_line, out, locals);
239            }
240
241            Statement::While {
242                condition,
243                body,
244                line,
245            } => {
246                Self::emit_line(*line, out);
247                let loop_start = out.len();
248
249                // Java pattern: BranchTrue(body) + Branch(exit) before body
250                let (true_positions, false_positions) =
251                    self.compile_condition(condition, out, locals);
252
253                // Patch true branches to body_start
254                let body_start = out.len();
255                for pos in &true_positions {
256                    out.patch_jump(*pos, body_start);
257                }
258
259                // Compile body
260                for s in body {
261                    self.compile_statement(s, out, locals);
262                }
263
264                // Jump back to loop start
265                out.push(Instruction::new(
266                    Opcode::Branch,
267                    Operand::JumpTarget(loop_start),
268                ));
269
270                // Patch false branches to exit
271                let exit_pos = out.len();
272                for pos in &false_positions {
273                    out.patch_jump(*pos, exit_pos);
274                }
275            }
276
277            Statement::Switch {
278                switch_type,
279                expr,
280                cases,
281                default,
282                default_index,
283                line,
284            } => {
285                Self::emit_line(*line, out);
286                self.compile_switch(
287                    switch_type,
288                    expr,
289                    cases,
290                    default,
291                    *default_index,
292                    out,
293                    locals,
294                );
295            }
296
297            Statement::Return { values, line } => {
298                Self::emit_line(*line, out);
299                let return_types = self.current_return_types.clone();
300                for (i, val) in values.iter().enumerate() {
301                    let hint = return_types.get(i).copied();
302                    self.compile_expr_hinted(val, out, locals, hint);
303                }
304                out.push(Instruction::simple(Opcode::Return));
305            }
306
307            Statement::Expression { expr, line } => {
308                // Java compiler behavior: for CommandCall expressions, leading ConstantVar
309                // args that resolve to strings are pushed BEFORE the LineNumber instruction.
310                let cmd_args_offset = if let Expr::CommandCall { name, args, .. } = expr {
311                    let n = self.count_pre_stmt_string_args(name, args);
312                    if n > 0 {
313                        // The reference compiler emits LineNumber(stmt_line - 1) before the
314                        // pre-stmt string args, but ONLY when the first pre-stmt arg is a
315                        // string constant (^name). Null literals and string literals don't
316                        // trigger the line-1 emission.
317                        let first_is_const = matches!(&args[0], Expr::ConstantVar(..));
318                        if first_is_const && *line > 1 {
319                            Self::emit_line(*line - 1, out);
320                        }
321                        let lookup = name.strip_prefix('.').unwrap_or(name);
322                        let ptypes: Vec<Type> = self
323                            .registry
324                            .command_param_types
325                            .get(lookup)
326                            .cloned()
327                            .unwrap_or_default();
328                        for (j, arg) in args[..n].iter().enumerate() {
329                            let hint = ptypes.get(j).copied();
330                            self.compile_expr_hinted(arg, out, locals, hint);
331                        }
332                    }
333                    n
334                } else {
335                    0
336                };
337                Self::emit_line(*line, out);
338                if cmd_args_offset > 0 {
339                    if let Expr::CommandCall {
340                        name,
341                        args,
342                        arg_lines,
343                        call_line: _,
344                    } = expr
345                    {
346                        self.compile_command_call_args_from(
347                            name,
348                            args,
349                            arg_lines,
350                            cmd_args_offset,
351                            out,
352                            locals,
353                        );
354                    }
355                } else {
356                    self.compile_expr(expr, out, locals);
357                }
358                // If the expression is a proc/label call that returns values in statement
359                // context (unused), Java emits POP_INT/STRING_DISCARD for each return value.
360                let return_types: Option<Vec<crate::types::Type>> = match expr {
361                    Expr::ProcCall { name, .. } => {
362                        self.registry.scripts.get(name.as_str()).and_then(|sym| {
363                            if let SymbolKind::Script { return_types, .. } = &sym.kind {
364                                Some(return_types.clone())
365                            } else {
366                                None
367                            }
368                        })
369                    }
370                    Expr::JumpCall { name, .. } => {
371                        self.registry.scripts.get(name.as_str()).and_then(|sym| {
372                            if let SymbolKind::Script { return_types, .. } = &sym.kind {
373                                Some(return_types.clone())
374                            } else {
375                                None
376                            }
377                        })
378                    }
379                    Expr::CommandCall { name, .. } => {
380                        // Strip leading dot for secondary entity commands
381                        let lookup_name = name.strip_prefix('.').unwrap_or(name);
382                        self.registry.commands.get(lookup_name).and_then(|sym| {
383                            if let SymbolKind::Command { return_types, .. } = &sym.kind {
384                                if return_types.is_empty() {
385                                    None
386                                } else {
387                                    Some(return_types.clone())
388                                }
389                            } else {
390                                None
391                            }
392                        })
393                    }
394                    _ => None,
395                };
396                if let Some(ret_types) = return_types {
397                    for ret_type in &ret_types {
398                        match ret_type.base_type() {
399                            BaseVarType::Integer => {
400                                out.push(Instruction::simple(Opcode::PopIntDiscard))
401                            }
402                            BaseVarType::String => {
403                                out.push(Instruction::simple(Opcode::PopStringDiscard))
404                            }
405                            BaseVarType::Long => {
406                                out.push(Instruction::simple(Opcode::PopLongDiscard))
407                            }
408                        }
409                    }
410                }
411            }
412            Statement::OrphanCase { .. } => {}
413            Statement::Empty => {}
414        }
415    }
416
417    #[allow(clippy::too_many_arguments, clippy::only_used_in_recursion)]
418    fn compile_if(
419        &mut self,
420        condition: &Expr,
421        body: &[Statement],
422        else_if: &[(Expr, Vec<Statement>, usize)],
423        else_body: &Option<Vec<Statement>>,
424        else_line: usize,
425        out: &mut CompiledScript,
426        locals: &mut SymbolTable,
427    ) {
428        let mut end_jumps = Vec::new();
429
430        // Java pattern: BranchTrue(body) + Branch(else/end)
431        let (true_positions, false_positions) = self.compile_condition(condition, out, locals);
432
433        // Patch true branches to body_start
434        let body_start = out.len();
435        for pos in &true_positions {
436            out.patch_jump(*pos, body_start);
437        }
438
439        // Compile if body
440        for s in body {
441            self.compile_statement(s, out, locals);
442        }
443
444        // Always emit Branch(end) after body (Java always does this)
445        let end_jump_pos = out.len();
446        out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
447        end_jumps.push(end_jump_pos);
448
449        // Patch false branches to else_start (right after body's Branch)
450        let else_start = out.len();
451        for pos in &false_positions {
452            out.patch_jump(*pos, else_start);
453        }
454
455        if !else_if.is_empty() {
456            // Java compiles else-if as nested: else { if (cond) { ... } else if ... }
457            // Each nesting level adds one extra Branch wrapper at the end.
458            let (first_cond, first_body, first_line) = &else_if[0];
459            let remaining = &else_if[1..];
460            // Emit line number for the else-if condition (Java does this)
461            Self::emit_line(*first_line, out);
462            self.compile_if(
463                first_cond, first_body, remaining, else_body, else_line, out, locals,
464            );
465
466            // Wrapper end-jump for this "else { ... }" level
467            let wrapper_jump = out.len();
468            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
469            end_jumps.push(wrapper_jump);
470        } else if let Some(else_stmts) = else_body {
471            // Plain else body
472            for s in else_stmts {
473                self.compile_statement(s, out, locals);
474            }
475            // Always emit Branch(end) after else body
476            let end_jump_pos = out.len();
477            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
478            end_jumps.push(end_jump_pos);
479        }
480
481        // Patch all end-jumps to here
482        let end_pos = out.len();
483        for pos in end_jumps {
484            out.patch_jump(pos, end_pos);
485        }
486    }
487
488    /// Count how many leading args are string-type expressions that should be pushed
489    /// BEFORE LineNumber in statement context (Neptune behavior).
490    /// This includes: string constants (^name), string literals, and null literals
491    /// when the command parameter type is string.
492    fn count_pre_stmt_string_args(&self, name: &str, args: &[Expr]) -> usize {
493        // Look up command parameter types to determine if null args are string-typed
494        let lookup_name = name.strip_prefix('.').unwrap_or(name);
495        let param_types: Vec<Type> = self
496            .registry
497            .command_param_types
498            .get(lookup_name)
499            .cloned()
500            .unwrap_or_default();
501
502        let mut count = 0;
503        for (i, arg) in args.iter().enumerate() {
504            let is_string_param = param_types
505                .get(i)
506                .map(|t| t.base_type() == crate::types::BaseVarType::String)
507                .unwrap_or(false);
508
509            match arg {
510                Expr::ConstantVar(cname, _) => {
511                    if let Some(sym) = self.registry.lookup_constant(cname)
512                        && let SymbolKind::Constant {
513                            string_value: Some(_),
514                            ..
515                        } = &sym.kind
516                    {
517                        count += 1;
518                        continue;
519                    }
520                    break;
521                }
522                Expr::NullLiteral if is_string_param => {
523                    count += 1;
524                    continue;
525                }
526                _ => break,
527            }
528        }
529        count
530    }
531
532    /// Compile a CommandCall expression starting at `args_start` (skipping already-pushed args).
533    fn compile_command_call_args_from(
534        &mut self,
535        name: &str,
536        args: &[Expr],
537        arg_lines: &[usize],
538        args_start: usize,
539        out: &mut CompiledScript,
540        locals: &mut SymbolTable,
541    ) {
542        let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
543            (stripped, 1u8)
544        } else {
545            (name, 0u8)
546        };
547        let param_types: Vec<Type> = self
548            .registry
549            .command_param_types
550            .get(lookup_name)
551            .cloned()
552            .unwrap_or_default();
553        let script_trigger = Self::command_script_trigger(lookup_name);
554        let variadic_info = Self::command_variadic_info(lookup_name);
555
556        for (i, arg) in args.iter().enumerate() {
557            if i < args_start {
558                continue;
559            }
560            if let Some(&al) = arg_lines.get(i)
561                && al > 0
562            {
563                Self::emit_line(al, out);
564            }
565            if i == 0
566                && let Some(trigger) = script_trigger
567                && let Expr::Identifier(script_name) = arg
568            {
569                let script_id = self
570                    .registry
571                    .script_id_for_trigger(trigger, script_name)
572                    .or_else(|| self.registry.proc_script_id(script_name))
573                    .or_else(|| self.registry.script_id(script_name))
574                    .unwrap_or(-1);
575                out.push(Instruction::push_int(script_id));
576                continue;
577            }
578            let hint = param_types.get(i).copied();
579            self.compile_expr_hinted(arg, out, locals, hint);
580        }
581
582        if let Some(fixed_arg_count) = variadic_info {
583            let variadic_args = if args.len() > fixed_arg_count {
584                &args[fixed_arg_count..]
585            } else {
586                &[]
587            };
588            let type_desc: String = variadic_args
589                .iter()
590                .map(|arg| self.infer_type_char(arg, locals))
591                .collect();
592            out.push(Instruction::push_string(type_desc));
593        }
594
595        let cmd_sym = self
596            .registry
597            .lookup_command(lookup_name)
598            .or_else(|| {
599                lookup_name.strip_suffix('*').and_then(|base| {
600                    let vararg_name = format!("{}vararg", base);
601                    self.registry.lookup_command(&vararg_name)
602                })
603            })
604            .cloned();
605        if let Some(sym) = cmd_sym {
606            if let SymbolKind::Command { opcode, .. } = &sym.kind {
607                let encoded = opcode | ((cmd_index as i32) << 16);
608                out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
609            }
610        } else {
611            out.push(Instruction::new(
612                Opcode::Command,
613                Operand::Str(name.to_string()),
614            ));
615        }
616    }
617
618    /// Compile a condition expression emitting Java-style BranchTrue + Branch pair.
619    /// Returns (true_branch_positions, false_branch_positions):
620    ///   true_branch_positions  = indices of BranchXxx instructions that jump to the body
621    ///   false_branch_positions = indices of Branch instructions that jump to the else/end
622    fn compile_condition(
623        &mut self,
624        condition: &Expr,
625        out: &mut CompiledScript,
626        locals: &mut SymbolTable,
627    ) -> (Vec<usize>, Vec<usize>) {
628        match condition {
629            Expr::BinaryOp { op, lhs, rhs } => {
630                // Infer lhs type to use as hint for rhs (type-aware entity ID resolution).
631                let lhs_type_hint = self.infer_type(lhs, locals);
632                self.compile_expr(lhs, out, locals);
633                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
634
635                // Emit positive branch (branch-if-true to body)
636                let opcode = match op {
637                    BinOp::Eq => Opcode::BranchEquals,
638                    BinOp::NotEq => Opcode::BranchNot,
639                    BinOp::Lt => Opcode::BranchLessThan,
640                    BinOp::Gt => Opcode::BranchGreaterThan,
641                    BinOp::LtEq => Opcode::BranchLessThanOrEquals,
642                    BinOp::GtEq => Opcode::BranchGreaterThanOrEquals,
643                    _ => Opcode::BranchNot,
644                };
645                let true_pos = out.len();
646                out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
647
648                // Emit unconditional branch (fallthrough to else/end)
649                let false_pos = out.len();
650                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
651
652                (vec![true_pos], vec![false_pos])
653            }
654
655            Expr::LogicalOp {
656                op,
657                lhs,
658                rhs,
659                rhs_line,
660            } => {
661                match op {
662                    LogicOp::And => {
663                        // Short-circuit AND: if lhs is true continue to rhs, else → else/end
664                        let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
665
666                        // Patch lhs_true branches to rhs_start
667                        let rhs_start = out.len();
668                        for pos in &lhs_true {
669                            out.patch_jump(*pos, rhs_start);
670                        }
671
672                        // Emit LineNumber for RHS if it starts on a different line.
673                        // Writer deduplication handles same-line cases.
674                        Self::emit_line(*rhs_line, out);
675                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
676
677                        // Combined: body reached only if rhs also true
678                        // false paths: either lhs false OR rhs false
679                        let mut false_branches = lhs_false;
680                        false_branches.extend(rhs_false);
681                        (rhs_true, false_branches)
682                    }
683                    LogicOp::Or => {
684                        // Short-circuit OR: if lhs is true → body, else check rhs
685                        let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
686
687                        // Patch lhs_false branches to rhs_start
688                        let rhs_start = out.len();
689                        for pos in &lhs_false {
690                            out.patch_jump(*pos, rhs_start);
691                        }
692
693                        // Emit LineNumber for RHS if it starts on a different line.
694                        Self::emit_line(*rhs_line, out);
695                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
696
697                        // Combined: body reached if lhs true OR rhs true
698                        let mut true_branches = lhs_true;
699                        true_branches.extend(rhs_true);
700                        (true_branches, rhs_false)
701                    }
702                }
703            }
704
705            // For any other expression, push value and 0, branch if value != 0 (true)
706            _ => {
707                self.compile_expr(condition, out, locals);
708                out.push(Instruction::push_int(0));
709
710                let true_pos = out.len();
711                out.push(Instruction::new(Opcode::BranchNot, Operand::JumpTarget(0)));
712
713                let false_pos = out.len();
714                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
715
716                (vec![true_pos], vec![false_pos])
717            }
718        }
719    }
720
721    #[allow(clippy::too_many_arguments)]
722    fn compile_switch(
723        &mut self,
724        switch_type: &str,
725        expr: &Expr,
726        cases: &[SwitchCase],
727        default: &Option<Vec<Statement>>,
728        default_index: usize,
729        out: &mut CompiledScript,
730        locals: &mut SymbolTable,
731    ) {
732        self.compile_expr(expr, out, locals);
733        // Parse switch type to get type hint for case value resolution.
734        let case_type_hint =
735            Type::from_name(switch_type.strip_prefix("switch_").unwrap_or(switch_type));
736
737        // Emit SWITCH instruction (table to be filled in later)
738        let switch_idx = out.len();
739        out.push(Instruction::new(
740            Opcode::Switch,
741            Operand::SwitchTable(Vec::new()),
742        ));
743
744        // Layout (matches reference compiler):
745        //
746        //   default_index == 0 (default appeared FIRST):
747        //     [Switch]          ← on no-match, falls through to sw_pos+1 = default body
748        //     [default body]    ← at sw_pos+1
749        //     [Branch(end)]
750        //     [case_0 body]     ← switch table points here
751        //     [Branch(end)]
752        //     ...
753        //     [end_pos]
754        //
755        //   default_index > 0 (default appeared after some/all cases, or absent):
756        //     [Switch]          ← on no-match, falls through to sw_pos+1 = Branch
757        //     [Branch(to_default_or_end)]  ← at sw_pos+1
758        //     [case_0 body]
759        //     [Branch(end)]
760        //     ...
761        //     [default body]    ← emitted at source position among cases
762        //     [Branch(end)]
763        //     ...
764        //     [end_pos]
765
766        let mut end_jumps = Vec::new();
767        // position of the no-match Branch (when default is not first)
768        let default_first = default_index == 0 && default.is_some();
769
770        let default_branch_pos = if default_first {
771            // Default body at sw_pos+1 (direct fall-through, no Branch needed at sw_pos+1)
772            if let Some(default_stmts) = default {
773                for s in default_stmts {
774                    self.compile_statement(s, out, locals);
775                }
776                let jump_pos = out.len();
777                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
778                end_jumps.push(jump_pos);
779            }
780            None
781        } else {
782            // Branch at sw_pos+1 (to skip cases and reach default, or to end if no default)
783            let pos = out.len();
784            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
785            Some(pos)
786        };
787
788        // Compile case bodies in source order, inserting default at its original position
789        let mut case_positions: Vec<(Vec<i32>, usize)> = Vec::new();
790        let mut default_body_pos = 0usize;
791
792        for (i, case) in cases.iter().enumerate() {
793            // If default appeared at this position (and wasn't first), emit it now
794            if !default_first && i == default_index {
795                default_body_pos = out.len();
796                if let Some(default_stmts) = default {
797                    for s in default_stmts {
798                        self.compile_statement(s, out, locals);
799                    }
800                    let jump_pos = out.len();
801                    out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
802                    end_jumps.push(jump_pos);
803                }
804            }
805
806            let body_start = out.len();
807            let mut values = Vec::new();
808            for val in &case.values {
809                if let Expr::IntLiteral(n) = val {
810                    values.push(*n);
811                } else if let Expr::ConstantVar(cname, _) = val {
812                    // Resolve constant to integer for switch case value
813                    if let Some(sym) = self.registry.constants.get(cname)
814                        && let SymbolKind::Constant {
815                            int_value: Some(value),
816                            ..
817                        } = &sym.kind
818                    {
819                        values.push(*value);
820                    }
821                } else if let Expr::Identifier(ident) = val {
822                    // Component reference: interface:component → packed hash
823                    let mut resolved = false;
824                    if let Some((iface_name, comp_name)) = ident.split_once(':')
825                        && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
826                    {
827                        values.push(packed);
828                        resolved = true;
829                    }
830                    // Use switch type hint for type-aware resolution
831                    if !resolved
832                        && let Some(hint) = case_type_hint
833                        && let Some(id) = self.registry.lookup_entity_id_typed(ident, hint)
834                    {
835                        values.push(id);
836                        resolved = true;
837                    }
838                    if !resolved {
839                        if let Some(sym) = self.registry.entity_ids.get(ident.as_str()) {
840                            if let SymbolKind::Constant {
841                                int_value: Some(value),
842                                ..
843                            } = &sym.kind
844                            {
845                                values.push(*value);
846                            }
847                        } else if let Some(sym) = self.registry.constants.get(ident.as_str())
848                            && let SymbolKind::Constant {
849                                int_value: Some(value),
850                                ..
851                            } = &sym.kind
852                        {
853                            values.push(*value);
854                        }
855                    }
856                } else if let Expr::BinaryOp {
857                    op: BinOp::Add,
858                    lhs,
859                    rhs,
860                } = val
861                {
862                    // Handle entity names containing '+' (e.g. cheese+tom_batta)
863                    if let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
864                        (lhs.as_ref(), rhs.as_ref())
865                    {
866                        let combined = format!("{}+{}", lhs_name, rhs_name);
867                        if let Some(hint) = case_type_hint {
868                            if let Some(id) = self.registry.lookup_entity_id_typed(&combined, hint)
869                            {
870                                values.push(id);
871                            }
872                        } else if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
873                            && let SymbolKind::Constant {
874                                int_value: Some(id),
875                                ..
876                            } = &sym.kind
877                        {
878                            values.push(*id);
879                        }
880                    }
881                } else if let Expr::CoordLiteral(v) = val {
882                    values.push(*v);
883                }
884            }
885            case_positions.push((values, body_start));
886
887            for s in &case.body {
888                self.compile_statement(s, out, locals);
889            }
890
891            // Jump to end of switch (after all cases)
892            let jump_pos = out.len();
893            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
894            end_jumps.push(jump_pos);
895        }
896
897        // If default appeared after ALL explicit cases (default_index == cases.len()), emit it now
898        if !default_first && default_index >= cases.len() {
899            default_body_pos = out.len();
900            if let Some(default_stmts) = default {
901                for s in default_stmts {
902                    self.compile_statement(s, out, locals);
903                }
904                let jump_pos = out.len();
905                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
906                end_jumps.push(jump_pos);
907            }
908        }
909
910        let end_pos = out.len();
911
912        // Patch the no-match Branch (when default is not first)
913        if let Some(dbp) = default_branch_pos {
914            let default_target = if default.is_some() {
915                default_body_pos
916            } else {
917                end_pos
918            };
919            out.patch_jump(dbp, default_target);
920        }
921
922        // Build the switch table with body positions
923        let mut table = Vec::new();
924        for (values, pos) in &case_positions {
925            for &v in values {
926                table.push((v, *pos));
927            }
928        }
929
930        // Update the SWITCH instruction with the complete table
931        out.instructions[switch_idx].operand = Operand::SwitchTable(table);
932
933        // Patch end-of-case jumps to end_pos
934        for pos in end_jumps {
935            out.patch_jump(pos, end_pos);
936        }
937    }
938
939    fn compile_expr(&mut self, expr: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
940        self.compile_expr_hinted(expr, out, locals, None);
941    }
942
943    fn compile_expr_hinted(
944        &mut self,
945        expr: &Expr,
946        out: &mut CompiledScript,
947        locals: &mut SymbolTable,
948        type_hint: Option<Type>,
949    ) {
950        match expr {
951            Expr::IntLiteral(n) => {
952                out.push(Instruction::push_int(*n));
953            }
954
955            Expr::LongLiteral(n) => {
956                out.push(Instruction::push_long(*n));
957            }
958
959            Expr::StringLiteral(s) => {
960                if let Some(h) = type_hint
961                    && h.base_type() == BaseVarType::Integer
962                    && h != Type::Int
963                    && h != Type::Boolean
964                {
965                    if let Some(id) = self.registry.lookup_entity_id_typed(s, h) {
966                        out.push(Instruction::push_int(id));
967                        return;
968                    }
969                    if let Some(sym) = self.registry.lookup_entity_id(s)
970                        && let SymbolKind::Constant {
971                            int_value: Some(id),
972                            ..
973                        } = &sym.kind
974                    {
975                        out.push(Instruction::push_int(*id));
976                        return;
977                    }
978                }
979                out.push(Instruction::push_string(s.clone()));
980            }
981
982            Expr::BoolLiteral(b) => {
983                out.push(Instruction::push_int(if *b { 1 } else { 0 }));
984            }
985
986            Expr::NullLiteral => {
987                // For string-typed parameters, null is the string "null".
988                // For all other types, null is integer -1.
989                if matches!(type_hint, Some(Type::String)) {
990                    out.push(Instruction::push_string("null".to_string()));
991                } else {
992                    out.push(Instruction::push_int(-1));
993                }
994            }
995
996            Expr::CharLiteral(c) => {
997                out.push(Instruction::push_int(*c as i32));
998            }
999
1000            Expr::CoordLiteral(c) => {
1001                out.push(Instruction::push_int(*c));
1002            }
1003
1004            Expr::LocalVar(name, _var_line) => {
1005                if let Some(sym) = locals.lookup(name) {
1006                    let (slot, base) = match &sym.kind {
1007                        SymbolKind::LocalVar { var_type, slot, .. } => {
1008                            (*slot, var_type.base_type())
1009                        }
1010                        SymbolKind::ScriptParam { param_type, slot } => {
1011                            (*slot, param_type.base_type())
1012                        }
1013                        _ => (0, BaseVarType::Integer),
1014                    };
1015                    let opcode = match base {
1016                        BaseVarType::Integer => Opcode::PushIntLocal,
1017                        BaseVarType::String => Opcode::PushStringLocal,
1018                        BaseVarType::Long => Opcode::PushLongLocal,
1019                    };
1020                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1021                } else {
1022                    // Variable not found - push 0 as fallback
1023                    out.push(Instruction::push_int(0));
1024                }
1025            }
1026
1027            Expr::GameVar(name, _var_line) => {
1028                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1029                // Encoding: (1 << 16) | var_id in the operand.
1030                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1031                    (stripped, true)
1032                } else {
1033                    (name.as_str(), false)
1034                };
1035                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1036                    && let SymbolKind::GameVar {
1037                        var_id, category, ..
1038                    } = &sym.kind
1039                {
1040                    let opcode = match category.as_str() {
1041                        "varp" => Opcode::PushVarp,
1042                        "varn" => Opcode::PushVarn,
1043                        "vars" => Opcode::PushVars,
1044                        "varbit" => Opcode::PushVarbit,
1045                        _ => Opcode::PushVarp,
1046                    };
1047                    let encoded_id = if secondary {
1048                        (1 << 16) | *var_id
1049                    } else {
1050                        *var_id
1051                    };
1052                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1053                }
1054            }
1055
1056            Expr::ConstantVar(name, const_line) => {
1057                if let Some(sym) = self.registry.lookup_constant(name).cloned()
1058                    && let SymbolKind::Constant {
1059                        int_value,
1060                        string_value,
1061                        ..
1062                    } = &sym.kind
1063                {
1064                    if let Some(v) = int_value {
1065                        out.push(Instruction::push_int(*v));
1066                    } else if let Some(s) = string_value {
1067                        // String constants: emit line - 1 to match Java compiler.
1068                        // The Java type checker resolves ^constant to a StringLiteral
1069                        // with NodeSourceLocation(line - 1, col - 1), converting from
1070                        // 1-based ANTLR lines to a 0-based offset. Integer constants
1071                        // are re-parsed via ANTLR with the offset, so they keep the
1072                        // original line (1 + (line-1) = line).
1073                        if *const_line > 0 {
1074                            Self::emit_line(*const_line - 1, out);
1075                        }
1076                        out.push(Instruction::push_string(s.clone()));
1077                    }
1078                }
1079            }
1080
1081            Expr::Identifier(name) => {
1082                // Component reference: interface_name:component_name → (iface_id << 16) | comp_id
1083                if let Some((iface_name, comp_name)) = name.split_once(':')
1084                    && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
1085                {
1086                    out.push(Instruction::push_int(packed));
1087                    return;
1088                }
1089
1090                // Resolution order: entity IDs (stat/npc/loc/etc.) > constants (.constant)
1091                // > commands > game vars > script IDs > fallback -1.
1092                // This matches Java: plain identifiers use entity IDs, not .constant overrides.
1093                //
1094                // When a type hint is available (propagated from the enclosing command call's
1095                // parameter types), prefer the type-specific entity ID. This handles cases where
1096                // the same name exists in multiple pack files (e.g. `smokepuff` in both synth.pack
1097                // and spotanim.pack) — the correct ID is chosen based on the expected parameter type.
1098                //
1099                // Script reference type hints (proc, label, queue, etc.) bypass entity IDs and
1100                // go directly to trigger-specific script ID lookup.
1101                if let Some(hint) = type_hint {
1102                    let trigger_opt: Option<&'static str> = match hint {
1103                        Type::Proc => Some("proc"),
1104                        Type::Label => Some("label"),
1105                        Type::Queue => Some("queue"),
1106                        Type::SoftTimer => Some("softtimer"),
1107                        Type::Timer => Some("timer"),
1108                        Type::Walktrigger => Some("walktrigger"),
1109                        _ => None,
1110                    };
1111                    if let Some(trigger) = trigger_opt {
1112                        let script_id = self
1113                            .registry
1114                            .script_id_for_trigger(trigger, name)
1115                            .or_else(|| self.registry.proc_script_id(name))
1116                            .or_else(|| self.registry.script_id(name))
1117                            .unwrap_or(-1);
1118                        out.push(Instruction::push_int(script_id));
1119                        return;
1120                    }
1121                    if let Some(id) = self.registry.lookup_entity_id_typed(name, hint) {
1122                        out.push(Instruction::push_int(id));
1123                        return;
1124                    }
1125                }
1126                if let Some(sym) = self.registry.lookup_entity_id(name).cloned()
1127                    && let SymbolKind::Constant {
1128                        const_type,
1129                        int_value,
1130                        string_value,
1131                    } = &sym.kind
1132                {
1133                    // Param entities should NOT shadow type name identifiers unless
1134                    // we have a Param-typed hint. This allows "namedobj" etc. to resolve
1135                    // to their type chars in enum(int, namedobj, ...) contexts.
1136                    let skip_for_type_char = *const_type == Type::Param
1137                        && type_hint != Some(Type::Param)
1138                        && self.registry.type_chars.contains_key(name);
1139                    if !skip_for_type_char {
1140                        if let Some(v) = int_value {
1141                            out.push(Instruction::push_int(*v));
1142                        } else if let Some(s) = string_value {
1143                            out.push(Instruction::push_string(s.clone()));
1144                        }
1145                        // If skip_for_type_char, fall through to commands/type_chars below
1146                        return;
1147                    }
1148                }
1149                if let Some(trigger_byte) = crate::trigger_table::byte(name) {
1150                    out.push(Instruction::push_int(trigger_byte as i32));
1151                    return;
1152                }
1153                if type_hint == Some(Type::Int)
1154                    && let Some(sym) = self
1155                        .registry
1156                        .lookup_command(name.strip_prefix('.').unwrap_or(name))
1157                    && let SymbolKind::Command {
1158                        opcode,
1159                        param_types,
1160                        ..
1161                    } = &sym.kind
1162                    && !param_types.is_empty()
1163                {
1164                    // Bare identifier referring to a command that takes args is
1165                    // used in the test framework as the opcode-as-int literal
1166                    // (e.g. `wait_for(mes, 30)` — `mes` becomes 2064).
1167                    // 0-arg commands (`uid`, `name`, `map_clock`) fall through
1168                    // to the lookup_command branch below which emits a real
1169                    // Command invocation, since calling them with no args is
1170                    // the natural meaning.
1171                    out.push(Instruction::push_int(*opcode));
1172                    return;
1173                }
1174                // Note: we fall through here only if entity lookup found a Param-type entity
1175                // that should be overridden by a type_char, or if entity lookup returned None.
1176                if let Some(sym) = self.registry.lookup_constant(name).cloned() {
1177                    if let SymbolKind::Constant {
1178                        int_value,
1179                        string_value,
1180                        ..
1181                    } = &sym.kind
1182                    {
1183                        if let Some(v) = int_value {
1184                            out.push(Instruction::push_int(*v));
1185                        } else if let Some(s) = string_value {
1186                            out.push(Instruction::push_string(s.clone()));
1187                        }
1188                    }
1189                } else {
1190                    let (lookup, idx) = if let Some(stripped) = name.strip_prefix('.') {
1191                        (stripped, 1u8)
1192                    } else {
1193                        (name.as_str(), 0u8)
1194                    };
1195                    let resolved = if let Some(sym) = self.registry.lookup_command(lookup).cloned()
1196                    {
1197                        if let SymbolKind::Command { opcode, .. } = &sym.kind {
1198                            let encoded = opcode | ((idx as i32) << 16);
1199                            out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1200                        }
1201                        true
1202                    } else {
1203                        false
1204                    };
1205                    if !resolved {
1206                        if let Some(sym) = self.registry.lookup_game_var(name).cloned()
1207                            && let SymbolKind::GameVar {
1208                                var_id, category, ..
1209                            } = &sym.kind
1210                        {
1211                            let push_op = match category.as_str() {
1212                                "varp" => Opcode::PushVarp,
1213                                "varn" => Opcode::PushVarn,
1214                                "vars" => Opcode::PushVars,
1215                                "varbit" => Opcode::PushVarbit,
1216                                _ => Opcode::PushVarp,
1217                            };
1218                            out.push(Instruction::new(push_op, Operand::Int(*var_id)));
1219                        } else if let Some(&type_char) = self.registry.type_chars.get(name) {
1220                            out.push(Instruction::push_int(type_char));
1221                        } else if let Some(script_id) = self
1222                            .registry
1223                            .proc_script_id(name)
1224                            .or_else(|| self.registry.script_id(name))
1225                        {
1226                            out.push(Instruction::push_int(script_id));
1227                        } else {
1228                            out.push(Instruction::push_int(-1));
1229                        }
1230                    }
1231                }
1232            }
1233
1234            Expr::ArrayAccess { name, index } => {
1235                // Push index
1236                self.compile_expr(index, out, locals);
1237
1238                // Push array element
1239                if let Some(sym) = locals.lookup(name) {
1240                    let slot = match &sym.kind {
1241                        SymbolKind::LocalVar { slot, .. } => *slot,
1242                        _ => 0,
1243                    };
1244                    out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(slot)));
1245                }
1246            }
1247
1248            Expr::BinaryOp { op, lhs, rhs } => {
1249                // Handle entity names that contain '+' (e.g. "cheese+tom_batta").
1250                // The parser splits these into BinaryOp::Add, but they should resolve
1251                // as a single entity identifier.
1252                if matches!(op, BinOp::Add)
1253                    && let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1254                        (lhs.as_ref(), rhs.as_ref())
1255                {
1256                    let combined = format!("{}+{}", lhs_name, rhs_name);
1257                    if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
1258                        && let SymbolKind::Constant {
1259                            int_value: Some(id),
1260                            ..
1261                        } = &sym.kind
1262                    {
1263                        out.push(Instruction::push_int(*id));
1264                        return;
1265                    }
1266                }
1267
1268                // For comparisons, infer the type of lhs to use as a hint for rhs.
1269                // This allows e.g. `$struct = blamish_oil` to correctly resolve
1270                // `blamish_oil` from struct.pack rather than a higher-priority pack.
1271                let lhs_type_hint = match op {
1272                    BinOp::Eq
1273                    | BinOp::NotEq
1274                    | BinOp::Lt
1275                    | BinOp::Gt
1276                    | BinOp::LtEq
1277                    | BinOp::GtEq => self.infer_type(lhs, locals),
1278                    _ => None,
1279                };
1280                self.compile_expr(lhs, out, locals);
1281                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
1282
1283                // Determine if this is a long operation based on operand types
1284                // For now, use int operations; type checker can refine
1285                let opcode = match op {
1286                    BinOp::Add => Opcode::Add,
1287                    BinOp::Sub => Opcode::Sub,
1288                    BinOp::Mul => Opcode::Multiply,
1289                    BinOp::Div => Opcode::Divide,
1290                    BinOp::Mod => Opcode::Modulo,
1291                    BinOp::BitAnd => Opcode::And,
1292                    BinOp::BitOr => Opcode::Or,
1293                    BinOp::Eq => {
1294                        Self::emit_comparison_value(Opcode::BranchEquals, 0, 1, out);
1295                        return;
1296                    }
1297                    BinOp::NotEq => {
1298                        Self::emit_comparison_value(Opcode::BranchEquals, 1, 0, out);
1299                        return;
1300                    }
1301                    BinOp::Lt => {
1302                        Self::emit_comparison_value(Opcode::BranchLessThan, 0, 1, out);
1303                        return;
1304                    }
1305                    BinOp::Gt => {
1306                        Self::emit_comparison_value(Opcode::BranchGreaterThan, 0, 1, out);
1307                        return;
1308                    }
1309                    BinOp::LtEq => {
1310                        Self::emit_comparison_value(Opcode::BranchLessThanOrEquals, 0, 1, out);
1311                        return;
1312                    }
1313                    BinOp::GtEq => {
1314                        Self::emit_comparison_value(Opcode::BranchGreaterThanOrEquals, 0, 1, out);
1315                        return;
1316                    }
1317                };
1318                out.push(Instruction::simple(opcode));
1319            }
1320
1321            Expr::LogicalOp { op, lhs, rhs, .. } => {
1322                self.compile_expr(lhs, out, locals);
1323                self.compile_expr(rhs, out, locals);
1324                match op {
1325                    LogicOp::And => out.push(Instruction::simple(Opcode::And)),
1326                    LogicOp::Or => out.push(Instruction::simple(Opcode::Or)),
1327                }
1328            }
1329
1330            Expr::Calc(inner) => {
1331                self.compile_expr(inner, out, locals);
1332            }
1333
1334            Expr::CommandCall {
1335                name,
1336                args,
1337                arg_lines,
1338                call_line,
1339            } => {
1340                // Dot-prefixed commands address the secondary active entity (operand = 1).
1341                let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
1342                    (stripped, 1u8)
1343                } else {
1344                    (name.as_str(), 0u8)
1345                };
1346
1347                // Fetch per-position type hints from the engine command signature.
1348                let param_types: Vec<Type> = self
1349                    .registry
1350                    .command_param_types
1351                    .get(lookup_name)
1352                    .cloned()
1353                    .unwrap_or_default();
1354
1355                // Commands that take a script reference as their first argument and
1356                // variadic extra arguments (described by a type-string pushed after them).
1357                let script_trigger = Self::command_script_trigger(lookup_name);
1358                let variadic_info = Self::command_variadic_info(lookup_name);
1359
1360                // Compile arguments, with special handling for the script-name first arg.
1361                for (i, arg) in args.iter().enumerate() {
1362                    // Emit LineNumber before each arg to track multi-line calls.
1363                    if let Some(&al) = arg_lines.get(i)
1364                        && al > 0
1365                    {
1366                        Self::emit_line(al, out);
1367                    }
1368                    if i == 0
1369                        && let Some(trigger) = script_trigger
1370                    {
1371                        // First arg is a script name identifier: resolve to trigger-specific ID.
1372                        if let Expr::Identifier(script_name) = arg {
1373                            let script_id = self
1374                                .registry
1375                                .script_id_for_trigger(trigger, script_name)
1376                                .or_else(|| self.registry.proc_script_id(script_name))
1377                                .or_else(|| self.registry.script_id(script_name))
1378                                .unwrap_or(-1);
1379                            out.push(Instruction::push_int(script_id));
1380                            continue;
1381                        }
1382                    }
1383                    // For 'enum' command, args 0 and 1 are input/output type chars.
1384                    // Resolve plain identifiers as type chars before falling through to commands.
1385                    if (lookup_name == "enum"
1386                        || lookup_name == "enum2"
1387                        || lookup_name == "db_getfield"
1388                        || lookup_name == "db_find"
1389                        || lookup_name == "db_find_refine"
1390                        || lookup_name == "db_findbyindex"
1391                        || lookup_name == "db_find_with_count"
1392                        || lookup_name == "param")
1393                        && (i == 0 || i == 1)
1394                        && let Expr::Identifier(n) = arg
1395                        && let Some(&tc) = self.registry.type_chars.get(n.as_str())
1396                    {
1397                        out.push(Instruction::push_int(tc));
1398                        continue;
1399                    }
1400                    let hint = param_types.get(i).copied();
1401                    self.compile_expr_hinted(arg, out, locals, hint);
1402                }
1403
1404                // Push the variadic type-descriptor string for commands that support it.
1405                if let Some(fixed_arg_count) = variadic_info {
1406                    let variadic_args = if args.len() > fixed_arg_count {
1407                        &args[fixed_arg_count..]
1408                    } else {
1409                        &[]
1410                    };
1411                    let type_desc: String = variadic_args
1412                        .iter()
1413                        .map(|arg| self.infer_type_char(arg, locals))
1414                        .collect();
1415                    out.push(Instruction::push_string(type_desc));
1416                }
1417
1418                // db_find needs an implicit extra push_int argument: the Java BaseVarType
1419                // ordinal of the column's first field type (INT=0, LONG=1, STRING=2).
1420                if lookup_name == "db_find" || lookup_name == "db_find_refine" {
1421                    let base_type_ordinal = if let Some(Expr::Identifier(col_name)) = args.first() {
1422                        self.registry
1423                            .dbcolumn_types
1424                            .get(col_name.as_str())
1425                            .map(|t| match t.base_type() {
1426                                crate::types::BaseVarType::Integer => 0,
1427                                crate::types::BaseVarType::Long => 1,
1428                                crate::types::BaseVarType::String => 2,
1429                            })
1430                            .unwrap_or(0)
1431                    } else {
1432                        0
1433                    };
1434                    out.push(Instruction::push_int(base_type_ordinal));
1435                }
1436
1437                // Re-emit the call expression's line before the final command instruction.
1438                // The reference compiler does lineInstruction(expr) after visiting args.
1439                if *call_line > 0 {
1440                    Self::emit_line(*call_line, out);
1441                }
1442
1443                // Look up command opcode and emit.
1444                // For variadic variants (name*), also check the "namevararg" form
1445                // used in command.pack.
1446                let cmd_sym = self
1447                    .registry
1448                    .lookup_command(lookup_name)
1449                    .or_else(|| {
1450                        lookup_name.strip_suffix('*').and_then(|base| {
1451                            let vararg_name = format!("{}vararg", base);
1452                            self.registry.lookup_command(&vararg_name)
1453                        })
1454                    })
1455                    .cloned();
1456                if let Some(sym) = cmd_sym {
1457                    if let SymbolKind::Command { opcode, .. } = &sym.kind {
1458                        let encoded = (*opcode) | ((cmd_index as i32) << 16);
1459                        out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1460                    }
1461                } else {
1462                    out.push(Instruction::new(
1463                        Opcode::Command,
1464                        Operand::Str(name.clone()),
1465                    ));
1466                }
1467
1468                // Note: db_find and db_find_refine do NOT push a count value.
1469                // Only db_find_with_count and db_find_refine_with_count push a count.
1470            }
1471
1472            Expr::ProcCall {
1473                name,
1474                args,
1475                arg_lines,
1476                call_line,
1477            } => {
1478                // Get parameter types from target proc for type-aware arg compilation
1479                let param_types: Vec<Type> = self
1480                    .registry
1481                    .lookup_script(name)
1482                    .and_then(|sym| {
1483                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1484                            Some(param_types.clone())
1485                        } else {
1486                            None
1487                        }
1488                    })
1489                    .unwrap_or_default();
1490                for (i, arg) in args.iter().enumerate() {
1491                    if let Some(&al) = arg_lines.get(i)
1492                        && al > 0
1493                    {
1494                        Self::emit_line(al, out);
1495                    }
1496                    let hint = param_types.get(i).copied();
1497                    self.compile_expr_hinted(arg, out, locals, hint);
1498                }
1499
1500                // Re-emit call expression's line before final gosub.
1501                if *call_line > 0 {
1502                    Self::emit_line(*call_line, out);
1503                }
1504
1505                // `~name(...)` resolves ONLY against `[proc,name]` — matching
1506                // RuneScriptTS. A silent fallback to any script with this name
1507                // (debugproc / label / timer) lets `~foo` bind to an unrelated
1508                // trigger; if that trigger's body also calls `~foo`, you get
1509                // infinite recursion at runtime. The type checker emits an
1510                // error diagnostic for unresolved procs, so `-1` here only
1511                // fires in paths that already produced an error.
1512                let script_id = self.registry.proc_script_id(name).unwrap_or(-1);
1513                out.push(Instruction::gosub_with_params(script_id));
1514            }
1515
1516            Expr::JumpCall {
1517                name,
1518                args,
1519                arg_lines,
1520                call_line,
1521            } => {
1522                // Get parameter types from target label for type-aware arg compilation
1523                let param_types: Vec<Type> = self
1524                    .registry
1525                    .lookup_script(name)
1526                    .and_then(|sym| {
1527                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1528                            Some(param_types.clone())
1529                        } else {
1530                            None
1531                        }
1532                    })
1533                    .unwrap_or_default();
1534                for (i, arg) in args.iter().enumerate() {
1535                    if let Some(&al) = arg_lines.get(i)
1536                        && al > 0
1537                    {
1538                        Self::emit_line(al, out);
1539                    }
1540                    let hint = param_types.get(i).copied();
1541                    self.compile_expr_hinted(arg, out, locals, hint);
1542                }
1543                // Re-emit call expression's line before final jump.
1544                if *call_line > 0 {
1545                    Self::emit_line(*call_line, out);
1546                }
1547
1548                let script_id = self
1549                    .registry
1550                    .label_script_id(name)
1551                    .or_else(|| self.registry.script_id(name))
1552                    .unwrap_or(-1);
1553                out.push(Instruction::new(
1554                    Opcode::JumpWithParams,
1555                    Operand::Int(script_id),
1556                ));
1557            }
1558
1559            Expr::JoinedString { parts } => {
1560                let mut count = 0u32;
1561                for part in parts {
1562                    match part {
1563                        StringPart::Literal(s) => {
1564                            out.push(Instruction::push_string(s.clone()));
1565                            count += 1;
1566                        }
1567                        StringPart::Expr(e) => {
1568                            self.compile_expr(e, out, locals);
1569                            count += 1;
1570                        }
1571                    }
1572                }
1573                out.push(Instruction::join_string(count));
1574            }
1575
1576            Expr::MultiAssign(..) => {
1577                // Multi-assign targets handled at statement level; no-op as expression
1578            }
1579        }
1580    }
1581
1582    fn compile_store(&mut self, target: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
1583        match target {
1584            Expr::LocalVar(name, _var_line) => {
1585                if let Some(sym) = locals.lookup(name) {
1586                    let (slot, base) = match &sym.kind {
1587                        SymbolKind::LocalVar { var_type, slot, .. } => {
1588                            (*slot, var_type.base_type())
1589                        }
1590                        SymbolKind::ScriptParam { param_type, slot } => {
1591                            (*slot, param_type.base_type())
1592                        }
1593                        _ => (0, BaseVarType::Integer),
1594                    };
1595                    let opcode = match base {
1596                        BaseVarType::Integer => Opcode::PopIntLocal,
1597                        BaseVarType::String => Opcode::PopStringLocal,
1598                        BaseVarType::Long => Opcode::PopLongLocal,
1599                    };
1600                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1601                }
1602            }
1603
1604            Expr::GameVar(name, _var_line) => {
1605                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1606                // Encoding: (1 << 16) | var_id in the operand.
1607                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1608                    (stripped, true)
1609                } else {
1610                    (name.as_str(), false)
1611                };
1612                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1613                    && let SymbolKind::GameVar {
1614                        var_id, category, ..
1615                    } = &sym.kind
1616                {
1617                    let opcode = match category.as_str() {
1618                        "varp" => Opcode::PopVarp,
1619                        "varn" => Opcode::PopVarn,
1620                        "vars" => Opcode::PopVars,
1621                        "varbit" => Opcode::PopVarbit,
1622                        _ => Opcode::PopVarp,
1623                    };
1624                    let encoded_id = if secondary {
1625                        (1 << 16) | *var_id
1626                    } else {
1627                        *var_id
1628                    };
1629                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1630                }
1631            }
1632
1633            Expr::ArrayAccess { name, index } => {
1634                // For array store: push index, then value is already on stack
1635                self.compile_expr(index, out, locals);
1636                if let Some(sym) = locals.lookup(name) {
1637                    let slot = match &sym.kind {
1638                        SymbolKind::LocalVar { slot, .. } => *slot,
1639                        _ => 0,
1640                    };
1641                    out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
1642                }
1643            }
1644
1645            Expr::MultiAssign(targets, target_lines) => {
1646                // Multi-return: pop return values in reverse order (last target = top of stack)
1647                for (i, target) in targets.iter().enumerate().rev() {
1648                    // Emit LineNumber for each target's source line
1649                    if let Some(&tl) = target_lines.get(i)
1650                        && tl > 0
1651                    {
1652                        Self::emit_line(tl, out);
1653                    }
1654                    self.compile_store(target, out, locals);
1655                }
1656            }
1657
1658            _ => {
1659                // Invalid store target - should be caught by type checker
1660            }
1661        }
1662    }
1663
1664    /// Returns the trigger type for commands whose first argument is a script name.
1665    fn command_script_trigger(cmd_name: &str) -> Option<&'static str> {
1666        match cmd_name {
1667            "queue" | "queue*" | "longqueue" | "longqueue*" | "strongqueue" | "strongqueue*"
1668            | "weakqueue" | "weakqueue*" | "clearqueue" => Some("queue"),
1669            "softtimer" | "softtimer*" => Some("softtimer"),
1670            "settimer" | "settimer*" | "cleartimer" => Some("timer"),
1671            "walktrigger" => Some("walktrigger"),
1672            _ => None,
1673        }
1674    }
1675
1676    /// Number of fixed (non-variadic) arguments for commands that push a type descriptor.
1677    /// Returns None for commands that don't use a type descriptor at all.
1678    fn command_variadic_info(cmd_name: &str) -> Option<usize> {
1679        match cmd_name {
1680            // queue/strongqueue/weakqueue have separate * variants (different opcodes)
1681            "queue*" | "strongqueue*" | "weakqueue*" => Some(2),
1682            "longqueue*" => Some(3),
1683            // settimer/softtimer are always variadic (no separate * variant)
1684            "settimer" | "softtimer" => Some(2),
1685            // runclientscript* has 1 fixed arg (script_id) + variadic params
1686            "runclientscript*" => Some(1),
1687            _ => None,
1688        }
1689    }
1690
1691    /// Infer the RS2 type character for an expression (used for variadic type descriptors).
1692    fn infer_type_char(&self, expr: &Expr, locals: &SymbolTable) -> char {
1693        match expr {
1694            Expr::StringLiteral(_) | Expr::JoinedString { .. } => 's',
1695            Expr::LongLiteral(_) => 'l',
1696            Expr::IntLiteral(_)
1697            | Expr::BoolLiteral(_)
1698            | Expr::CoordLiteral(_)
1699            | Expr::CharLiteral(_) => 'i',
1700            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1701                if let Some(sym) = locals.lookup(name) {
1702                    match &sym.kind {
1703                        SymbolKind::LocalVar { var_type, .. } => self.type_to_type_char(*var_type),
1704                        SymbolKind::ScriptParam { param_type, .. } => {
1705                            self.type_to_type_char(*param_type)
1706                        }
1707                        _ => 'i',
1708                    }
1709                } else {
1710                    'i'
1711                }
1712            }
1713            Expr::GameVar(name, _var_line) => {
1714                if let Some(sym) = self.registry.lookup_game_var(name)
1715                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1716                {
1717                    return self.type_to_type_char(*var_type);
1718                }
1719                'i'
1720            }
1721            Expr::CommandCall { name, .. } => {
1722                let lookup = name.trim_start_matches('.');
1723                if let Some(sym) = self.registry.lookup_command(lookup)
1724                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1725                    && let Some(rt) = return_types.first()
1726                {
1727                    return self.type_to_type_char(*rt);
1728                }
1729                // Unknown or void command - check known command types
1730                Self::known_command_type_char(lookup)
1731            }
1732            Expr::ProcCall { name, .. } => {
1733                if let Some(sym) = self.registry.lookup_script(name)
1734                    && let SymbolKind::Script { return_types, .. } = &sym.kind
1735                    && let Some(rt) = return_types.first()
1736                {
1737                    return self.type_to_type_char(*rt);
1738                }
1739                'i'
1740            }
1741            Expr::Identifier(name) => {
1742                // Bare identifier (no parens) - might be a zero-arg command like `uid`
1743                let lookup = name.trim_start_matches('.');
1744                if let Some(sym) = self.registry.lookup_command(lookup)
1745                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1746                    && let Some(rt) = return_types.first()
1747                {
1748                    return self.type_to_type_char(*rt);
1749                }
1750                Self::known_command_type_char(lookup)
1751            }
1752            Expr::ConstantVar(name, _) => {
1753                if let Some(sym) = self.registry.lookup_constant(name)
1754                    && let SymbolKind::Constant { const_type, .. } = &sym.kind
1755                {
1756                    return self.type_to_type_char(*const_type);
1757                }
1758                'i'
1759            }
1760            Expr::BinaryOp { .. } | Expr::Calc(_) => 'i',
1761            Expr::NullLiteral => 'i',
1762            _ => 'i',
1763        }
1764    }
1765
1766    /// Infer the type of an assignment target (lvalue) for type-hinted value compilation.
1767    fn infer_target_type(&self, target: &Expr, locals: &SymbolTable) -> Option<Type> {
1768        match target {
1769            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1770                if let Some(sym) = locals.lookup(name) {
1771                    match &sym.kind {
1772                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1773                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1774                        _ => None,
1775                    }
1776                } else {
1777                    None
1778                }
1779            }
1780            Expr::GameVar(name, _var_line) => {
1781                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1782                    stripped
1783                } else {
1784                    name.as_str()
1785                };
1786                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1787                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1788                {
1789                    return Some(*var_type);
1790                }
1791                None
1792            }
1793            _ => None,
1794        }
1795    }
1796
1797    /// Infer the `Type` of an expression for use as a comparison type hint.
1798    fn infer_type(&self, expr: &Expr, locals: &SymbolTable) -> Option<Type> {
1799        match expr {
1800            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1801                if let Some(sym) = locals.lookup(name) {
1802                    match &sym.kind {
1803                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1804                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1805                        _ => None,
1806                    }
1807                } else {
1808                    None
1809                }
1810            }
1811            Expr::GameVar(name, _var_line) => {
1812                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1813                    stripped
1814                } else {
1815                    name.as_str()
1816                };
1817                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1818                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1819                {
1820                    return Some(*var_type);
1821                }
1822                None
1823            }
1824            Expr::CommandCall { name, .. } => {
1825                let lookup = name.trim_start_matches('.');
1826                if let Some(sym) = self.registry.lookup_command(lookup)
1827                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1828                {
1829                    return return_types.first().copied();
1830                }
1831                None
1832            }
1833            Expr::Identifier(name) => {
1834                // Zero-arg commands used without parens (e.g. `loc_category`)
1835                let lookup = name.trim_start_matches('.');
1836                if let Some(sym) = self.registry.lookup_command(lookup)
1837                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1838                {
1839                    return return_types.first().copied();
1840                }
1841                None
1842            }
1843            _ => None,
1844        }
1845    }
1846
1847    fn type_to_type_char(&self, t: Type) -> char {
1848        match t.base_type() {
1849            BaseVarType::String => 's',
1850            BaseVarType::Long => 'l',
1851            BaseVarType::Integer => {
1852                // Use the type_chars map for more precise type chars
1853                // (e.g., namedobj='O', playeruid='p')
1854                for (name, &tc) in &self.registry.type_chars {
1855                    if let Some(from_type) = Type::from_name(name)
1856                        && from_type == t
1857                    {
1858                        return (tc as u8) as char;
1859                    }
1860                }
1861                'i'
1862            }
1863        }
1864    }
1865
1866    fn known_command_type_char(name: &str) -> char {
1867        // Commands whose return type is not in the sym file but is known
1868        match name {
1869            "uid" => 'p',     // PlayerUid
1870            "npc_uid" => 'u', // NpcUid
1871            "displayname" | "name" | "npc_name" | "oc_name" | "oc_cert" => 's',
1872            _ => 'i',
1873        }
1874    }
1875
1876    /// Returns `Some(error message)` if `[trigger,entity_name]` resolved a
1877    /// trigger byte but failed to resolve `entity_name` to a real subject,
1878    /// which would silently produce an unreachable script (lookup_key = -1).
1879    /// Returns `None` for legitimate cases:
1880    ///   - bare `_` wildcard (global trigger, no subject)
1881    ///   - `_category` form (category lookup — caller validates separately)
1882    ///   - coord-shaped triggers (`zone`, `zoneexit`, `mapzone`, `mapzoneexit`)
1883    ///   - name-keyed triggers (`queue`, `timer`, `walktrigger`, `proc`, `label`, …)
1884    pub fn validate_trigger_subject(
1885        trigger: &str,
1886        entity_name: &str,
1887        registry: &SymbolRegistry,
1888    ) -> Option<String> {
1889        if entity_name.is_empty() || entity_name == "_" {
1890            return None;
1891        }
1892        // Category subjects are validated by their own path; skip.
1893        if entity_name.starts_with('_') {
1894            return None;
1895        }
1896        // Triggers whose subject is a coord, has no subject at all, or is
1897        // historically not validated (ai_queue/ai_timer) — see trigger_table.
1898        if !crate::trigger_table::validates_subject(trigger) {
1899            return None;
1900        }
1901        let key = Self::compute_lookup_key(trigger, entity_name, registry);
1902        if key == -1 {
1903            let hint = if entity_name.contains(':') {
1904                let (iface, comp) = entity_name.split_once(':').unwrap();
1905                format!(
1906                    "interface:component subject — check interface.pack for either an if3 entry \
1907                     `<iface_id>:<comp_id>=<comp_name>` (with iface_id matching `{iface}`) \
1908                     or an if1 entry `<flat_id>={iface}:{comp}`"
1909                )
1910            } else {
1911                "Likely a typo or missing pack entry (check interface.pack / npc.pack / obj.pack / loc.pack)".to_string()
1912            };
1913            return Some(format!(
1914                "[{trigger},{entity_name}] — subject `{entity_name}` did not resolve to an entity. \
1915                 {hint}. Script will compile but never dispatch."
1916            ));
1917        }
1918        None
1919    }
1920
1921    /// Compute the CS2 Neptune lookup key for a script.
1922    /// Formula: `entity_id * 1024 + 512 + trigger_byte`, or -1 if not applicable.
1923    /// For global scripts (entity="_"), returns just `trigger_byte`.
1924    pub fn compute_lookup_key(trigger: &str, entity_name: &str, registry: &SymbolRegistry) -> i32 {
1925        // Trigger byte from the central trigger_table. Unknown triggers
1926        // (queue, softtimer, timer, walktrigger, proc, label, command,
1927        // clientscript, debugproc) are name-keyed and have no byte.
1928        let trigger_byte = match crate::trigger_table::byte(trigger) {
1929            Some(b) => b as i64,
1930            None => return -1,
1931        };
1932
1933        // Global scripts with no specific entity return just the trigger byte
1934        if entity_name == "_" {
1935            return trigger_byte as i32;
1936        }
1937
1938        // Coordinate-based triggers: parse "level_bx_by" format
1939        if matches!(trigger, "mapzone" | "mapzoneexit") {
1940            let parts: Vec<&str> = entity_name.splitn(4, '_').collect();
1941            if parts.len() >= 3
1942                && let (Ok(bx), Ok(by)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>())
1943            {
1944                let entity_id: i64 = ((bx & 3) << 20) | (by << 6);
1945                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1946            }
1947            return -1;
1948        }
1949
1950        // Coordinate-based triggers: parse "level_bx_by_lx_lz" format
1951        if matches!(trigger, "zone" | "zoneexit") {
1952            let parts: Vec<&str> = entity_name.splitn(6, '_').collect();
1953            if parts.len() >= 5
1954                && let (Ok(bx), Ok(by), Ok(lx), Ok(lz)) = (
1955                    parts[1].parse::<i64>(),
1956                    parts[2].parse::<i64>(),
1957                    parts[3].parse::<i64>(),
1958                    parts[4].parse::<i64>(),
1959                )
1960            {
1961                let entity_id: i64 = ((bx & 3) << 20) | (by << 6) | (lx << 14) | lz;
1962                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1963            }
1964            return -1;
1965        }
1966
1967        // Category-based entities: entity names starting with '_' reference a category
1968        // (e.g. [opheldu,_alcoholic_drinks] → category "alcoholic_drinks").
1969        // These use offset 256 instead of 512 in the lookupKey formula.
1970        //
1971        // NOTE: the bare `_` (pure wildcard) case is handled earlier in
1972        // this function (entity_name == "_" → returns just trigger_byte).
1973        if let Some(cat_name) = entity_name.strip_prefix('_') {
1974            if let Some(sym) = registry.lookup_entity_id_typed(cat_name, Type::Category) {
1975                return (sym as i64 * 1024 + 256 + trigger_byte) as i32;
1976            }
1977            return -1;
1978        }
1979
1980        // Component subject in `interface:component` form (e.g. `options:com_14`).
1981        // The subject is the packed `(iface_id << 16) | comp_id` registered by
1982        // symloader's `registry.components` map. Used by if_button / inv_button
1983        // triggers — their dispatch hashes iface+comp into 32 bits.
1984        if let Some((iface_name, comp_name)) = entity_name.split_once(':') {
1985            if let Some(packed) = registry.lookup_component(iface_name, comp_name) {
1986                return (packed as i64 * 1024 + 512 + trigger_byte) as i32;
1987            }
1988            return -1;
1989        }
1990
1991        // Type-aware entity lookup so that e.g. "potato" resolves to loc_id
1992        // for [oploc2,potato] rather than the obj_id that has higher flat
1993        // priority. Trigger → entity-type routing lives in trigger_table.
1994        if let Some(entity_type) = crate::trigger_table::subject_type(trigger)
1995            && let Some(entity_id) = registry.lookup_entity_id_typed(entity_name, entity_type)
1996        {
1997            return (entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
1998        }
1999
2000        // Fallback: flat entity_ids lookup
2001        if let Some(sym) = registry.lookup_entity_id(entity_name)
2002            && let crate::symbol::SymbolKind::Constant {
2003                int_value: Some(entity_id),
2004                ..
2005            } = &sym.kind
2006        {
2007            return (*entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2008        }
2009        -1
2010    }
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015    use super::*;
2016    use crate::types::Type;
2017
2018    /// Build a registry seeded with a few entities and one interface+component
2019    /// pair, mimicking the shape symloader produces from interface.pack /
2020    /// npc.pack / obj.pack.
2021    fn seed_registry() -> SymbolRegistry {
2022        let mut r = SymbolRegistry::new();
2023        // Interface 261 = "options", with component 14 = "com_14".
2024        // Key uses normalized form (com14) matching what symloader produces.
2025        r.register_entity_id("options".into(), Type::Interface, 261);
2026        r.register_entity_id("com14".into(), Type::Component, 14);
2027        r.components
2028            .insert("options:com14".into(), (261 << 16) | 14);
2029        // An npc + obj entity for non-interface trigger tests.
2030        r.register_entity_id("man".into(), Type::Npc, 1);
2031        r.register_entity_id("bronze_axe".into(), Type::Obj, 1351);
2032        r
2033    }
2034
2035    #[test]
2036    fn if_button_resolves_interface_component_form() {
2037        let r = seed_registry();
2038        let key = Compiler::compute_lookup_key("if_button", "options:com_14", &r);
2039        let expected = ((261i64 << 16 | 14) * 1024 + 512 + 147) as i32;
2040        assert_eq!(key, expected);
2041        // And the lookup-key wraps to match the engine's
2042        // ServerTriggerType::IfButton::lookup_key_subject(com_hash) where
2043        // com_hash = iface*65536 + comp.
2044        let com_hash = (261i64 << 16 | 14) as i32;
2045        let engine_key = (com_hash as i64 * 1024 + 512 + 147) as i32;
2046        assert_eq!(key, engine_key);
2047    }
2048
2049    #[test]
2050    fn validate_warns_on_unresolved_if_button_subject() {
2051        let r = seed_registry();
2052        // Unknown component name — old bug shape (would silently never dispatch).
2053        let warning =
2054            Compiler::validate_trigger_subject("if_button", "options:com_does_not_exist", &r);
2055        assert!(
2056            warning.is_some(),
2057            "expected a warning for unresolved subject"
2058        );
2059        assert!(warning.unwrap().contains("did not resolve"));
2060    }
2061
2062    #[test]
2063    fn validate_silent_on_resolvable_subject() {
2064        let r = seed_registry();
2065        assert!(Compiler::validate_trigger_subject("if_button", "options:com_14", &r).is_none());
2066        assert!(Compiler::validate_trigger_subject("opnpc1", "man", &r).is_none());
2067        assert!(Compiler::validate_trigger_subject("opheld1", "bronze_axe", &r).is_none());
2068    }
2069
2070    #[test]
2071    fn validate_silent_on_wildcards_and_categories() {
2072        let r = seed_registry();
2073        // Bare `_` — global trigger, no subject.
2074        assert!(Compiler::validate_trigger_subject("opheld1", "_", &r).is_none());
2075        // `_category` form — caller validates separately.
2076        assert!(Compiler::validate_trigger_subject("opheldu", "_alcoholic_drinks", &r).is_none());
2077    }
2078
2079    #[test]
2080    fn validate_silent_on_name_keyed_triggers() {
2081        let r = seed_registry();
2082        // queue/timer/walktrigger/proc are name-keyed; `lookup_key = -1` is correct.
2083        assert!(Compiler::validate_trigger_subject("queue", "my_queue", &r).is_none());
2084        assert!(Compiler::validate_trigger_subject("timer", "my_timer", &r).is_none());
2085        assert!(Compiler::validate_trigger_subject("proc", "my_proc", &r).is_none());
2086    }
2087
2088    #[test]
2089    fn validate_silent_on_coord_triggers() {
2090        let r = seed_registry();
2091        // Coord-shaped names are parsed from the entity string itself.
2092        assert!(Compiler::validate_trigger_subject("zone", "0_50_50_10_10", &r).is_none());
2093    }
2094
2095    #[test]
2096    fn validate_warns_on_unknown_npc_subject() {
2097        let r = seed_registry();
2098        let warning = Compiler::validate_trigger_subject("opnpc1", "not_a_real_npc", &r);
2099        assert!(warning.is_some());
2100    }
2101}