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    /// Test-harness commands (`test_op`, `wait_for`) accept a bare trigger or
533    /// command NAME in an `int` parameter and want it lowered to the trigger
534    /// byte / command opcode (e.g. `test_op(oploc1, ...)` → byte,
535    /// `wait_for(mes, ...)` → opcode). This is scoped to those commands ONLY,
536    /// so general identifier resolution is unchanged from pre-test behavior — a
537    /// command that shares a trigger's name (e.g. `if_close`) still compiles to
538    /// its command opcode everywhere else. Returns true (and emits the push) if
539    /// `arg` was handled here.
540    fn try_emit_test_command_id_arg(
541        &self,
542        lookup_name: &str,
543        arg: &Expr,
544        hint: Option<Type>,
545        out: &mut CompiledScript,
546    ) -> bool {
547        if !matches!(lookup_name, "test_op" | "wait_for") || hint != Some(Type::Int) {
548            return false;
549        }
550        let Expr::Identifier(ident) = arg else {
551            return false;
552        };
553        if ident.contains(':') {
554            return false;
555        }
556        if let Some(trigger_byte) = crate::trigger_table::byte(ident) {
557            out.push(Instruction::push_int(trigger_byte as i32));
558            return true;
559        }
560        if let Some(sym) = self
561            .registry
562            .lookup_command(ident.strip_prefix('.').unwrap_or(ident))
563            && let SymbolKind::Command { opcode, .. } = &sym.kind
564        {
565            let opcode = *opcode;
566            out.push(Instruction::push_int(opcode));
567            return true;
568        }
569        false
570    }
571
572    /// Compile a CommandCall expression starting at `args_start` (skipping already-pushed args).
573    fn compile_command_call_args_from(
574        &mut self,
575        name: &str,
576        args: &[Expr],
577        arg_lines: &[usize],
578        args_start: usize,
579        out: &mut CompiledScript,
580        locals: &mut SymbolTable,
581    ) {
582        let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
583            (stripped, 1u8)
584        } else {
585            (name, 0u8)
586        };
587        let param_types: Vec<Type> = self
588            .registry
589            .command_param_types
590            .get(lookup_name)
591            .cloned()
592            .unwrap_or_default();
593        let script_trigger = Self::command_script_trigger(lookup_name);
594        let variadic_info = Self::command_variadic_info(lookup_name);
595
596        for (i, arg) in args.iter().enumerate() {
597            if i < args_start {
598                continue;
599            }
600            if let Some(&al) = arg_lines.get(i)
601                && al > 0
602            {
603                Self::emit_line(al, out);
604            }
605            if i == 0
606                && let Some(trigger) = script_trigger
607                && let Expr::Identifier(script_name) = arg
608            {
609                let script_id = self
610                    .registry
611                    .script_id_for_trigger(trigger, script_name)
612                    .or_else(|| self.registry.proc_script_id(script_name))
613                    .or_else(|| self.registry.script_id(script_name))
614                    .unwrap_or(-1);
615                out.push(Instruction::push_int(script_id));
616                continue;
617            }
618            let hint = param_types.get(i).copied();
619            if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
620                continue;
621            }
622            self.compile_expr_hinted(arg, out, locals, hint);
623        }
624
625        if let Some(fixed_arg_count) = variadic_info {
626            let variadic_args = if args.len() > fixed_arg_count {
627                &args[fixed_arg_count..]
628            } else {
629                &[]
630            };
631            let type_desc: String = variadic_args
632                .iter()
633                .map(|arg| self.infer_type_char(arg, locals))
634                .collect();
635            out.push(Instruction::push_string(type_desc));
636        }
637
638        let cmd_sym = self
639            .registry
640            .lookup_command(lookup_name)
641            .or_else(|| {
642                lookup_name.strip_suffix('*').and_then(|base| {
643                    let vararg_name = format!("{}vararg", base);
644                    self.registry.lookup_command(&vararg_name)
645                })
646            })
647            .cloned();
648        if let Some(sym) = cmd_sym {
649            if let SymbolKind::Command { opcode, .. } = &sym.kind {
650                let encoded = opcode | ((cmd_index as i32) << 16);
651                out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
652            }
653        } else {
654            out.push(Instruction::new(
655                Opcode::Command,
656                Operand::Str(name.to_string()),
657            ));
658        }
659    }
660
661    /// Compile a condition expression emitting Java-style BranchTrue + Branch pair.
662    /// Returns (true_branch_positions, false_branch_positions):
663    ///   true_branch_positions  = indices of BranchXxx instructions that jump to the body
664    ///   false_branch_positions = indices of Branch instructions that jump to the else/end
665    fn compile_condition(
666        &mut self,
667        condition: &Expr,
668        out: &mut CompiledScript,
669        locals: &mut SymbolTable,
670    ) -> (Vec<usize>, Vec<usize>) {
671        match condition {
672            Expr::BinaryOp { op, lhs, rhs } => {
673                // Infer lhs type to use as hint for rhs (type-aware entity ID resolution).
674                let lhs_type_hint = self.infer_type(lhs, locals);
675                self.compile_expr(lhs, out, locals);
676                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
677
678                // Emit positive branch (branch-if-true to body)
679                let opcode = match op {
680                    BinOp::Eq => Opcode::BranchEquals,
681                    BinOp::NotEq => Opcode::BranchNot,
682                    BinOp::Lt => Opcode::BranchLessThan,
683                    BinOp::Gt => Opcode::BranchGreaterThan,
684                    BinOp::LtEq => Opcode::BranchLessThanOrEquals,
685                    BinOp::GtEq => Opcode::BranchGreaterThanOrEquals,
686                    _ => Opcode::BranchNot,
687                };
688                let true_pos = out.len();
689                out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
690
691                // Emit unconditional branch (fallthrough to else/end)
692                let false_pos = out.len();
693                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
694
695                (vec![true_pos], vec![false_pos])
696            }
697
698            Expr::LogicalOp {
699                op,
700                lhs,
701                rhs,
702                rhs_line,
703            } => {
704                match op {
705                    LogicOp::And => {
706                        // Short-circuit AND: if lhs is true continue to rhs, else → else/end
707                        let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
708
709                        // Patch lhs_true branches to rhs_start
710                        let rhs_start = out.len();
711                        for pos in &lhs_true {
712                            out.patch_jump(*pos, rhs_start);
713                        }
714
715                        // Emit LineNumber for RHS if it starts on a different line.
716                        // Writer deduplication handles same-line cases.
717                        Self::emit_line(*rhs_line, out);
718                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
719
720                        // Combined: body reached only if rhs also true
721                        // false paths: either lhs false OR rhs false
722                        let mut false_branches = lhs_false;
723                        false_branches.extend(rhs_false);
724                        (rhs_true, false_branches)
725                    }
726                    LogicOp::Or => {
727                        // Short-circuit OR: if lhs is true → body, else check rhs
728                        let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
729
730                        // Patch lhs_false branches to rhs_start
731                        let rhs_start = out.len();
732                        for pos in &lhs_false {
733                            out.patch_jump(*pos, rhs_start);
734                        }
735
736                        // Emit LineNumber for RHS if it starts on a different line.
737                        Self::emit_line(*rhs_line, out);
738                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
739
740                        // Combined: body reached if lhs true OR rhs true
741                        let mut true_branches = lhs_true;
742                        true_branches.extend(rhs_true);
743                        (true_branches, rhs_false)
744                    }
745                }
746            }
747
748            // For any other expression, push value and 0, branch if value != 0 (true)
749            _ => {
750                self.compile_expr(condition, out, locals);
751                out.push(Instruction::push_int(0));
752
753                let true_pos = out.len();
754                out.push(Instruction::new(Opcode::BranchNot, Operand::JumpTarget(0)));
755
756                let false_pos = out.len();
757                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
758
759                (vec![true_pos], vec![false_pos])
760            }
761        }
762    }
763
764    #[allow(clippy::too_many_arguments)]
765    fn compile_switch(
766        &mut self,
767        switch_type: &str,
768        expr: &Expr,
769        cases: &[SwitchCase],
770        default: &Option<Vec<Statement>>,
771        default_index: usize,
772        out: &mut CompiledScript,
773        locals: &mut SymbolTable,
774    ) {
775        self.compile_expr(expr, out, locals);
776        // Parse switch type to get type hint for case value resolution.
777        let case_type_hint =
778            Type::from_name(switch_type.strip_prefix("switch_").unwrap_or(switch_type));
779
780        // Emit SWITCH instruction (table to be filled in later)
781        let switch_idx = out.len();
782        out.push(Instruction::new(
783            Opcode::Switch,
784            Operand::SwitchTable(Vec::new()),
785        ));
786
787        // Layout (matches reference compiler):
788        //
789        //   default_index == 0 (default appeared FIRST):
790        //     [Switch]          ← on no-match, falls through to sw_pos+1 = default body
791        //     [default body]    ← at sw_pos+1
792        //     [Branch(end)]
793        //     [case_0 body]     ← switch table points here
794        //     [Branch(end)]
795        //     ...
796        //     [end_pos]
797        //
798        //   default_index > 0 (default appeared after some/all cases, or absent):
799        //     [Switch]          ← on no-match, falls through to sw_pos+1 = Branch
800        //     [Branch(to_default_or_end)]  ← at sw_pos+1
801        //     [case_0 body]
802        //     [Branch(end)]
803        //     ...
804        //     [default body]    ← emitted at source position among cases
805        //     [Branch(end)]
806        //     ...
807        //     [end_pos]
808
809        let mut end_jumps = Vec::new();
810        // position of the no-match Branch (when default is not first)
811        let default_first = default_index == 0 && default.is_some();
812
813        let default_branch_pos = if default_first {
814            // Default body at sw_pos+1 (direct fall-through, no Branch needed at sw_pos+1)
815            if let Some(default_stmts) = default {
816                for s in default_stmts {
817                    self.compile_statement(s, out, locals);
818                }
819                let jump_pos = out.len();
820                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
821                end_jumps.push(jump_pos);
822            }
823            None
824        } else {
825            // Branch at sw_pos+1 (to skip cases and reach default, or to end if no default)
826            let pos = out.len();
827            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
828            Some(pos)
829        };
830
831        // Compile case bodies in source order, inserting default at its original position
832        let mut case_positions: Vec<(Vec<i32>, usize)> = Vec::new();
833        let mut default_body_pos = 0usize;
834
835        for (i, case) in cases.iter().enumerate() {
836            // If default appeared at this position (and wasn't first), emit it now
837            if !default_first && i == default_index {
838                default_body_pos = out.len();
839                if let Some(default_stmts) = default {
840                    for s in default_stmts {
841                        self.compile_statement(s, out, locals);
842                    }
843                    let jump_pos = out.len();
844                    out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
845                    end_jumps.push(jump_pos);
846                }
847            }
848
849            let body_start = out.len();
850            let mut values = Vec::new();
851            for val in &case.values {
852                if let Expr::IntLiteral(n) = val {
853                    values.push(*n);
854                } else if let Expr::ConstantVar(cname, _) = val {
855                    // Resolve constant to integer for switch case value
856                    if let Some(sym) = self.registry.constants.get(cname)
857                        && let SymbolKind::Constant {
858                            int_value: Some(value),
859                            ..
860                        } = &sym.kind
861                    {
862                        values.push(*value);
863                    }
864                } else if let Expr::Identifier(ident) = val {
865                    // Component reference: interface:component → packed hash
866                    let mut resolved = false;
867                    if let Some((iface_name, comp_name)) = ident.split_once(':')
868                        && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
869                    {
870                        values.push(packed);
871                        resolved = true;
872                    }
873                    // Use switch type hint for type-aware resolution
874                    if !resolved
875                        && let Some(hint) = case_type_hint
876                        && let Some(id) = self.registry.lookup_entity_id_typed(ident, hint)
877                    {
878                        values.push(id);
879                        resolved = true;
880                    }
881                    if !resolved {
882                        if let Some(sym) = self.registry.entity_ids.get(ident.as_str()) {
883                            if let SymbolKind::Constant {
884                                int_value: Some(value),
885                                ..
886                            } = &sym.kind
887                            {
888                                values.push(*value);
889                            }
890                        } else if let Some(sym) = self.registry.constants.get(ident.as_str())
891                            && let SymbolKind::Constant {
892                                int_value: Some(value),
893                                ..
894                            } = &sym.kind
895                        {
896                            values.push(*value);
897                        }
898                    }
899                } else if let Expr::BinaryOp {
900                    op: BinOp::Add,
901                    lhs,
902                    rhs,
903                } = val
904                {
905                    // Handle entity names containing '+' (e.g. cheese+tom_batta)
906                    if let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
907                        (lhs.as_ref(), rhs.as_ref())
908                    {
909                        let combined = format!("{}+{}", lhs_name, rhs_name);
910                        if let Some(hint) = case_type_hint {
911                            if let Some(id) = self.registry.lookup_entity_id_typed(&combined, hint)
912                            {
913                                values.push(id);
914                            }
915                        } else if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
916                            && let SymbolKind::Constant {
917                                int_value: Some(id),
918                                ..
919                            } = &sym.kind
920                        {
921                            values.push(*id);
922                        }
923                    }
924                } else if let Expr::CoordLiteral(v) = val {
925                    values.push(*v);
926                }
927            }
928            case_positions.push((values, body_start));
929
930            for s in &case.body {
931                self.compile_statement(s, out, locals);
932            }
933
934            // Jump to end of switch (after all cases)
935            let jump_pos = out.len();
936            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
937            end_jumps.push(jump_pos);
938        }
939
940        // If default appeared after ALL explicit cases (default_index == cases.len()), emit it now
941        if !default_first && default_index >= cases.len() {
942            default_body_pos = out.len();
943            if let Some(default_stmts) = default {
944                for s in default_stmts {
945                    self.compile_statement(s, out, locals);
946                }
947                let jump_pos = out.len();
948                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
949                end_jumps.push(jump_pos);
950            }
951        }
952
953        let end_pos = out.len();
954
955        // Patch the no-match Branch (when default is not first)
956        if let Some(dbp) = default_branch_pos {
957            let default_target = if default.is_some() {
958                default_body_pos
959            } else {
960                end_pos
961            };
962            out.patch_jump(dbp, default_target);
963        }
964
965        // Build the switch table with body positions
966        let mut table = Vec::new();
967        for (values, pos) in &case_positions {
968            for &v in values {
969                table.push((v, *pos));
970            }
971        }
972
973        // Update the SWITCH instruction with the complete table
974        out.instructions[switch_idx].operand = Operand::SwitchTable(table);
975
976        // Patch end-of-case jumps to end_pos
977        for pos in end_jumps {
978            out.patch_jump(pos, end_pos);
979        }
980    }
981
982    fn compile_expr(&mut self, expr: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
983        self.compile_expr_hinted(expr, out, locals, None);
984    }
985
986    fn compile_expr_hinted(
987        &mut self,
988        expr: &Expr,
989        out: &mut CompiledScript,
990        locals: &mut SymbolTable,
991        type_hint: Option<Type>,
992    ) {
993        match expr {
994            Expr::IntLiteral(n) => {
995                out.push(Instruction::push_int(*n));
996            }
997
998            Expr::LongLiteral(n) => {
999                out.push(Instruction::push_long(*n));
1000            }
1001
1002            Expr::StringLiteral(s) => {
1003                if let Some(h) = type_hint
1004                    && h.base_type() == BaseVarType::Integer
1005                    && h != Type::Int
1006                    && h != Type::Boolean
1007                {
1008                    if let Some(id) = self.registry.lookup_entity_id_typed(s, h) {
1009                        out.push(Instruction::push_int(id));
1010                        return;
1011                    }
1012                    if let Some(sym) = self.registry.lookup_entity_id(s)
1013                        && let SymbolKind::Constant {
1014                            int_value: Some(id),
1015                            ..
1016                        } = &sym.kind
1017                    {
1018                        out.push(Instruction::push_int(*id));
1019                        return;
1020                    }
1021                }
1022                out.push(Instruction::push_string(s.clone()));
1023            }
1024
1025            Expr::BoolLiteral(b) => {
1026                out.push(Instruction::push_int(if *b { 1 } else { 0 }));
1027            }
1028
1029            Expr::NullLiteral => {
1030                // For string-typed parameters, null is the string "null".
1031                // For all other types, null is integer -1.
1032                if matches!(type_hint, Some(Type::String)) {
1033                    out.push(Instruction::push_string("null".to_string()));
1034                } else {
1035                    out.push(Instruction::push_int(-1));
1036                }
1037            }
1038
1039            Expr::CharLiteral(c) => {
1040                out.push(Instruction::push_int(*c as i32));
1041            }
1042
1043            Expr::CoordLiteral(c) => {
1044                out.push(Instruction::push_int(*c));
1045            }
1046
1047            Expr::LocalVar(name, _var_line) => {
1048                if let Some(sym) = locals.lookup(name) {
1049                    let (slot, base) = match &sym.kind {
1050                        SymbolKind::LocalVar { var_type, slot, .. } => {
1051                            (*slot, var_type.base_type())
1052                        }
1053                        SymbolKind::ScriptParam { param_type, slot } => {
1054                            (*slot, param_type.base_type())
1055                        }
1056                        _ => (0, BaseVarType::Integer),
1057                    };
1058                    let opcode = match base {
1059                        BaseVarType::Integer => Opcode::PushIntLocal,
1060                        BaseVarType::String => Opcode::PushStringLocal,
1061                        BaseVarType::Long => Opcode::PushLongLocal,
1062                    };
1063                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1064                } else {
1065                    // Variable not found - push 0 as fallback
1066                    out.push(Instruction::push_int(0));
1067                }
1068            }
1069
1070            Expr::GameVar(name, _var_line) => {
1071                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1072                // Encoding: (1 << 16) | var_id in the operand.
1073                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1074                    (stripped, true)
1075                } else {
1076                    (name.as_str(), false)
1077                };
1078                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1079                    && let SymbolKind::GameVar {
1080                        var_id, category, ..
1081                    } = &sym.kind
1082                {
1083                    let opcode = match category.as_str() {
1084                        "varp" => Opcode::PushVarp,
1085                        "varn" => Opcode::PushVarn,
1086                        "vars" => Opcode::PushVars,
1087                        "varbit" => Opcode::PushVarbit,
1088                        _ => Opcode::PushVarp,
1089                    };
1090                    let encoded_id = if secondary {
1091                        (1 << 16) | *var_id
1092                    } else {
1093                        *var_id
1094                    };
1095                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1096                }
1097            }
1098
1099            Expr::ConstantVar(name, const_line) => {
1100                if let Some(sym) = self.registry.lookup_constant(name).cloned()
1101                    && let SymbolKind::Constant {
1102                        int_value,
1103                        string_value,
1104                        ..
1105                    } = &sym.kind
1106                {
1107                    if let Some(v) = int_value {
1108                        out.push(Instruction::push_int(*v));
1109                    } else if let Some(s) = string_value {
1110                        // String constants: emit line - 1 to match Java compiler.
1111                        // The Java type checker resolves ^constant to a StringLiteral
1112                        // with NodeSourceLocation(line - 1, col - 1), converting from
1113                        // 1-based ANTLR lines to a 0-based offset. Integer constants
1114                        // are re-parsed via ANTLR with the offset, so they keep the
1115                        // original line (1 + (line-1) = line).
1116                        if *const_line > 0 {
1117                            Self::emit_line(*const_line - 1, out);
1118                        }
1119                        out.push(Instruction::push_string(s.clone()));
1120                    }
1121                }
1122            }
1123
1124            Expr::Identifier(name) => {
1125                // Component reference: interface_name:component_name → (iface_id << 16) | comp_id
1126                if let Some((iface_name, comp_name)) = name.split_once(':')
1127                    && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
1128                {
1129                    out.push(Instruction::push_int(packed));
1130                    return;
1131                }
1132
1133                // Resolution order: entity IDs (stat/npc/loc/etc.) > constants (.constant)
1134                // > commands > game vars > script IDs > fallback -1.
1135                // This matches Java: plain identifiers use entity IDs, not .constant overrides.
1136                //
1137                // When a type hint is available (propagated from the enclosing command call's
1138                // parameter types), prefer the type-specific entity ID. This handles cases where
1139                // the same name exists in multiple pack files (e.g. `smokepuff` in both synth.pack
1140                // and spotanim.pack) — the correct ID is chosen based on the expected parameter type.
1141                //
1142                // Script reference type hints (proc, label, queue, etc.) bypass entity IDs and
1143                // go directly to trigger-specific script ID lookup.
1144                if let Some(hint) = type_hint {
1145                    let trigger_opt: Option<&'static str> = match hint {
1146                        Type::Proc => Some("proc"),
1147                        Type::Label => Some("label"),
1148                        Type::Queue => Some("queue"),
1149                        Type::SoftTimer => Some("softtimer"),
1150                        Type::Timer => Some("timer"),
1151                        Type::Walktrigger => Some("walktrigger"),
1152                        _ => None,
1153                    };
1154                    if let Some(trigger) = trigger_opt {
1155                        let script_id = self
1156                            .registry
1157                            .script_id_for_trigger(trigger, name)
1158                            .or_else(|| self.registry.proc_script_id(name))
1159                            .or_else(|| self.registry.script_id(name))
1160                            .unwrap_or(-1);
1161                        out.push(Instruction::push_int(script_id));
1162                        return;
1163                    }
1164                    if let Some(id) = self.registry.lookup_entity_id_typed(name, hint) {
1165                        out.push(Instruction::push_int(id));
1166                        return;
1167                    }
1168                }
1169                if let Some(sym) = self.registry.lookup_entity_id(name).cloned()
1170                    && let SymbolKind::Constant {
1171                        const_type,
1172                        int_value,
1173                        string_value,
1174                    } = &sym.kind
1175                {
1176                    // Param entities should NOT shadow type name identifiers unless
1177                    // we have a Param-typed hint. This allows "namedobj" etc. to resolve
1178                    // to their type chars in enum(int, namedobj, ...) contexts.
1179                    let skip_for_type_char = *const_type == Type::Param
1180                        && type_hint != Some(Type::Param)
1181                        && self.registry.type_chars.contains_key(name);
1182                    if !skip_for_type_char {
1183                        if let Some(v) = int_value {
1184                            out.push(Instruction::push_int(*v));
1185                        } else if let Some(s) = string_value {
1186                            out.push(Instruction::push_string(s.clone()));
1187                        }
1188                        // If skip_for_type_char, fall through to commands/type_chars below
1189                        return;
1190                    }
1191                }
1192                // NOTE: a bare trigger/command NAME used as an int literal (the
1193                // test harness's `test_op(oploc1, ...)` / `wait_for(mes, ...)`)
1194                // is resolved at the *call site* of those specific commands (see
1195                // `try_emit_test_command_id_arg`), NOT here. Resolving it here
1196                // (for any int-hinted identifier) shadowed real commands that
1197                // share a trigger's name — notably `if_close`, both the close
1198                // command (opcode 2033) and the `[if_close,...]` trigger (byte
1199                // 148) — so a bare `if_close` statement compiled to
1200                // `push_int(148)` and the close was silently dropped.
1201                // Note: we fall through here only if entity lookup found a Param-type entity
1202                // that should be overridden by a type_char, or if entity lookup returned None.
1203                if let Some(sym) = self.registry.lookup_constant(name).cloned() {
1204                    if let SymbolKind::Constant {
1205                        int_value,
1206                        string_value,
1207                        ..
1208                    } = &sym.kind
1209                    {
1210                        if let Some(v) = int_value {
1211                            out.push(Instruction::push_int(*v));
1212                        } else if let Some(s) = string_value {
1213                            out.push(Instruction::push_string(s.clone()));
1214                        }
1215                    }
1216                } else {
1217                    let (lookup, idx) = if let Some(stripped) = name.strip_prefix('.') {
1218                        (stripped, 1u8)
1219                    } else {
1220                        (name.as_str(), 0u8)
1221                    };
1222                    let resolved = if let Some(sym) = self.registry.lookup_command(lookup).cloned()
1223                    {
1224                        if let SymbolKind::Command { opcode, .. } = &sym.kind {
1225                            let encoded = opcode | ((idx as i32) << 16);
1226                            out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1227                        }
1228                        true
1229                    } else {
1230                        false
1231                    };
1232                    if !resolved {
1233                        if let Some(sym) = self.registry.lookup_game_var(name).cloned()
1234                            && let SymbolKind::GameVar {
1235                                var_id, category, ..
1236                            } = &sym.kind
1237                        {
1238                            let push_op = match category.as_str() {
1239                                "varp" => Opcode::PushVarp,
1240                                "varn" => Opcode::PushVarn,
1241                                "vars" => Opcode::PushVars,
1242                                "varbit" => Opcode::PushVarbit,
1243                                _ => Opcode::PushVarp,
1244                            };
1245                            out.push(Instruction::new(push_op, Operand::Int(*var_id)));
1246                        } else if let Some(&type_char) = self.registry.type_chars.get(name) {
1247                            out.push(Instruction::push_int(type_char));
1248                        } else if let Some(script_id) = self
1249                            .registry
1250                            .proc_script_id(name)
1251                            .or_else(|| self.registry.script_id(name))
1252                        {
1253                            out.push(Instruction::push_int(script_id));
1254                        } else {
1255                            out.push(Instruction::push_int(-1));
1256                        }
1257                    }
1258                }
1259            }
1260
1261            Expr::ArrayAccess { name, index } => {
1262                // Push index
1263                self.compile_expr(index, out, locals);
1264
1265                // Push array element
1266                if let Some(sym) = locals.lookup(name) {
1267                    let slot = match &sym.kind {
1268                        SymbolKind::LocalVar { slot, .. } => *slot,
1269                        _ => 0,
1270                    };
1271                    out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(slot)));
1272                }
1273            }
1274
1275            Expr::BinaryOp { op, lhs, rhs } => {
1276                // Handle entity names that contain '+' (e.g. "cheese+tom_batta").
1277                // The parser splits these into BinaryOp::Add, but they should resolve
1278                // as a single entity identifier.
1279                if matches!(op, BinOp::Add)
1280                    && let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1281                        (lhs.as_ref(), rhs.as_ref())
1282                {
1283                    let combined = format!("{}+{}", lhs_name, rhs_name);
1284                    if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
1285                        && let SymbolKind::Constant {
1286                            int_value: Some(id),
1287                            ..
1288                        } = &sym.kind
1289                    {
1290                        out.push(Instruction::push_int(*id));
1291                        return;
1292                    }
1293                }
1294
1295                // For comparisons, infer the type of lhs to use as a hint for rhs.
1296                // This allows e.g. `$struct = blamish_oil` to correctly resolve
1297                // `blamish_oil` from struct.pack rather than a higher-priority pack.
1298                let lhs_type_hint = match op {
1299                    BinOp::Eq
1300                    | BinOp::NotEq
1301                    | BinOp::Lt
1302                    | BinOp::Gt
1303                    | BinOp::LtEq
1304                    | BinOp::GtEq => self.infer_type(lhs, locals),
1305                    _ => None,
1306                };
1307                self.compile_expr(lhs, out, locals);
1308                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
1309
1310                // Determine if this is a long operation based on operand types
1311                // For now, use int operations; type checker can refine
1312                let opcode = match op {
1313                    BinOp::Add => Opcode::Add,
1314                    BinOp::Sub => Opcode::Sub,
1315                    BinOp::Mul => Opcode::Multiply,
1316                    BinOp::Div => Opcode::Divide,
1317                    BinOp::Mod => Opcode::Modulo,
1318                    BinOp::BitAnd => Opcode::And,
1319                    BinOp::BitOr => Opcode::Or,
1320                    BinOp::Eq => {
1321                        Self::emit_comparison_value(Opcode::BranchEquals, 0, 1, out);
1322                        return;
1323                    }
1324                    BinOp::NotEq => {
1325                        Self::emit_comparison_value(Opcode::BranchEquals, 1, 0, out);
1326                        return;
1327                    }
1328                    BinOp::Lt => {
1329                        Self::emit_comparison_value(Opcode::BranchLessThan, 0, 1, out);
1330                        return;
1331                    }
1332                    BinOp::Gt => {
1333                        Self::emit_comparison_value(Opcode::BranchGreaterThan, 0, 1, out);
1334                        return;
1335                    }
1336                    BinOp::LtEq => {
1337                        Self::emit_comparison_value(Opcode::BranchLessThanOrEquals, 0, 1, out);
1338                        return;
1339                    }
1340                    BinOp::GtEq => {
1341                        Self::emit_comparison_value(Opcode::BranchGreaterThanOrEquals, 0, 1, out);
1342                        return;
1343                    }
1344                };
1345                out.push(Instruction::simple(opcode));
1346            }
1347
1348            Expr::LogicalOp { op, lhs, rhs, .. } => {
1349                self.compile_expr(lhs, out, locals);
1350                self.compile_expr(rhs, out, locals);
1351                match op {
1352                    LogicOp::And => out.push(Instruction::simple(Opcode::And)),
1353                    LogicOp::Or => out.push(Instruction::simple(Opcode::Or)),
1354                }
1355            }
1356
1357            Expr::Calc(inner) => {
1358                self.compile_expr(inner, out, locals);
1359            }
1360
1361            Expr::CommandCall {
1362                name,
1363                args,
1364                arg_lines,
1365                call_line,
1366            } => {
1367                // Dot-prefixed commands address the secondary active entity (operand = 1).
1368                let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
1369                    (stripped, 1u8)
1370                } else {
1371                    (name.as_str(), 0u8)
1372                };
1373
1374                // Fetch per-position type hints from the engine command signature.
1375                let param_types: Vec<Type> = self
1376                    .registry
1377                    .command_param_types
1378                    .get(lookup_name)
1379                    .cloned()
1380                    .unwrap_or_default();
1381
1382                // Commands that take a script reference as their first argument and
1383                // variadic extra arguments (described by a type-string pushed after them).
1384                let script_trigger = Self::command_script_trigger(lookup_name);
1385                let variadic_info = Self::command_variadic_info(lookup_name);
1386
1387                // Compile arguments, with special handling for the script-name first arg.
1388                for (i, arg) in args.iter().enumerate() {
1389                    // Emit LineNumber before each arg to track multi-line calls.
1390                    if let Some(&al) = arg_lines.get(i)
1391                        && al > 0
1392                    {
1393                        Self::emit_line(al, out);
1394                    }
1395                    if i == 0
1396                        && let Some(trigger) = script_trigger
1397                    {
1398                        // First arg is a script name identifier: resolve to trigger-specific ID.
1399                        if let Expr::Identifier(script_name) = arg {
1400                            let script_id = self
1401                                .registry
1402                                .script_id_for_trigger(trigger, script_name)
1403                                .or_else(|| self.registry.proc_script_id(script_name))
1404                                .or_else(|| self.registry.script_id(script_name))
1405                                .unwrap_or(-1);
1406                            out.push(Instruction::push_int(script_id));
1407                            continue;
1408                        }
1409                    }
1410                    // For 'enum' command, args 0 and 1 are input/output type chars.
1411                    // Resolve plain identifiers as type chars before falling through to commands.
1412                    if (lookup_name == "enum"
1413                        || lookup_name == "enum2"
1414                        || lookup_name == "db_getfield"
1415                        || lookup_name == "db_find"
1416                        || lookup_name == "db_find_refine"
1417                        || lookup_name == "db_findbyindex"
1418                        || lookup_name == "db_find_with_count"
1419                        || lookup_name == "param")
1420                        && (i == 0 || i == 1)
1421                        && let Expr::Identifier(n) = arg
1422                        && let Some(&tc) = self.registry.type_chars.get(n.as_str())
1423                    {
1424                        out.push(Instruction::push_int(tc));
1425                        continue;
1426                    }
1427                    let hint = param_types.get(i).copied();
1428                    if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
1429                        continue;
1430                    }
1431                    self.compile_expr_hinted(arg, out, locals, hint);
1432                }
1433
1434                // Push the variadic type-descriptor string for commands that support it.
1435                if let Some(fixed_arg_count) = variadic_info {
1436                    let variadic_args = if args.len() > fixed_arg_count {
1437                        &args[fixed_arg_count..]
1438                    } else {
1439                        &[]
1440                    };
1441                    let type_desc: String = variadic_args
1442                        .iter()
1443                        .map(|arg| self.infer_type_char(arg, locals))
1444                        .collect();
1445                    out.push(Instruction::push_string(type_desc));
1446                }
1447
1448                // db_find needs an implicit extra push_int argument: the Java BaseVarType
1449                // ordinal of the column's first field type (INT=0, LONG=1, STRING=2).
1450                if lookup_name == "db_find" || lookup_name == "db_find_refine" {
1451                    let base_type_ordinal = if let Some(Expr::Identifier(col_name)) = args.first() {
1452                        self.registry
1453                            .dbcolumn_types
1454                            .get(col_name.as_str())
1455                            .map(|t| match t.base_type() {
1456                                crate::types::BaseVarType::Integer => 0,
1457                                crate::types::BaseVarType::Long => 1,
1458                                crate::types::BaseVarType::String => 2,
1459                            })
1460                            .unwrap_or(0)
1461                    } else {
1462                        0
1463                    };
1464                    out.push(Instruction::push_int(base_type_ordinal));
1465                }
1466
1467                // Re-emit the call expression's line before the final command instruction.
1468                // The reference compiler does lineInstruction(expr) after visiting args.
1469                if *call_line > 0 {
1470                    Self::emit_line(*call_line, out);
1471                }
1472
1473                // Look up command opcode and emit.
1474                // For variadic variants (name*), also check the "namevararg" form
1475                // used in command.pack.
1476                let cmd_sym = self
1477                    .registry
1478                    .lookup_command(lookup_name)
1479                    .or_else(|| {
1480                        lookup_name.strip_suffix('*').and_then(|base| {
1481                            let vararg_name = format!("{}vararg", base);
1482                            self.registry.lookup_command(&vararg_name)
1483                        })
1484                    })
1485                    .cloned();
1486                if let Some(sym) = cmd_sym {
1487                    if let SymbolKind::Command { opcode, .. } = &sym.kind {
1488                        let encoded = (*opcode) | ((cmd_index as i32) << 16);
1489                        out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1490                    }
1491                } else {
1492                    out.push(Instruction::new(
1493                        Opcode::Command,
1494                        Operand::Str(name.clone()),
1495                    ));
1496                }
1497
1498                // Note: db_find and db_find_refine do NOT push a count value.
1499                // Only db_find_with_count and db_find_refine_with_count push a count.
1500            }
1501
1502            Expr::ProcCall {
1503                name,
1504                args,
1505                arg_lines,
1506                call_line,
1507            } => {
1508                // Get parameter types from target proc for type-aware arg compilation
1509                let param_types: Vec<Type> = self
1510                    .registry
1511                    .lookup_script(name)
1512                    .and_then(|sym| {
1513                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1514                            Some(param_types.clone())
1515                        } else {
1516                            None
1517                        }
1518                    })
1519                    .unwrap_or_default();
1520                for (i, arg) in args.iter().enumerate() {
1521                    if let Some(&al) = arg_lines.get(i)
1522                        && al > 0
1523                    {
1524                        Self::emit_line(al, out);
1525                    }
1526                    let hint = param_types.get(i).copied();
1527                    self.compile_expr_hinted(arg, out, locals, hint);
1528                }
1529
1530                // Re-emit call expression's line before final gosub.
1531                if *call_line > 0 {
1532                    Self::emit_line(*call_line, out);
1533                }
1534
1535                // `~name(...)` resolves ONLY against `[proc,name]` — matching
1536                // RuneScriptTS. A silent fallback to any script with this name
1537                // (debugproc / label / timer) lets `~foo` bind to an unrelated
1538                // trigger; if that trigger's body also calls `~foo`, you get
1539                // infinite recursion at runtime. The type checker emits an
1540                // error diagnostic for unresolved procs, so `-1` here only
1541                // fires in paths that already produced an error.
1542                let script_id = self.registry.proc_script_id(name).unwrap_or(-1);
1543                out.push(Instruction::gosub_with_params(script_id));
1544            }
1545
1546            Expr::JumpCall {
1547                name,
1548                args,
1549                arg_lines,
1550                call_line,
1551            } => {
1552                // Get parameter types from target label for type-aware arg compilation
1553                let param_types: Vec<Type> = self
1554                    .registry
1555                    .lookup_script(name)
1556                    .and_then(|sym| {
1557                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
1558                            Some(param_types.clone())
1559                        } else {
1560                            None
1561                        }
1562                    })
1563                    .unwrap_or_default();
1564                for (i, arg) in args.iter().enumerate() {
1565                    if let Some(&al) = arg_lines.get(i)
1566                        && al > 0
1567                    {
1568                        Self::emit_line(al, out);
1569                    }
1570                    let hint = param_types.get(i).copied();
1571                    self.compile_expr_hinted(arg, out, locals, hint);
1572                }
1573                // Re-emit call expression's line before final jump.
1574                if *call_line > 0 {
1575                    Self::emit_line(*call_line, out);
1576                }
1577
1578                let script_id = self
1579                    .registry
1580                    .label_script_id(name)
1581                    .or_else(|| self.registry.script_id(name))
1582                    .unwrap_or(-1);
1583                out.push(Instruction::new(
1584                    Opcode::JumpWithParams,
1585                    Operand::Int(script_id),
1586                ));
1587            }
1588
1589            Expr::JoinedString { parts } => {
1590                let mut count = 0u32;
1591                for part in parts {
1592                    match part {
1593                        StringPart::Literal(s) => {
1594                            out.push(Instruction::push_string(s.clone()));
1595                            count += 1;
1596                        }
1597                        StringPart::Expr(e) => {
1598                            self.compile_expr(e, out, locals);
1599                            count += 1;
1600                        }
1601                    }
1602                }
1603                out.push(Instruction::join_string(count));
1604            }
1605
1606            Expr::MultiAssign(..) => {
1607                // Multi-assign targets handled at statement level; no-op as expression
1608            }
1609        }
1610    }
1611
1612    fn compile_store(&mut self, target: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
1613        match target {
1614            Expr::LocalVar(name, _var_line) => {
1615                if let Some(sym) = locals.lookup(name) {
1616                    let (slot, base) = match &sym.kind {
1617                        SymbolKind::LocalVar { var_type, slot, .. } => {
1618                            (*slot, var_type.base_type())
1619                        }
1620                        SymbolKind::ScriptParam { param_type, slot } => {
1621                            (*slot, param_type.base_type())
1622                        }
1623                        _ => (0, BaseVarType::Integer),
1624                    };
1625                    let opcode = match base {
1626                        BaseVarType::Integer => Opcode::PopIntLocal,
1627                        BaseVarType::String => Opcode::PopStringLocal,
1628                        BaseVarType::Long => Opcode::PopLongLocal,
1629                    };
1630                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1631                }
1632            }
1633
1634            Expr::GameVar(name, _var_line) => {
1635                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1636                // Encoding: (1 << 16) | var_id in the operand.
1637                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1638                    (stripped, true)
1639                } else {
1640                    (name.as_str(), false)
1641                };
1642                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1643                    && let SymbolKind::GameVar {
1644                        var_id, category, ..
1645                    } = &sym.kind
1646                {
1647                    let opcode = match category.as_str() {
1648                        "varp" => Opcode::PopVarp,
1649                        "varn" => Opcode::PopVarn,
1650                        "vars" => Opcode::PopVars,
1651                        "varbit" => Opcode::PopVarbit,
1652                        _ => Opcode::PopVarp,
1653                    };
1654                    let encoded_id = if secondary {
1655                        (1 << 16) | *var_id
1656                    } else {
1657                        *var_id
1658                    };
1659                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1660                }
1661            }
1662
1663            Expr::ArrayAccess { name, index } => {
1664                // For array store: push index, then value is already on stack
1665                self.compile_expr(index, out, locals);
1666                if let Some(sym) = locals.lookup(name) {
1667                    let slot = match &sym.kind {
1668                        SymbolKind::LocalVar { slot, .. } => *slot,
1669                        _ => 0,
1670                    };
1671                    out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
1672                }
1673            }
1674
1675            Expr::MultiAssign(targets, target_lines) => {
1676                // Multi-return: pop return values in reverse order (last target = top of stack)
1677                for (i, target) in targets.iter().enumerate().rev() {
1678                    // Emit LineNumber for each target's source line
1679                    if let Some(&tl) = target_lines.get(i)
1680                        && tl > 0
1681                    {
1682                        Self::emit_line(tl, out);
1683                    }
1684                    self.compile_store(target, out, locals);
1685                }
1686            }
1687
1688            _ => {
1689                // Invalid store target - should be caught by type checker
1690            }
1691        }
1692    }
1693
1694    /// Returns the trigger type for commands whose first argument is a script name.
1695    fn command_script_trigger(cmd_name: &str) -> Option<&'static str> {
1696        match cmd_name {
1697            "queue" | "queue*" | "longqueue" | "longqueue*" | "strongqueue" | "strongqueue*"
1698            | "weakqueue" | "weakqueue*" | "clearqueue" => Some("queue"),
1699            "softtimer" | "softtimer*" => Some("softtimer"),
1700            "settimer" | "settimer*" | "cleartimer" => Some("timer"),
1701            "walktrigger" => Some("walktrigger"),
1702            _ => None,
1703        }
1704    }
1705
1706    /// Number of fixed (non-variadic) arguments for commands that push a type descriptor.
1707    /// Returns None for commands that don't use a type descriptor at all.
1708    fn command_variadic_info(cmd_name: &str) -> Option<usize> {
1709        match cmd_name {
1710            // queue/strongqueue/weakqueue have separate * variants (different opcodes)
1711            "queue*" | "strongqueue*" | "weakqueue*" => Some(2),
1712            "longqueue*" => Some(3),
1713            // settimer/softtimer are always variadic (no separate * variant)
1714            "settimer" | "softtimer" => Some(2),
1715            // runclientscript* has 1 fixed arg (script_id) + variadic params
1716            "runclientscript*" => Some(1),
1717            _ => None,
1718        }
1719    }
1720
1721    /// Infer the RS2 type character for an expression (used for variadic type descriptors).
1722    fn infer_type_char(&self, expr: &Expr, locals: &SymbolTable) -> char {
1723        match expr {
1724            Expr::StringLiteral(_) | Expr::JoinedString { .. } => 's',
1725            Expr::LongLiteral(_) => 'l',
1726            Expr::IntLiteral(_)
1727            | Expr::BoolLiteral(_)
1728            | Expr::CoordLiteral(_)
1729            | Expr::CharLiteral(_) => 'i',
1730            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1731                if let Some(sym) = locals.lookup(name) {
1732                    match &sym.kind {
1733                        SymbolKind::LocalVar { var_type, .. } => self.type_to_type_char(*var_type),
1734                        SymbolKind::ScriptParam { param_type, .. } => {
1735                            self.type_to_type_char(*param_type)
1736                        }
1737                        _ => 'i',
1738                    }
1739                } else {
1740                    'i'
1741                }
1742            }
1743            Expr::GameVar(name, _var_line) => {
1744                if let Some(sym) = self.registry.lookup_game_var(name)
1745                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1746                {
1747                    return self.type_to_type_char(*var_type);
1748                }
1749                'i'
1750            }
1751            Expr::CommandCall { name, .. } => {
1752                let lookup = name.trim_start_matches('.');
1753                if let Some(sym) = self.registry.lookup_command(lookup)
1754                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1755                    && let Some(rt) = return_types.first()
1756                {
1757                    return self.type_to_type_char(*rt);
1758                }
1759                // Unknown or void command - check known command types
1760                Self::known_command_type_char(lookup)
1761            }
1762            Expr::ProcCall { name, .. } => {
1763                if let Some(sym) = self.registry.lookup_script(name)
1764                    && let SymbolKind::Script { return_types, .. } = &sym.kind
1765                    && let Some(rt) = return_types.first()
1766                {
1767                    return self.type_to_type_char(*rt);
1768                }
1769                'i'
1770            }
1771            Expr::Identifier(name) => {
1772                // Bare identifier (no parens) - might be a zero-arg command like `uid`
1773                let lookup = name.trim_start_matches('.');
1774                if let Some(sym) = self.registry.lookup_command(lookup)
1775                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1776                    && let Some(rt) = return_types.first()
1777                {
1778                    return self.type_to_type_char(*rt);
1779                }
1780                Self::known_command_type_char(lookup)
1781            }
1782            Expr::ConstantVar(name, _) => {
1783                if let Some(sym) = self.registry.lookup_constant(name)
1784                    && let SymbolKind::Constant { const_type, .. } = &sym.kind
1785                {
1786                    return self.type_to_type_char(*const_type);
1787                }
1788                'i'
1789            }
1790            Expr::BinaryOp { .. } | Expr::Calc(_) => 'i',
1791            Expr::NullLiteral => 'i',
1792            _ => 'i',
1793        }
1794    }
1795
1796    /// Infer the type of an assignment target (lvalue) for type-hinted value compilation.
1797    fn infer_target_type(&self, target: &Expr, locals: &SymbolTable) -> Option<Type> {
1798        match target {
1799            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1800                if let Some(sym) = locals.lookup(name) {
1801                    match &sym.kind {
1802                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1803                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1804                        _ => None,
1805                    }
1806                } else {
1807                    None
1808                }
1809            }
1810            Expr::GameVar(name, _var_line) => {
1811                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1812                    stripped
1813                } else {
1814                    name.as_str()
1815                };
1816                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1817                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1818                {
1819                    return Some(*var_type);
1820                }
1821                None
1822            }
1823            _ => None,
1824        }
1825    }
1826
1827    /// Infer the `Type` of an expression for use as a comparison type hint.
1828    fn infer_type(&self, expr: &Expr, locals: &SymbolTable) -> Option<Type> {
1829        match expr {
1830            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1831                if let Some(sym) = locals.lookup(name) {
1832                    match &sym.kind {
1833                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1834                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1835                        _ => None,
1836                    }
1837                } else {
1838                    None
1839                }
1840            }
1841            Expr::GameVar(name, _var_line) => {
1842                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1843                    stripped
1844                } else {
1845                    name.as_str()
1846                };
1847                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1848                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1849                {
1850                    return Some(*var_type);
1851                }
1852                None
1853            }
1854            Expr::CommandCall { name, .. } => {
1855                let lookup = name.trim_start_matches('.');
1856                if let Some(sym) = self.registry.lookup_command(lookup)
1857                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1858                {
1859                    return return_types.first().copied();
1860                }
1861                None
1862            }
1863            Expr::Identifier(name) => {
1864                // Zero-arg commands used without parens (e.g. `loc_category`)
1865                let lookup = name.trim_start_matches('.');
1866                if let Some(sym) = self.registry.lookup_command(lookup)
1867                    && let SymbolKind::Command { return_types, .. } = &sym.kind
1868                {
1869                    return return_types.first().copied();
1870                }
1871                None
1872            }
1873            _ => None,
1874        }
1875    }
1876
1877    fn type_to_type_char(&self, t: Type) -> char {
1878        match t.base_type() {
1879            BaseVarType::String => 's',
1880            BaseVarType::Long => 'l',
1881            BaseVarType::Integer => {
1882                // Use the type_chars map for more precise type chars
1883                // (e.g., namedobj='O', playeruid='p')
1884                for (name, &tc) in &self.registry.type_chars {
1885                    if let Some(from_type) = Type::from_name(name)
1886                        && from_type == t
1887                    {
1888                        return (tc as u8) as char;
1889                    }
1890                }
1891                'i'
1892            }
1893        }
1894    }
1895
1896    fn known_command_type_char(name: &str) -> char {
1897        // Commands whose return type is not in the sym file but is known
1898        match name {
1899            "uid" => 'p',     // PlayerUid
1900            "npc_uid" => 'u', // NpcUid
1901            "displayname" | "name" | "npc_name" | "oc_name" | "oc_cert" => 's',
1902            _ => 'i',
1903        }
1904    }
1905
1906    /// Returns `Some(error message)` if `[trigger,entity_name]` resolved a
1907    /// trigger byte but failed to resolve `entity_name` to a real subject,
1908    /// which would silently produce an unreachable script (lookup_key = -1).
1909    /// Returns `None` for legitimate cases:
1910    ///   - bare `_` wildcard (global trigger, no subject)
1911    ///   - `_category` form (category lookup — caller validates separately)
1912    ///   - coord-shaped triggers (`zone`, `zoneexit`, `mapzone`, `mapzoneexit`)
1913    ///   - name-keyed triggers (`queue`, `timer`, `walktrigger`, `proc`, `label`, …)
1914    pub fn validate_trigger_subject(
1915        trigger: &str,
1916        entity_name: &str,
1917        registry: &SymbolRegistry,
1918    ) -> Option<String> {
1919        if entity_name.is_empty() || entity_name == "_" {
1920            return None;
1921        }
1922        // Category subjects are validated by their own path; skip.
1923        if entity_name.starts_with('_') {
1924            return None;
1925        }
1926        // Triggers whose subject is a coord, has no subject at all, or is
1927        // historically not validated (ai_queue/ai_timer) — see trigger_table.
1928        if !crate::trigger_table::validates_subject(trigger) {
1929            return None;
1930        }
1931        let key = Self::compute_lookup_key(trigger, entity_name, registry);
1932        if key == -1 {
1933            let hint = if entity_name.contains(':') {
1934                let (iface, comp) = entity_name.split_once(':').unwrap();
1935                format!(
1936                    "interface:component subject — check interface.pack for either an if3 entry \
1937                     `<iface_id>:<comp_id>=<comp_name>` (with iface_id matching `{iface}`) \
1938                     or an if1 entry `<flat_id>={iface}:{comp}`"
1939                )
1940            } else {
1941                "Likely a typo or missing pack entry (check interface.pack / npc.pack / obj.pack / loc.pack)".to_string()
1942            };
1943            return Some(format!(
1944                "[{trigger},{entity_name}] — subject `{entity_name}` did not resolve to an entity. \
1945                 {hint}. Script will compile but never dispatch."
1946            ));
1947        }
1948        None
1949    }
1950
1951    /// Compute the CS2 Neptune lookup key for a script.
1952    /// Formula: `entity_id * 1024 + 512 + trigger_byte`, or -1 if not applicable.
1953    /// For global scripts (entity="_"), returns just `trigger_byte`.
1954    pub fn compute_lookup_key(trigger: &str, entity_name: &str, registry: &SymbolRegistry) -> i32 {
1955        // Trigger byte from the central trigger_table. Unknown triggers
1956        // (queue, softtimer, timer, walktrigger, proc, label, command,
1957        // clientscript, debugproc) are name-keyed and have no byte.
1958        let trigger_byte = match crate::trigger_table::byte(trigger) {
1959            Some(b) => b as i64,
1960            None => return -1,
1961        };
1962
1963        // Global scripts with no specific entity return just the trigger byte
1964        if entity_name == "_" {
1965            return trigger_byte as i32;
1966        }
1967
1968        // Coordinate-based triggers: parse "level_bx_by" format
1969        if matches!(trigger, "mapzone" | "mapzoneexit") {
1970            let parts: Vec<&str> = entity_name.splitn(4, '_').collect();
1971            if parts.len() >= 3
1972                && let (Ok(bx), Ok(by)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>())
1973            {
1974                let entity_id: i64 = ((bx & 3) << 20) | (by << 6);
1975                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1976            }
1977            return -1;
1978        }
1979
1980        // Coordinate-based triggers: parse "level_bx_by_lx_lz" format
1981        if matches!(trigger, "zone" | "zoneexit") {
1982            let parts: Vec<&str> = entity_name.splitn(6, '_').collect();
1983            if parts.len() >= 5
1984                && let (Ok(bx), Ok(by), Ok(lx), Ok(lz)) = (
1985                    parts[1].parse::<i64>(),
1986                    parts[2].parse::<i64>(),
1987                    parts[3].parse::<i64>(),
1988                    parts[4].parse::<i64>(),
1989                )
1990            {
1991                let entity_id: i64 = ((bx & 3) << 20) | (by << 6) | (lx << 14) | lz;
1992                return (entity_id * 1024 + 512 + trigger_byte) as i32;
1993            }
1994            return -1;
1995        }
1996
1997        // Category-based entities: entity names starting with '_' reference a category
1998        // (e.g. [opheldu,_alcoholic_drinks] → category "alcoholic_drinks").
1999        // These use offset 256 instead of 512 in the lookupKey formula.
2000        //
2001        // NOTE: the bare `_` (pure wildcard) case is handled earlier in
2002        // this function (entity_name == "_" → returns just trigger_byte).
2003        if let Some(cat_name) = entity_name.strip_prefix('_') {
2004            if let Some(sym) = registry.lookup_entity_id_typed(cat_name, Type::Category) {
2005                return (sym as i64 * 1024 + 256 + trigger_byte) as i32;
2006            }
2007            return -1;
2008        }
2009
2010        // Component subject in `interface:component` form (e.g. `options:com_14`).
2011        // The subject is the packed `(iface_id << 16) | comp_id` registered by
2012        // symloader's `registry.components` map. Used by if_button / inv_button
2013        // triggers — their dispatch hashes iface+comp into 32 bits.
2014        if let Some((iface_name, comp_name)) = entity_name.split_once(':') {
2015            if let Some(packed) = registry.lookup_component(iface_name, comp_name) {
2016                return (packed as i64 * 1024 + 512 + trigger_byte) as i32;
2017            }
2018            return -1;
2019        }
2020
2021        // Type-aware entity lookup so that e.g. "potato" resolves to loc_id
2022        // for [oploc2,potato] rather than the obj_id that has higher flat
2023        // priority. Trigger → entity-type routing lives in trigger_table.
2024        if let Some(entity_type) = crate::trigger_table::subject_type(trigger)
2025            && let Some(entity_id) = registry.lookup_entity_id_typed(entity_name, entity_type)
2026        {
2027            return (entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2028        }
2029
2030        // Fallback: flat entity_ids lookup
2031        if let Some(sym) = registry.lookup_entity_id(entity_name)
2032            && let crate::symbol::SymbolKind::Constant {
2033                int_value: Some(entity_id),
2034                ..
2035            } = &sym.kind
2036        {
2037            return (*entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2038        }
2039        -1
2040    }
2041}
2042
2043#[cfg(test)]
2044mod tests {
2045    use super::*;
2046    use crate::types::Type;
2047
2048    /// Build a registry seeded with a few entities and one interface+component
2049    /// pair, mimicking the shape symloader produces from interface.pack /
2050    /// npc.pack / obj.pack.
2051    fn seed_registry() -> SymbolRegistry {
2052        let mut r = SymbolRegistry::new();
2053        // Interface 261 = "options", with component 14 = "com_14".
2054        // Key uses normalized form (com14) matching what symloader produces.
2055        r.register_entity_id("options".into(), Type::Interface, 261);
2056        r.register_entity_id("com14".into(), Type::Component, 14);
2057        r.components
2058            .insert("options:com14".into(), (261 << 16) | 14);
2059        // An npc + obj entity for non-interface trigger tests.
2060        r.register_entity_id("man".into(), Type::Npc, 1);
2061        r.register_entity_id("bronze_axe".into(), Type::Obj, 1351);
2062        r
2063    }
2064
2065    #[test]
2066    fn if_button_resolves_interface_component_form() {
2067        let r = seed_registry();
2068        let key = Compiler::compute_lookup_key("if_button", "options:com_14", &r);
2069        let expected = ((261i64 << 16 | 14) * 1024 + 512 + 147) as i32;
2070        assert_eq!(key, expected);
2071        // And the lookup-key wraps to match the engine's
2072        // ServerTriggerType::IfButton::lookup_key_subject(com_hash) where
2073        // com_hash = iface*65536 + comp.
2074        let com_hash = (261i64 << 16 | 14) as i32;
2075        let engine_key = (com_hash as i64 * 1024 + 512 + 147) as i32;
2076        assert_eq!(key, engine_key);
2077    }
2078
2079    #[test]
2080    fn validate_warns_on_unresolved_if_button_subject() {
2081        let r = seed_registry();
2082        // Unknown component name — old bug shape (would silently never dispatch).
2083        let warning =
2084            Compiler::validate_trigger_subject("if_button", "options:com_does_not_exist", &r);
2085        assert!(
2086            warning.is_some(),
2087            "expected a warning for unresolved subject"
2088        );
2089        assert!(warning.unwrap().contains("did not resolve"));
2090    }
2091
2092    #[test]
2093    fn validate_silent_on_resolvable_subject() {
2094        let r = seed_registry();
2095        assert!(Compiler::validate_trigger_subject("if_button", "options:com_14", &r).is_none());
2096        assert!(Compiler::validate_trigger_subject("opnpc1", "man", &r).is_none());
2097        assert!(Compiler::validate_trigger_subject("opheld1", "bronze_axe", &r).is_none());
2098    }
2099
2100    #[test]
2101    fn validate_silent_on_wildcards_and_categories() {
2102        let r = seed_registry();
2103        // Bare `_` — global trigger, no subject.
2104        assert!(Compiler::validate_trigger_subject("opheld1", "_", &r).is_none());
2105        // `_category` form — caller validates separately.
2106        assert!(Compiler::validate_trigger_subject("opheldu", "_alcoholic_drinks", &r).is_none());
2107    }
2108
2109    #[test]
2110    fn validate_silent_on_name_keyed_triggers() {
2111        let r = seed_registry();
2112        // queue/timer/walktrigger/proc are name-keyed; `lookup_key = -1` is correct.
2113        assert!(Compiler::validate_trigger_subject("queue", "my_queue", &r).is_none());
2114        assert!(Compiler::validate_trigger_subject("timer", "my_timer", &r).is_none());
2115        assert!(Compiler::validate_trigger_subject("proc", "my_proc", &r).is_none());
2116    }
2117
2118    #[test]
2119    fn validate_silent_on_coord_triggers() {
2120        let r = seed_registry();
2121        // Coord-shaped names are parsed from the entity string itself.
2122        assert!(Compiler::validate_trigger_subject("zone", "0_50_50_10_10", &r).is_none());
2123    }
2124
2125    #[test]
2126    fn validate_warns_on_unknown_npc_subject() {
2127        let r = seed_registry();
2128        let warning = Compiler::validate_trigger_subject("opnpc1", "not_a_real_npc", &r);
2129        assert!(warning.is_some());
2130    }
2131
2132    #[test]
2133    fn bare_command_sharing_a_trigger_name_compiles_to_the_command() {
2134        // `if_close` is BOTH the close command (opcode 2033) and the
2135        // `[if_close,...]` trigger (byte 148). A bare `if_close` statement must
2136        // compile to the COMMAND. Regression: the trigger byte used to shadow
2137        // the command in general identifier resolution, so `if_close` silently
2138        // compiled to `push_int(148)` and the close was dropped at runtime.
2139        let mut r = seed_registry();
2140        r.register_command("if_close".into(), 2033, vec![], vec![]);
2141        let mut c = Compiler::new(r);
2142        let mut out = CompiledScript::new("t".into(), 0);
2143        let mut locals = SymbolTable::new();
2144        c.compile_expr_hinted(
2145            &Expr::Identifier("if_close".into()),
2146            &mut out,
2147            &mut locals,
2148            None,
2149        );
2150        assert!(
2151            out.instructions
2152                .iter()
2153                .any(|i| i.opcode == Opcode::Command && matches!(i.operand, Operand::Int(2033))),
2154            "bare `if_close` should emit Command(2033), got {:?}",
2155            out.instructions
2156        );
2157        assert!(
2158            !out.instructions
2159                .iter()
2160                .any(|i| matches!(i.operand, Operand::Int(148))),
2161            "bare `if_close` must NOT emit the trigger byte 148: {:?}",
2162            out.instructions
2163        );
2164    }
2165
2166    #[test]
2167    fn test_commands_resolve_names_to_ids_but_only_for_themselves() {
2168        // The name->int resolution is scoped to test_op/wait_for arguments only;
2169        // it must never leak into general identifier resolution.
2170        let mut r = seed_registry();
2171        r.register_command("mes".into(), 2064, vec![Type::String], vec![]);
2172        r.register_command("if_close".into(), 2033, vec![], vec![]);
2173        let c = Compiler::new(r);
2174
2175        // test_op(oploc1, ...): trigger name -> trigger byte (oploc1 = 66).
2176        let mut out = CompiledScript::new("t".into(), 0);
2177        assert!(c.try_emit_test_command_id_arg(
2178            "test_op",
2179            &Expr::Identifier("oploc1".into()),
2180            Some(Type::Int),
2181            &mut out
2182        ));
2183        let last = out.instructions.last().expect("an instruction");
2184        assert!(
2185            matches!(last.operand, Operand::Int(66)),
2186            "got {:?}",
2187            last.operand
2188        );
2189
2190        // wait_for(mes, ...): command name -> command opcode (mes = 2064).
2191        let mut out = CompiledScript::new("t".into(), 0);
2192        assert!(c.try_emit_test_command_id_arg(
2193            "wait_for",
2194            &Expr::Identifier("mes".into()),
2195            Some(Type::Int),
2196            &mut out
2197        ));
2198        let last = out.instructions.last().expect("an instruction");
2199        assert!(
2200            matches!(last.operand, Operand::Int(2064)),
2201            "got {:?}",
2202            last.operand
2203        );
2204
2205        // A NON-test command does not trigger the resolution, so `if_close`
2206        // is left for normal resolution (→ its command opcode) downstream.
2207        let mut out = CompiledScript::new("t".into(), 0);
2208        assert!(!c.try_emit_test_command_id_arg(
2209            "mes",
2210            &Expr::Identifier("if_close".into()),
2211            Some(Type::Int),
2212            &mut out
2213        ));
2214        assert!(out.instructions.is_empty());
2215
2216        // A non-int parameter position is never treated as an id.
2217        let mut out = CompiledScript::new("t".into(), 0);
2218        assert!(!c.try_emit_test_command_id_arg(
2219            "test_op",
2220            &Expr::Identifier("oploc1".into()),
2221            Some(Type::Loc),
2222            &mut out
2223        ));
2224    }
2225}