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