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                // Note: we fall through here only if entity lookup found a Param-type entity
1150                // that should be overridden by a type_char, or if entity lookup returned None.
1151                if let Some(sym) = self.registry.lookup_constant(name).cloned() {
1152                    if let SymbolKind::Constant {
1153                        int_value,
1154                        string_value,
1155                        ..
1156                    } = &sym.kind
1157                    {
1158                        if let Some(v) = int_value {
1159                            out.push(Instruction::push_int(*v));
1160                        } else if let Some(s) = string_value {
1161                            out.push(Instruction::push_string(s.clone()));
1162                        }
1163                    }
1164                } else {
1165                    let (lookup, idx) = if let Some(stripped) = name.strip_prefix('.') {
1166                        (stripped, 1u8)
1167                    } else {
1168                        (name.as_str(), 0u8)
1169                    };
1170                    let resolved = if let Some(sym) = self.registry.lookup_command(lookup).cloned()
1171                    {
1172                        if let SymbolKind::Command { opcode, .. } = &sym.kind {
1173                            let encoded = opcode | ((idx as i32) << 16);
1174                            out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1175                        }
1176                        true
1177                    } else {
1178                        false
1179                    };
1180                    if !resolved {
1181                        if let Some(sym) = self.registry.lookup_game_var(name).cloned()
1182                            && let SymbolKind::GameVar {
1183                                var_id, category, ..
1184                            } = &sym.kind
1185                        {
1186                            let push_op = match category.as_str() {
1187                                "varp" => Opcode::PushVarp,
1188                                "varn" => Opcode::PushVarn,
1189                                "vars" => Opcode::PushVars,
1190                                "varbit" => Opcode::PushVarbit,
1191                                _ => Opcode::PushVarp,
1192                            };
1193                            out.push(Instruction::new(push_op, Operand::Int(*var_id)));
1194                        } else if let Some(&type_char) = self.registry.type_chars.get(name) {
1195                            out.push(Instruction::push_int(type_char));
1196                        } else if let Some(script_id) = self
1197                            .registry
1198                            .proc_script_id(name)
1199                            .or_else(|| self.registry.script_id(name))
1200                        {
1201                            out.push(Instruction::push_int(script_id));
1202                        } else {
1203                            out.push(Instruction::push_int(-1));
1204                        }
1205                    }
1206                }
1207            }
1208
1209            Expr::ArrayAccess { name, index } => {
1210                // Push index
1211                self.compile_expr(index, out, locals);
1212
1213                // Push array element
1214                if let Some(sym) = locals.lookup(name) {
1215                    let slot = match &sym.kind {
1216                        SymbolKind::LocalVar { slot, .. } => *slot,
1217                        _ => 0,
1218                    };
1219                    out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(slot)));
1220                }
1221            }
1222
1223            Expr::BinaryOp { op, lhs, rhs } => {
1224                // Handle entity names that contain '+' (e.g. "cheese+tom_batta").
1225                // The parser splits these into BinaryOp::Add, but they should resolve
1226                // as a single entity identifier.
1227                if matches!(op, BinOp::Add)
1228                    && let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1229                        (lhs.as_ref(), rhs.as_ref())
1230                {
1231                    let combined = format!("{}+{}", lhs_name, rhs_name);
1232                    if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
1233                        && let SymbolKind::Constant {
1234                            int_value: Some(id),
1235                            ..
1236                        } = &sym.kind
1237                    {
1238                        out.push(Instruction::push_int(*id));
1239                        return;
1240                    }
1241                }
1242
1243                // For comparisons, infer the type of lhs to use as a hint for rhs.
1244                // This allows e.g. `$struct = blamish_oil` to correctly resolve
1245                // `blamish_oil` from struct.pack rather than a higher-priority pack.
1246                let lhs_type_hint = match op {
1247                    BinOp::Eq
1248                    | BinOp::NotEq
1249                    | BinOp::Lt
1250                    | BinOp::Gt
1251                    | BinOp::LtEq
1252                    | BinOp::GtEq => self.infer_type(lhs, locals),
1253                    _ => None,
1254                };
1255                self.compile_expr(lhs, out, locals);
1256                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
1257
1258                // Determine if this is a long operation based on operand types
1259                // For now, use int operations; type checker can refine
1260                let opcode = match op {
1261                    BinOp::Add => Opcode::Add,
1262                    BinOp::Sub => Opcode::Sub,
1263                    BinOp::Mul => Opcode::Multiply,
1264                    BinOp::Div => Opcode::Divide,
1265                    BinOp::Mod => Opcode::Modulo,
1266                    BinOp::BitAnd => Opcode::And,
1267                    BinOp::BitOr => Opcode::Or,
1268                    BinOp::Eq => {
1269                        Self::emit_comparison_value(Opcode::BranchEquals, 0, 1, out);
1270                        return;
1271                    }
1272                    BinOp::NotEq => {
1273                        Self::emit_comparison_value(Opcode::BranchEquals, 1, 0, out);
1274                        return;
1275                    }
1276                    BinOp::Lt => {
1277                        Self::emit_comparison_value(Opcode::BranchLessThan, 0, 1, out);
1278                        return;
1279                    }
1280                    BinOp::Gt => {
1281                        Self::emit_comparison_value(Opcode::BranchGreaterThan, 0, 1, out);
1282                        return;
1283                    }
1284                    BinOp::LtEq => {
1285                        Self::emit_comparison_value(Opcode::BranchLessThanOrEquals, 0, 1, out);
1286                        return;
1287                    }
1288                    BinOp::GtEq => {
1289                        Self::emit_comparison_value(Opcode::BranchGreaterThanOrEquals, 0, 1, out);
1290                        return;
1291                    }
1292                };
1293                out.push(Instruction::simple(opcode));
1294            }
1295
1296            Expr::LogicalOp { op, lhs, rhs, .. } => {
1297                self.compile_expr(lhs, out, locals);
1298                self.compile_expr(rhs, out, locals);
1299                match op {
1300                    LogicOp::And => out.push(Instruction::simple(Opcode::And)),
1301                    LogicOp::Or => out.push(Instruction::simple(Opcode::Or)),
1302                }
1303            }
1304
1305            Expr::Calc(inner) => {
1306                self.compile_expr(inner, out, locals);
1307            }
1308
1309            Expr::CommandCall {
1310                name,
1311                args,
1312                arg_lines,
1313                call_line,
1314            } => {
1315                // Dot-prefixed commands address the secondary active entity (operand = 1).
1316                let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
1317                    (stripped, 1u8)
1318                } else {
1319                    (name.as_str(), 0u8)
1320                };
1321
1322                // Fetch per-position type hints from the engine command signature.
1323                let param_types: Vec<Type> = self
1324                    .registry
1325                    .command_param_types
1326                    .get(lookup_name)
1327                    .cloned()
1328                    .unwrap_or_default();
1329
1330                // Commands that take a script reference as their first argument and
1331                // variadic extra arguments (described by a type-string pushed after them).
1332                let script_trigger = Self::command_script_trigger(lookup_name);
1333                let variadic_info = Self::command_variadic_info(lookup_name);
1334
1335                // Compile arguments, with special handling for the script-name first arg.
1336                for (i, arg) in args.iter().enumerate() {
1337                    // Emit LineNumber before each arg to track multi-line calls.
1338                    if let Some(&al) = arg_lines.get(i)
1339                        && al > 0
1340                    {
1341                        Self::emit_line(al, out);
1342                    }
1343                    if i == 0
1344                        && let Some(trigger) = script_trigger
1345                    {
1346                        // First arg is a script name identifier: resolve to trigger-specific ID.
1347                        if let Expr::Identifier(script_name) = arg {
1348                            let script_id = self
1349                                .registry
1350                                .script_id_for_trigger(trigger, script_name)
1351                                .or_else(|| self.registry.proc_script_id(script_name))
1352                                .or_else(|| self.registry.script_id(script_name))
1353                                .unwrap_or(-1);
1354                            out.push(Instruction::push_int(script_id));
1355                            continue;
1356                        }
1357                    }
1358                    // For 'enum' command, args 0 and 1 are input/output type chars.
1359                    // Resolve plain identifiers as type chars before falling through to commands.
1360                    if (lookup_name == "enum"
1361                        || lookup_name == "enum2"
1362                        || lookup_name == "db_getfield"
1363                        || lookup_name == "db_find"
1364                        || lookup_name == "db_find_refine"
1365                        || lookup_name == "db_findbyindex"
1366                        || lookup_name == "db_find_with_count"
1367                        || lookup_name == "param")
1368                        && (i == 0 || i == 1)
1369                        && let Expr::Identifier(n) = arg
1370                        && let Some(&tc) = self.registry.type_chars.get(n.as_str())
1371                    {
1372                        out.push(Instruction::push_int(tc));
1373                        continue;
1374                    }
1375                    let hint = param_types.get(i).copied();
1376                    self.compile_expr_hinted(arg, out, locals, hint);
1377                }
1378
1379                // Push the variadic type-descriptor string for commands that support it.
1380                if let Some(fixed_arg_count) = variadic_info {
1381                    let variadic_args = if args.len() > fixed_arg_count {
1382                        &args[fixed_arg_count..]
1383                    } else {
1384                        &[]
1385                    };
1386                    let type_desc: String = variadic_args
1387                        .iter()
1388                        .map(|arg| self.infer_type_char(arg, locals))
1389                        .collect();
1390                    out.push(Instruction::push_string(type_desc));
1391                }
1392
1393                // db_find needs an implicit extra push_int argument: the Java BaseVarType
1394                // ordinal of the column's first field type (INT=0, LONG=1, STRING=2).
1395                if lookup_name == "db_find" || lookup_name == "db_find_refine" {
1396                    let base_type_ordinal = if let Some(Expr::Identifier(col_name)) = args.first() {
1397                        self.registry
1398                            .dbcolumn_types
1399                            .get(col_name.as_str())
1400                            .map(|t| match t.base_type() {
1401                                crate::types::BaseVarType::Integer => 0,
1402                                crate::types::BaseVarType::Long => 1,
1403                                crate::types::BaseVarType::String => 2,
1404                            })
1405                            .unwrap_or(0)
1406                    } else {
1407                        0
1408                    };
1409                    out.push(Instruction::push_int(base_type_ordinal));
1410                }
1411
1412                // Re-emit the call expression's line before the final command instruction.
1413                // The reference compiler does lineInstruction(expr) after visiting args.
1414                if *call_line > 0 {
1415                    Self::emit_line(*call_line, out);
1416                }
1417
1418                // Look up command opcode and emit.
1419                // For variadic variants (name*), also check the "namevararg" form
1420                // used in command.pack.
1421                let cmd_sym = self
1422                    .registry
1423                    .lookup_command(lookup_name)
1424                    .or_else(|| {
1425                        lookup_name.strip_suffix('*').and_then(|base| {
1426                            let vararg_name = format!("{}vararg", base);
1427                            self.registry.lookup_command(&vararg_name)
1428                        })
1429                    })
1430                    .cloned();
1431                if let Some(sym) = cmd_sym {
1432                    if let SymbolKind::Command { opcode, .. } = &sym.kind {
1433                        let encoded = (*opcode) | ((cmd_index as i32) << 16);
1434                        out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1435                    }
1436                } else {
1437                    out.push(Instruction::new(
1438                        Opcode::Command,
1439                        Operand::Str(name.clone()),
1440                    ));
1441                }
1442
1443                // Note: db_find and db_find_refine do NOT push a count value.
1444                // Only db_find_with_count and db_find_refine_with_count push a count.
1445            }
1446
1447            Expr::ProcCall {
1448                name,
1449                args,
1450                arg_lines,
1451                call_line,
1452            } => {
1453                // Get parameter types from target proc for type-aware arg compilation
1454                let param_types: Vec<Type> = self
1455                    .registry
1456                    .lookup_script(name)
1457                    .and_then(|sym| {
1458                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1459                            Some(param_types.clone())
1460                        } else {
1461                            None
1462                        }
1463                    })
1464                    .unwrap_or_default();
1465                for (i, arg) in args.iter().enumerate() {
1466                    if let Some(&al) = arg_lines.get(i)
1467                        && al > 0
1468                    {
1469                        Self::emit_line(al, out);
1470                    }
1471                    let hint = param_types.get(i).copied();
1472                    self.compile_expr_hinted(arg, out, locals, hint);
1473                }
1474
1475                // Re-emit call expression's line before final gosub.
1476                if *call_line > 0 {
1477                    Self::emit_line(*call_line, out);
1478                }
1479
1480                // `~name(...)` resolves ONLY against `[proc,name]` — matching
1481                // RuneScriptTS. A silent fallback to any script with this name
1482                // (debugproc / label / timer) lets `~foo` bind to an unrelated
1483                // trigger; if that trigger's body also calls `~foo`, you get
1484                // infinite recursion at runtime. The type checker emits an
1485                // error diagnostic for unresolved procs, so `-1` here only
1486                // fires in paths that already produced an error.
1487                let script_id = self.registry.proc_script_id(name).unwrap_or(-1);
1488                out.push(Instruction::gosub_with_params(script_id));
1489            }
1490
1491            Expr::JumpCall {
1492                name,
1493                args,
1494                arg_lines,
1495                call_line,
1496            } => {
1497                // Get parameter types from target label for type-aware arg compilation
1498                let param_types: Vec<Type> = self
1499                    .registry
1500                    .lookup_script(name)
1501                    .and_then(|sym| {
1502                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1503                            Some(param_types.clone())
1504                        } else {
1505                            None
1506                        }
1507                    })
1508                    .unwrap_or_default();
1509                for (i, arg) in args.iter().enumerate() {
1510                    if let Some(&al) = arg_lines.get(i)
1511                        && al > 0
1512                    {
1513                        Self::emit_line(al, out);
1514                    }
1515                    let hint = param_types.get(i).copied();
1516                    self.compile_expr_hinted(arg, out, locals, hint);
1517                }
1518                // Re-emit call expression's line before final jump.
1519                if *call_line > 0 {
1520                    Self::emit_line(*call_line, out);
1521                }
1522
1523                let script_id = self
1524                    .registry
1525                    .label_script_id(name)
1526                    .or_else(|| self.registry.script_id(name))
1527                    .unwrap_or(-1);
1528                out.push(Instruction::new(
1529                    Opcode::JumpWithParams,
1530                    Operand::Int(script_id),
1531                ));
1532            }
1533
1534            Expr::JoinedString { parts } => {
1535                let mut count = 0u32;
1536                for part in parts {
1537                    match part {
1538                        StringPart::Literal(s) => {
1539                            out.push(Instruction::push_string(s.clone()));
1540                            count += 1;
1541                        }
1542                        StringPart::Expr(e) => {
1543                            self.compile_expr(e, out, locals);
1544                            count += 1;
1545                        }
1546                    }
1547                }
1548                out.push(Instruction::join_string(count));
1549            }
1550
1551            Expr::MultiAssign(..) => {
1552                // Multi-assign targets handled at statement level; no-op as expression
1553            }
1554        }
1555    }
1556
1557    fn compile_store(&mut self, target: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
1558        match target {
1559            Expr::LocalVar(name, _var_line) => {
1560                if let Some(sym) = locals.lookup(name) {
1561                    let (slot, base) = match &sym.kind {
1562                        SymbolKind::LocalVar { var_type, slot, .. } => {
1563                            (*slot, var_type.base_type())
1564                        }
1565                        SymbolKind::ScriptParam { param_type, slot } => {
1566                            (*slot, param_type.base_type())
1567                        }
1568                        _ => (0, BaseVarType::Integer),
1569                    };
1570                    let opcode = match base {
1571                        BaseVarType::Integer => Opcode::PopIntLocal,
1572                        BaseVarType::String => Opcode::PopStringLocal,
1573                        BaseVarType::Long => Opcode::PopLongLocal,
1574                    };
1575                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1576                }
1577            }
1578
1579            Expr::GameVar(name, _var_line) => {
1580                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1581                // Encoding: (1 << 16) | var_id in the operand.
1582                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1583                    (stripped, true)
1584                } else {
1585                    (name.as_str(), false)
1586                };
1587                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1588                    && let SymbolKind::GameVar {
1589                        var_id, category, ..
1590                    } = &sym.kind
1591                {
1592                    let opcode = match category.as_str() {
1593                        "varp" => Opcode::PopVarp,
1594                        "varn" => Opcode::PopVarn,
1595                        "vars" => Opcode::PopVars,
1596                        "varbit" => Opcode::PopVarbit,
1597                        _ => Opcode::PopVarp,
1598                    };
1599                    let encoded_id = if secondary {
1600                        (1 << 16) | *var_id
1601                    } else {
1602                        *var_id
1603                    };
1604                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1605                }
1606            }
1607
1608            Expr::ArrayAccess { name, index } => {
1609                // For array store: push index, then value is already on stack
1610                self.compile_expr(index, out, locals);
1611                if let Some(sym) = locals.lookup(name) {
1612                    let slot = match &sym.kind {
1613                        SymbolKind::LocalVar { slot, .. } => *slot,
1614                        _ => 0,
1615                    };
1616                    out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
1617                }
1618            }
1619
1620            Expr::MultiAssign(targets, target_lines) => {
1621                // Multi-return: pop return values in reverse order (last target = top of stack)
1622                for (i, target) in targets.iter().enumerate().rev() {
1623                    // Emit LineNumber for each target's source line
1624                    if let Some(&tl) = target_lines.get(i)
1625                        && tl > 0
1626                    {
1627                        Self::emit_line(tl, out);
1628                    }
1629                    self.compile_store(target, out, locals);
1630                }
1631            }
1632
1633            _ => {
1634                // Invalid store target - should be caught by type checker
1635            }
1636        }
1637    }
1638
1639    /// Returns the trigger type for commands whose first argument is a script name.
1640    fn command_script_trigger(cmd_name: &str) -> Option<&'static str> {
1641        match cmd_name {
1642            "queue" | "queue*" | "longqueue" | "longqueue*" | "strongqueue" | "strongqueue*"
1643            | "weakqueue" | "weakqueue*" | "clearqueue" => Some("queue"),
1644            "softtimer" | "softtimer*" => Some("softtimer"),
1645            "settimer" | "settimer*" | "cleartimer" => Some("timer"),
1646            "walktrigger" => Some("walktrigger"),
1647            _ => None,
1648        }
1649    }
1650
1651    /// Number of fixed (non-variadic) arguments for commands that push a type descriptor.
1652    /// Returns None for commands that don't use a type descriptor at all.
1653    fn command_variadic_info(cmd_name: &str) -> Option<usize> {
1654        match cmd_name {
1655            // queue/strongqueue/weakqueue have separate * variants (different opcodes)
1656            "queue*" | "strongqueue*" | "weakqueue*" => Some(2),
1657            "longqueue*" => Some(3),
1658            // settimer/softtimer are always variadic (no separate * variant)
1659            "settimer" | "softtimer" => Some(2),
1660            // runclientscript* has 1 fixed arg (script_id) + variadic params
1661            "runclientscript*" => Some(1),
1662            _ => None,
1663        }
1664    }
1665
1666    /// Infer the RS2 type character for an expression (used for variadic type descriptors).
1667    fn infer_type_char(&self, expr: &Expr, locals: &SymbolTable) -> char {
1668        match expr {
1669            Expr::StringLiteral(_) | Expr::JoinedString { .. } => 's',
1670            Expr::LongLiteral(_) => 'l',
1671            Expr::IntLiteral(_)
1672            | Expr::BoolLiteral(_)
1673            | Expr::CoordLiteral(_)
1674            | Expr::CharLiteral(_) => 'i',
1675            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1676                if let Some(sym) = locals.lookup(name) {
1677                    match &sym.kind {
1678                        SymbolKind::LocalVar { var_type, .. } => self.type_to_type_char(*var_type),
1679                        SymbolKind::ScriptParam { param_type, .. } => {
1680                            self.type_to_type_char(*param_type)
1681                        }
1682                        _ => 'i',
1683                    }
1684                } else {
1685                    'i'
1686                }
1687            }
1688            Expr::GameVar(name, _var_line) => {
1689                if let Some(sym) = self.registry.lookup_game_var(name)
1690                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1691                {
1692                    return self.type_to_type_char(*var_type);
1693                }
1694                'i'
1695            }
1696            Expr::CommandCall { name, .. } => {
1697                let lookup = name.trim_start_matches('.');
1698                if let Some(sym) = self.registry.lookup_command(lookup)
1699                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1700                    && let Some(rt) = return_types.first()
1701                {
1702                    return self.type_to_type_char(*rt);
1703                }
1704                // Unknown or void command - check known command types
1705                Self::known_command_type_char(lookup)
1706            }
1707            Expr::ProcCall { name, .. } => {
1708                if let Some(sym) = self.registry.lookup_script(name)
1709                    && let SymbolKind::Script { return_types, .. } = &sym.kind
1710                    && let Some(rt) = return_types.first()
1711                {
1712                    return self.type_to_type_char(*rt);
1713                }
1714                'i'
1715            }
1716            Expr::Identifier(name) => {
1717                // Bare identifier (no parens) - might be a zero-arg command like `uid`
1718                let lookup = name.trim_start_matches('.');
1719                if let Some(sym) = self.registry.lookup_command(lookup)
1720                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1721                    && let Some(rt) = return_types.first()
1722                {
1723                    return self.type_to_type_char(*rt);
1724                }
1725                Self::known_command_type_char(lookup)
1726            }
1727            Expr::ConstantVar(name, _) => {
1728                if let Some(sym) = self.registry.lookup_constant(name)
1729                    && let SymbolKind::Constant { const_type, .. } = &sym.kind
1730                {
1731                    return self.type_to_type_char(*const_type);
1732                }
1733                'i'
1734            }
1735            Expr::BinaryOp { .. } | Expr::Calc(_) => 'i',
1736            Expr::NullLiteral => 'i',
1737            _ => 'i',
1738        }
1739    }
1740
1741    /// Infer the type of an assignment target (lvalue) for type-hinted value compilation.
1742    fn infer_target_type(&self, target: &Expr, locals: &SymbolTable) -> Option<Type> {
1743        match target {
1744            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1745                if let Some(sym) = locals.lookup(name) {
1746                    match &sym.kind {
1747                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1748                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1749                        _ => None,
1750                    }
1751                } else {
1752                    None
1753                }
1754            }
1755            Expr::GameVar(name, _var_line) => {
1756                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1757                    stripped
1758                } else {
1759                    name.as_str()
1760                };
1761                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1762                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1763                {
1764                    return Some(*var_type);
1765                }
1766                None
1767            }
1768            _ => None,
1769        }
1770    }
1771
1772    /// Infer the `Type` of an expression for use as a comparison type hint.
1773    fn infer_type(&self, expr: &Expr, locals: &SymbolTable) -> Option<Type> {
1774        match expr {
1775            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1776                if let Some(sym) = locals.lookup(name) {
1777                    match &sym.kind {
1778                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1779                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1780                        _ => None,
1781                    }
1782                } else {
1783                    None
1784                }
1785            }
1786            Expr::GameVar(name, _var_line) => {
1787                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1788                    stripped
1789                } else {
1790                    name.as_str()
1791                };
1792                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1793                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1794                {
1795                    return Some(*var_type);
1796                }
1797                None
1798            }
1799            Expr::CommandCall { name, .. } => {
1800                let lookup = name.trim_start_matches('.');
1801                if let Some(sym) = self.registry.lookup_command(lookup)
1802                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1803                {
1804                    return return_types.first().copied();
1805                }
1806                None
1807            }
1808            Expr::Identifier(name) => {
1809                // Zero-arg commands used without parens (e.g. `loc_category`)
1810                let lookup = name.trim_start_matches('.');
1811                if let Some(sym) = self.registry.lookup_command(lookup)
1812                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1813                {
1814                    return return_types.first().copied();
1815                }
1816                None
1817            }
1818            _ => None,
1819        }
1820    }
1821
1822    fn type_to_type_char(&self, t: Type) -> char {
1823        match t.base_type() {
1824            BaseVarType::String => 's',
1825            BaseVarType::Long => 'l',
1826            BaseVarType::Integer => {
1827                // Use the type_chars map for more precise type chars
1828                // (e.g., namedobj='O', playeruid='p')
1829                for (name, &tc) in &self.registry.type_chars {
1830                    if let Some(from_type) = Type::from_name(name)
1831                        && from_type == t
1832                    {
1833                        return (tc as u8) as char;
1834                    }
1835                }
1836                'i'
1837            }
1838        }
1839    }
1840
1841    fn known_command_type_char(name: &str) -> char {
1842        // Commands whose return type is not in the sym file but is known
1843        match name {
1844            "uid" => 'p',     // PlayerUid
1845            "npc_uid" => 'u', // NpcUid
1846            "displayname" | "name" | "npc_name" | "oc_name" | "oc_cert" => 's',
1847            _ => 'i',
1848        }
1849    }
1850
1851    /// Returns `Some(error message)` if `[trigger,entity_name]` resolved a
1852    /// trigger byte but failed to resolve `entity_name` to a real subject,
1853    /// which would silently produce an unreachable script (lookup_key = -1).
1854    /// Returns `None` for legitimate cases:
1855    ///   - bare `_` wildcard (global trigger, no subject)
1856    ///   - `_category` form (category lookup — caller validates separately)
1857    ///   - coord-shaped triggers (`zone`, `zoneexit`, `mapzone`, `mapzoneexit`)
1858    ///   - name-keyed triggers (`queue`, `timer`, `walktrigger`, `proc`, `label`, …)
1859    pub fn validate_trigger_subject(
1860        trigger: &str,
1861        entity_name: &str,
1862        registry: &SymbolRegistry,
1863    ) -> Option<String> {
1864        if entity_name.is_empty() || entity_name == "_" {
1865            return None;
1866        }
1867        // Category subjects are validated by their own path; skip.
1868        if entity_name.starts_with('_') {
1869            return None;
1870        }
1871        // Triggers whose subject is a coord, has no subject at all, or is
1872        // historically not validated (ai_queue/ai_timer) — see trigger_table.
1873        if !crate::trigger_table::validates_subject(trigger) {
1874            return None;
1875        }
1876        let key = Self::compute_lookup_key(trigger, entity_name, registry);
1877        if key == -1 {
1878            let hint = if entity_name.contains(':') {
1879                let (iface, comp) = entity_name.split_once(':').unwrap();
1880                format!(
1881                    "interface:component subject — check interface.pack for either an if3 entry \
1882                     `<iface_id>:<comp_id>=<comp_name>` (with iface_id matching `{iface}`) \
1883                     or an if1 entry `<flat_id>={iface}:{comp}`"
1884                )
1885            } else {
1886                "Likely a typo or missing pack entry (check interface.pack / npc.pack / obj.pack / loc.pack)".to_string()
1887            };
1888            return Some(format!(
1889                "[{trigger},{entity_name}] — subject `{entity_name}` did not resolve to an entity. \
1890                 {hint}. Script will compile but never dispatch."
1891            ));
1892        }
1893        None
1894    }
1895
1896    /// Compute the CS2 Neptune lookup key for a script.
1897    /// Formula: `entity_id * 1024 + 512 + trigger_byte`, or -1 if not applicable.
1898    /// For global scripts (entity="_"), returns just `trigger_byte`.
1899    pub fn compute_lookup_key(trigger: &str, entity_name: &str, registry: &SymbolRegistry) -> i32 {
1900        // Trigger byte from the central trigger_table. Unknown triggers
1901        // (queue, softtimer, timer, walktrigger, proc, label, command,
1902        // clientscript, debugproc) are name-keyed and have no byte.
1903        let trigger_byte = match crate::trigger_table::byte(trigger) {
1904            Some(b) => b as i64,
1905            None => return -1,
1906        };
1907
1908        // Global scripts with no specific entity return just the trigger byte
1909        if entity_name == "_" {
1910            return trigger_byte as i32;
1911        }
1912
1913        // Coordinate-based triggers: parse "level_bx_by" format
1914        if matches!(trigger, "mapzone" | "mapzoneexit") {
1915            let parts: Vec<&str> = entity_name.splitn(4, '_').collect();
1916            if parts.len() >= 3
1917                && let (Ok(bx), Ok(by)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>())
1918            {
1919                let entity_id: i64 = ((bx & 3) << 20) | (by << 6);
1920                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1921            }
1922            return -1;
1923        }
1924
1925        // Coordinate-based triggers: parse "level_bx_by_lx_lz" format
1926        if matches!(trigger, "zone" | "zoneexit") {
1927            let parts: Vec<&str> = entity_name.splitn(6, '_').collect();
1928            if parts.len() >= 5
1929                && let (Ok(bx), Ok(by), Ok(lx), Ok(lz)) = (
1930                    parts[1].parse::<i64>(),
1931                    parts[2].parse::<i64>(),
1932                    parts[3].parse::<i64>(),
1933                    parts[4].parse::<i64>(),
1934                )
1935            {
1936                let entity_id: i64 = ((bx & 3) << 20) | (by << 6) | (lx << 14) | lz;
1937                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1938            }
1939            return -1;
1940        }
1941
1942        // Category-based entities: entity names starting with '_' reference a category
1943        // (e.g. [opheldu,_alcoholic_drinks] → category "alcoholic_drinks").
1944        // These use offset 256 instead of 512 in the lookupKey formula.
1945        //
1946        // NOTE: the bare `_` (pure wildcard) case is handled earlier in
1947        // this function (entity_name == "_" → returns just trigger_byte).
1948        if let Some(cat_name) = entity_name.strip_prefix('_') {
1949            if let Some(sym) = registry.lookup_entity_id_typed(cat_name, Type::Category) {
1950                return (sym as i64 * 1024 + 256 + trigger_byte) as i32;
1951            }
1952            return -1;
1953        }
1954
1955        // Component subject in `interface:component` form (e.g. `options:com_14`).
1956        // The subject is the packed `(iface_id << 16) | comp_id` registered by
1957        // symloader's `registry.components` map. Used by if_button / inv_button
1958        // triggers — their dispatch hashes iface+comp into 32 bits.
1959        if let Some((iface_name, comp_name)) = entity_name.split_once(':') {
1960            if let Some(packed) = registry.lookup_component(iface_name, comp_name) {
1961                return (packed as i64 * 1024 + 512 + trigger_byte) as i32;
1962            }
1963            return -1;
1964        }
1965
1966        // Type-aware entity lookup so that e.g. "potato" resolves to loc_id
1967        // for [oploc2,potato] rather than the obj_id that has higher flat
1968        // priority. Trigger → entity-type routing lives in trigger_table.
1969        if let Some(entity_type) = crate::trigger_table::subject_type(trigger)
1970            && let Some(entity_id) = registry.lookup_entity_id_typed(entity_name, entity_type)
1971        {
1972            return (entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
1973        }
1974
1975        // Fallback: flat entity_ids lookup
1976        if let Some(sym) = registry.lookup_entity_id(entity_name)
1977            && let crate::symbol::SymbolKind::Constant {
1978                int_value: Some(entity_id),
1979                ..
1980            } = &sym.kind
1981        {
1982            return (*entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
1983        }
1984        -1
1985    }
1986}
1987
1988#[cfg(test)]
1989mod tests {
1990    use super::*;
1991    use crate::types::Type;
1992
1993    /// Build a registry seeded with a few entities and one interface+component
1994    /// pair, mimicking the shape symloader produces from interface.pack /
1995    /// npc.pack / obj.pack.
1996    fn seed_registry() -> SymbolRegistry {
1997        let mut r = SymbolRegistry::new();
1998        // Interface 261 = "options", with component 14 = "com_14".
1999        // Key uses normalized form (com14) matching what symloader produces.
2000        r.register_entity_id("options".into(), Type::Interface, 261);
2001        r.register_entity_id("com14".into(), Type::Component, 14);
2002        r.components
2003            .insert("options:com14".into(), (261 << 16) | 14);
2004        // An npc + obj entity for non-interface trigger tests.
2005        r.register_entity_id("man".into(), Type::Npc, 1);
2006        r.register_entity_id("bronze_axe".into(), Type::Obj, 1351);
2007        r
2008    }
2009
2010    #[test]
2011    fn if_button_resolves_interface_component_form() {
2012        let r = seed_registry();
2013        let key = Compiler::compute_lookup_key("if_button", "options:com_14", &r);
2014        let expected = ((261i64 << 16 | 14) * 1024 + 512 + 147) as i32;
2015        assert_eq!(key, expected);
2016        // And the lookup-key wraps to match the engine's
2017        // ServerTriggerType::IfButton::lookup_key_subject(com_hash) where
2018        // com_hash = iface*65536 + comp.
2019        let com_hash = (261i64 << 16 | 14) as i32;
2020        let engine_key = (com_hash as i64 * 1024 + 512 + 147) as i32;
2021        assert_eq!(key, engine_key);
2022    }
2023
2024    #[test]
2025    fn validate_warns_on_unresolved_if_button_subject() {
2026        let r = seed_registry();
2027        // Unknown component name — old bug shape (would silently never dispatch).
2028        let warning =
2029            Compiler::validate_trigger_subject("if_button", "options:com_does_not_exist", &r);
2030        assert!(
2031            warning.is_some(),
2032            "expected a warning for unresolved subject"
2033        );
2034        assert!(warning.unwrap().contains("did not resolve"));
2035    }
2036
2037    #[test]
2038    fn validate_silent_on_resolvable_subject() {
2039        let r = seed_registry();
2040        assert!(Compiler::validate_trigger_subject("if_button", "options:com_14", &r).is_none());
2041        assert!(Compiler::validate_trigger_subject("opnpc1", "man", &r).is_none());
2042        assert!(Compiler::validate_trigger_subject("opheld1", "bronze_axe", &r).is_none());
2043    }
2044
2045    #[test]
2046    fn validate_silent_on_wildcards_and_categories() {
2047        let r = seed_registry();
2048        // Bare `_` — global trigger, no subject.
2049        assert!(Compiler::validate_trigger_subject("opheld1", "_", &r).is_none());
2050        // `_category` form — caller validates separately.
2051        assert!(Compiler::validate_trigger_subject("opheldu", "_alcoholic_drinks", &r).is_none());
2052    }
2053
2054    #[test]
2055    fn validate_silent_on_name_keyed_triggers() {
2056        let r = seed_registry();
2057        // queue/timer/walktrigger/proc are name-keyed; `lookup_key = -1` is correct.
2058        assert!(Compiler::validate_trigger_subject("queue", "my_queue", &r).is_none());
2059        assert!(Compiler::validate_trigger_subject("timer", "my_timer", &r).is_none());
2060        assert!(Compiler::validate_trigger_subject("proc", "my_proc", &r).is_none());
2061    }
2062
2063    #[test]
2064    fn validate_silent_on_coord_triggers() {
2065        let r = seed_registry();
2066        // Coord-shaped names are parsed from the entity string itself.
2067        assert!(Compiler::validate_trigger_subject("zone", "0_50_50_10_10", &r).is_none());
2068    }
2069
2070    #[test]
2071    fn validate_warns_on_unknown_npc_subject() {
2072        let r = seed_registry();
2073        let warning = Compiler::validate_trigger_subject("opnpc1", "not_a_real_npc", &r);
2074        assert!(warning.is_some());
2075    }
2076}