Skip to main content

runec/
compiler.rs

1use crate::arguments::{
2    command_hints, command_parameters, command_returns, expression_types, positional_hints,
3    proc_hints, stack_hints,
4};
5use crate::bytecode::*;
6use crate::clientscript::decompile::inference::written_end;
7use crate::clientscript::hooks;
8use crate::parser::*;
9use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
10use crate::types::{BaseVarType, Type};
11use std::collections::HashMap;
12use std::ops::Range;
13use std::slice::from_ref;
14
15/// Shared lowering for RS2, CS2 and target-selected global sources. Binary
16/// encoding and storage are separate from this phase.
17pub fn compile_file(
18    file: &ScriptFile,
19    label: &std::path::Path,
20    registry: &SymbolRegistry,
21    client: bool,
22    diagnostics: &mut crate::diagnostics::DiagnosticsCollector,
23) -> Vec<CompiledScript> {
24    let mut compiler = Compiler::new(registry);
25    compiler.client = client;
26    let mut compiled = Vec::with_capacity(file.scripts.len());
27    for script in file
28        .scripts
29        .iter()
30        .filter(|script| script.trigger != "command")
31    {
32        if let Some(mut script) = compiler.compile_checked(script, label, diagnostics) {
33            script.source_path = label.to_string_lossy().into_owned();
34            compiled.push(script);
35        }
36    }
37    compiled
38}
39
40/// Code generator that transforms parsed AST into bytecode instructions.
41pub struct Compiler<'a> {
42    pub implicit_return: bool,
43    client: bool,
44    loop_depth: usize,
45    pub errors: Vec<String>,
46    labels: HashMap<String, usize>,
47    label_jumps: Vec<(usize, String)>,
48    label_switches: Vec<(usize, usize, String)>,
49    /// Borrowed read-only during code generation, so many `Compiler`s can share
50    /// one registry across threads (each thread builds its own scratch state).
51    pub registry: &'a SymbolRegistry,
52    /// Return types of the currently-compiling script (used for type hints in return statements).
53    current_return_types: Vec<Type>,
54    stack_returns: bool,
55    /// The line number of the currently-compiling statement.
56    current_stmt_line: usize,
57    trace: Option<Vec<ExpressionTrace>>,
58}
59
60pub(crate) struct ExpressionTrace {
61    pub expression: usize,
62    pub instructions: Range<usize>,
63    pub operation: Option<usize>,
64    pub signature: Option<(Vec<Type>, Vec<Type>)>,
65}
66
67impl<'a> Compiler<'a> {
68    /// Checked emission for hosts that need structured errors rather than a
69    /// partially generated script. The source label is never opened.
70    pub fn compile_checked(
71        &mut self,
72        script: &ScriptDeclaration,
73        label: &std::path::Path,
74        diagnostics: &mut crate::diagnostics::DiagnosticsCollector,
75    ) -> Option<CompiledScript> {
76        let compiled = self.compile_script(script);
77        for error in &self.errors {
78            diagnostics.error(
79                label.to_path_buf(),
80                script.line,
81                0,
82                error.clone(),
83                crate::diagnostics::Phase::CodeGeneration,
84            );
85        }
86        self.errors.is_empty().then_some(compiled)
87    }
88
89    pub fn new(registry: &'a SymbolRegistry) -> Self {
90        Compiler {
91            implicit_return: true,
92            client: false,
93            loop_depth: 0,
94            errors: Vec::new(),
95            labels: HashMap::new(),
96            label_jumps: Vec::new(),
97            label_switches: Vec::new(),
98            registry,
99            current_return_types: Vec::new(),
100            stack_returns: false,
101            current_stmt_line: 0,
102            trace: None,
103        }
104    }
105
106    pub(crate) fn compile_traced(
107        &mut self,
108        script: &ScriptDeclaration,
109        client: bool,
110    ) -> (CompiledScript, Vec<ExpressionTrace>) {
111        self.client = client;
112        self.trace = Some(Vec::new());
113        let compiled = self.compile_script(script);
114        (compiled, self.trace.take().unwrap_or_default())
115    }
116
117    /// Compile a single script declaration into bytecode.
118    pub fn compile_script(&mut self, script: &ScriptDeclaration) -> CompiledScript {
119        self.labels.clear();
120        self.label_jumps.clear();
121        self.label_switches.clear();
122        self.errors.clear();
123        self.loop_depth = 0;
124        let id = self
125            .registry
126            .script_id_for_trigger(&script.trigger, &script.name)
127            .or_else(|| self.registry.script_id(&script.name))
128            .unwrap_or(-1);
129        let full_name = format!("[{},{}]", script.trigger, script.name);
130        let mut compiled = CompiledScript::new(full_name, id);
131        compiled.trigger = script.trigger.clone();
132        compiled.lookup_key =
133            Self::compute_lookup_key(&script.trigger, &script.name, self.registry);
134        compiled.param_types = script.params.iter().map(|p| p.param_type).collect();
135        let mut locals = SymbolTable::new();
136
137        // Register parameters — push to LocalTable AND define in SymbolTable
138        for param in &script.params {
139            let slot = compiled
140                .local_table
141                .push_param(param.name.clone(), param.param_type);
142            locals.define(
143                param.name.clone(),
144                SymbolKind::ScriptParam {
145                    param_type: param.param_type,
146                    slot,
147                },
148            );
149        }
150
151        // Compile body statements
152        self.current_return_types = script.return_types.clone();
153        self.stack_returns = self
154            .registry
155            .stack_scripts
156            .contains(&format!("{}:{}", script.trigger, script.name));
157        for stmt in &script.body {
158            self.compile_statement(stmt, &mut compiled, &mut locals);
159        }
160
161        let written_end = written_end(&script.body, &script.return_types);
162        let implicit_return = self.implicit_return && !(self.client && written_end);
163        for ret_type in script.return_types.iter().filter(|_| implicit_return) {
164            match ret_type.base_type() {
165                BaseVarType::Integer => {
166                    compiled.push(Instruction::push_int(ret_type.default_return_value()))
167                }
168                BaseVarType::String => compiled.push_string(String::new()),
169                BaseVarType::Long => compiled.push(Instruction::push_long(0)),
170            }
171        }
172        if implicit_return {
173            compiled.push(Instruction::simple(Opcode::Return));
174        }
175        for (pc, label) in &self.label_jumps {
176            if let Some(&target) = self.labels.get(label) {
177                compiled.patch_jump(*pc, target);
178            } else {
179                self.errors.push(format!("Unknown label {label}"));
180            }
181        }
182        for (table, case, label) in &self.label_switches {
183            if let Some(&target) = self.labels.get(label) {
184                compiled.switch_tables[*table][*case].1 = target;
185            } else {
186                self.errors.push(format!("Unknown switch label {label}"));
187            }
188        }
189
190        // Set local variable counts from LocalTable (matching TS getLocalCount/getParameterCount)
191        compiled.int_local_count = compiled.local_table.get_local_count(BaseVarType::Integer);
192        compiled.string_local_count = compiled.local_table.get_local_count(BaseVarType::String);
193        compiled.long_local_count = compiled.local_table.get_local_count(BaseVarType::Long);
194        compiled.int_arg_count = compiled.local_table.get_param_count(BaseVarType::Integer);
195        compiled.string_arg_count = compiled.local_table.get_param_count(BaseVarType::String);
196        compiled.long_arg_count = compiled.local_table.get_param_count(BaseVarType::Long);
197
198        compiled
199    }
200
201    fn emit_line(line: usize, out: &mut CompiledScript) {
202        out.push(Instruction::new(
203            Opcode::LineNumber,
204            Operand::Int(line as i32),
205        ));
206    }
207
208    fn emit_arithmetic(&mut self, opcode: Opcode, out: &mut CompiledScript) {
209        let name = match opcode {
210            Opcode::Add => "add",
211            Opcode::Sub => "sub",
212            Opcode::Multiply => "multiply",
213            Opcode::Divide => "divide",
214            Opcode::Modulo => "modulo",
215            Opcode::And => "and",
216            Opcode::Or => "or",
217            _ => unreachable!(),
218        };
219        if let Some(code) = self.registry.command_opcode(name) {
220            out.push(Instruction::new(Opcode::Command, Operand::Int(code)));
221        } else if self.registry.profile.is_some() {
222            self.errors.push(format!(
223                "Arithmetic requires the '{name}' command in the supplied engine profile"
224            ));
225        } else {
226            out.push(Instruction::simple(opcode));
227        }
228    }
229
230    fn emit_comparison_value(
231        branch_opcode: Opcode,
232        fallthrough_value: i32,
233        branch_value: i32,
234        out: &mut CompiledScript,
235    ) {
236        let branch_pos = out.len();
237        out.push(Instruction::new(branch_opcode, Operand::JumpTarget(0)));
238        out.push(Instruction::push_int(fallthrough_value));
239        let jump_pos = out.len();
240        out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
241        let branch_target = out.len();
242        out.push(Instruction::push_int(branch_value));
243        let end_pos = out.len();
244        out.patch_jump(branch_pos, branch_target);
245        out.patch_jump(jump_pos, end_pos);
246    }
247
248    fn compile_statement(
249        &mut self,
250        stmt: &Statement,
251        out: &mut CompiledScript,
252        locals: &mut SymbolTable,
253    ) {
254        // Track the statement's line for re-emission after multi-line call arguments.
255        match stmt {
256            Statement::VarDeclaration { line, .. }
257            | Statement::ArrayDeclaration { line, .. }
258            | Statement::Assignment { line, .. }
259            | Statement::If { line, .. }
260            | Statement::While { line, .. }
261            | Statement::Switch { line, .. }
262            | Statement::Return { line, .. }
263            | Statement::Expression { line, .. }
264            | Statement::OrphanCase { line, .. } => {
265                self.current_stmt_line = *line;
266            }
267            Statement::Empty => {}
268        }
269        match stmt {
270            Statement::VarDeclaration {
271                var_type,
272                name,
273                value,
274                line,
275            } => {
276                // Push to LocalTable for slot assignment (matching TS locals.all.push)
277                let slot = out.local_table.push_local(name.clone(), *var_type, false);
278                // Also define in SymbolTable for scoped name resolution
279                locals.define(
280                    name.clone(),
281                    SymbolKind::LocalVar {
282                        var_type: *var_type,
283                        slot,
284                        is_array: false,
285                    },
286                );
287
288                if self.client
289                    && self.loop_depth == 0
290                    && value.is_none()
291                    && (var_type.base_type() == BaseVarType::Long
292                        || (var_type.base_type() == BaseVarType::Integer
293                            && var_type.default_int_value() == 0))
294                {
295                    return;
296                }
297
298                if let Some(init) = value {
299                    // With initial value: LineNumber BEFORE the expression.
300                    // The arg-based LineNumber emission in calls may override this via writer
301                    // deduplication (same-PC rule keeps the last line number).
302                    Self::emit_line(*line, out);
303                    // Use the declared var type as a hint so identifiers resolve to the
304                    // correct entity ID (e.g. `def_npc_stat $x = magic` → npc_stat id=5, not stat id=6).
305                    self.compile_expr_hinted(init, out, locals, Some(*var_type));
306                    // Emit LineNumber(stmt_line) again before the pop instruction.
307                    // For multi-line init calls, this re-anchors the pop to the statement's line.
308                    // Writer deduplication handles same-line cases (no extra entry emitted).
309                    Self::emit_line(*line, out);
310                } else {
311                    // No initial value: Java pushes default BEFORE the LineNumber
312                    match var_type.base_type() {
313                        BaseVarType::Integer => {
314                            out.push(Instruction::push_int(var_type.default_int_value()))
315                        }
316                        BaseVarType::String => out.push_string(String::new()),
317                        BaseVarType::Long => out.push(Instruction::push_long(0)),
318                    }
319                    Self::emit_line(*line, out);
320                }
321
322                // Pop into local variable slot
323                let pop_opcode = match var_type.base_type() {
324                    BaseVarType::Integer => Opcode::PopIntLocal,
325                    BaseVarType::String => Opcode::PopStringLocal,
326                    BaseVarType::Long => Opcode::PopLongLocal,
327                };
328                out.push(Instruction::new(pop_opcode, Operand::Int(slot)));
329            }
330
331            Statement::ArrayDeclaration {
332                element_type,
333                name,
334                size,
335                line,
336            } => {
337                Self::emit_line(*line, out);
338                let slot = locals
339                    .lookup(name)
340                    .and_then(|symbol| {
341                        if let SymbolKind::LocalVar {
342                            slot,
343                            is_array: true,
344                            ..
345                        } = symbol.kind
346                        {
347                            Some(slot)
348                        } else {
349                            None
350                        }
351                    })
352                    .unwrap_or_else(|| {
353                        let slot = out
354                            .local_table
355                            .push_local(name.clone(), *element_type, true);
356                        match array_name(name) {
357                            Some((_, number)) => number,
358                            _ => slot,
359                        }
360                    });
361                if !(0..5).contains(&slot) {
362                    self.errors.push(format!(
363                        "Array '${name}' uses slot {slot}; only array slots 0 through 4 are available."
364                    ));
365                }
366                locals.define(
367                    name.clone(),
368                    SymbolKind::LocalVar {
369                        var_type: *element_type,
370                        slot,
371                        is_array: true,
372                    },
373                );
374
375                if matches!(size, Expr::NullLiteral) {
376                    return;
377                }
378                // Push array size
379                self.compile_expr(size, out, locals);
380
381                // Emit define array
382                let type_char = element_type.to_char() as u8;
383                out.push(Instruction::new(
384                    Opcode::DefineArray,
385                    Operand::ArrayDef(slot, type_char),
386                ));
387
388                let _ = line;
389            }
390
391            Statement::Assignment {
392                target,
393                value,
394                line,
395            } => {
396                Self::emit_line(*line, out);
397                // Infer the target type to use as a hint when compiling the value.
398                let target_type_hint = self.infer_target_type(target, locals);
399                if let Expr::ArrayAccess { name, index } = target {
400                    self.compile_expr(index, out, locals);
401                    self.compile_expr_hinted(value, out, locals, target_type_hint);
402                    if let Some(symbol) = locals.lookup(name)
403                        && let SymbolKind::LocalVar { slot, .. } = symbol.kind
404                    {
405                        out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
406                    }
407                    return;
408                }
409                if let Expr::Tuple(values) = value {
410                    let targets = match target {
411                        Expr::MultiAssign(targets, _) => targets.as_slice(),
412                        _ => from_ref(target),
413                    };
414                    let types: Vec<_> = targets
415                        .iter()
416                        .filter_map(|target| self.infer_target_type(target, locals))
417                        .collect();
418                    let hints = stack_hints(self.registry, &types, values, locals);
419                    for (value, hint) in values.iter().zip(hints) {
420                        self.compile_expr_hinted(value, out, locals, hint);
421                    }
422                } else {
423                    self.compile_expr_hinted(value, out, locals, target_type_hint);
424                }
425                self.compile_store(target, out, locals);
426            }
427
428            Statement::If {
429                condition,
430                body,
431                else_if,
432                else_body,
433                else_line,
434                line,
435            } => {
436                Self::emit_line(*line, out);
437                self.compile_if(condition, body, else_if, else_body, *else_line, out, locals);
438            }
439
440            Statement::While {
441                condition,
442                body,
443                line,
444            } => {
445                Self::emit_line(*line, out);
446                let loop_start = out.len();
447
448                // Java pattern: BranchTrue(body) + Branch(exit) before body
449                let (true_positions, false_positions) =
450                    self.compile_condition(condition, out, locals);
451
452                // Patch true branches to body_start
453                let body_start = out.len();
454                for pos in &true_positions {
455                    out.patch_jump(*pos, body_start);
456                }
457
458                // Compile body
459                self.loop_depth += 1;
460                for s in body {
461                    self.compile_statement(s, out, locals);
462                }
463                self.loop_depth -= 1;
464
465                // Jump back to loop start
466                out.push(Instruction::new(
467                    Opcode::Branch,
468                    Operand::JumpTarget(loop_start),
469                ));
470
471                // Patch false branches to exit
472                let exit_pos = out.len();
473                for pos in &false_positions {
474                    out.patch_jump(*pos, exit_pos);
475                }
476            }
477
478            Statement::Switch {
479                switch_type,
480                expr,
481                cases,
482                default,
483                default_index,
484                line,
485            } => {
486                Self::emit_line(*line, out);
487                self.compile_switch(
488                    switch_type,
489                    expr,
490                    cases,
491                    default,
492                    *default_index,
493                    out,
494                    locals,
495                );
496            }
497
498            Statement::Return { values, line } => {
499                Self::emit_line(*line, out);
500                let return_types = self.current_return_types.clone();
501                let hints = if self.stack_returns {
502                    positional_hints(self.registry, &return_types, values, locals)
503                } else {
504                    (0..values.len())
505                        .map(|i| return_types.get(i).copied())
506                        .collect()
507                };
508                for (val, hint) in values.iter().zip(hints) {
509                    self.compile_expr_hinted(val, out, locals, hint);
510                }
511                out.push(Instruction::simple(Opcode::Return));
512            }
513
514            Statement::Expression { expr, line } => {
515                let trace_start = out.len();
516                // Java compiler behavior: for CommandCall expressions, leading ConstantVar
517                // args that resolve to strings are pushed BEFORE the LineNumber instruction.
518                let cmd_args_offset = if let Expr::CommandCall { name, args, .. } = expr {
519                    let n = self.count_pre_stmt_string_args(name, args);
520                    if n > 0 {
521                        // The reference compiler emits LineNumber(stmt_line - 1) before the
522                        // pre-stmt string args, but ONLY when the first pre-stmt arg is a
523                        // string constant (^name). Null literals and string literals don't
524                        // trigger the line-1 emission.
525                        let first_is_const = matches!(&args[0], Expr::ConstantVar(..));
526                        if first_is_const && *line > 1 {
527                            Self::emit_line(*line - 1, out);
528                        }
529                        let lookup = name.strip_prefix('.').unwrap_or(name);
530                        let ptypes: Vec<Type> = self
531                            .registry
532                            .command_param_types
533                            .get(lookup)
534                            .cloned()
535                            .unwrap_or_default();
536                        for (j, arg) in args[..n].iter().enumerate() {
537                            let hint = ptypes.get(j).copied();
538                            self.compile_expr_hinted(arg, out, locals, hint);
539                        }
540                    }
541                    n
542                } else {
543                    0
544                };
545                Self::emit_line(*line, out);
546                if cmd_args_offset > 0 {
547                    if let Expr::CommandCall {
548                        name,
549                        args,
550                        arg_lines,
551                        call_line: _,
552                    } = expr
553                    {
554                        self.compile_command_call_args_from(
555                            name,
556                            args,
557                            arg_lines,
558                            cmd_args_offset,
559                            out,
560                            locals,
561                        );
562                        self.trace_expression(expr, trace_start, out, locals);
563                    }
564                } else {
565                    self.compile_expr(expr, out, locals);
566                }
567                // If the expression is a proc/label call that returns values in statement
568                // context (unused), Java emits POP_INT/STRING_DISCARD for each return value.
569                let return_types: Option<Vec<Type>> = match expr {
570                    Expr::ProcCall { name, .. } => self
571                        .registry
572                        .lookup_script_by_trigger("proc", name)
573                        .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name))
574                        .and_then(|sym| {
575                            if let SymbolKind::Script { return_types, .. } = &sym.kind {
576                                Some(return_types.clone())
577                            } else {
578                                None
579                            }
580                        }),
581                    Expr::JumpCall { name, .. } => self
582                        .registry
583                        .lookup_script_by_trigger("label", name)
584                        .and_then(|sym| {
585                            if let SymbolKind::Script { return_types, .. } = &sym.kind {
586                                Some(return_types.clone())
587                            } else {
588                                None
589                            }
590                        }),
591                    Expr::CommandCall { name, args, .. } => {
592                        Some(command_returns(self.registry, name, args))
593                    }
594                    Expr::Identifier(name) => Some(command_returns(self.registry, name, &[])),
595                    _ => None,
596                };
597                if let Some(mut ret_types) = return_types {
598                    // A client script drops a call's values a stack at a time.
599                    if self.client {
600                        ret_types.sort_by_key(|ty| match ty.base_type() {
601                            BaseVarType::Integer => 0,
602                            BaseVarType::String => 1,
603                            BaseVarType::Long => 2,
604                        });
605                    }
606                    for ret_type in ret_types.iter().rev() {
607                        match ret_type.base_type() {
608                            BaseVarType::Integer => {
609                                out.push(Instruction::simple(Opcode::PopIntDiscard))
610                            }
611                            BaseVarType::String => {
612                                out.push(Instruction::simple(Opcode::PopStringDiscard))
613                            }
614                            BaseVarType::Long => {
615                                out.push(Instruction::simple(Opcode::PopLongDiscard))
616                            }
617                        }
618                    }
619                }
620            }
621            Statement::OrphanCase { .. } => {}
622            Statement::Empty => {}
623        }
624    }
625
626    #[allow(clippy::too_many_arguments, clippy::only_used_in_recursion)]
627    fn compile_if(
628        &mut self,
629        condition: &Expr,
630        body: &[Statement],
631        else_if: &[(Expr, Vec<Statement>, usize)],
632        else_body: &Option<Vec<Statement>>,
633        else_line: usize,
634        out: &mut CompiledScript,
635        locals: &mut SymbolTable,
636    ) {
637        let mut end_jumps = Vec::new();
638
639        // Java pattern: BranchTrue(body) + Branch(else/end)
640        let (true_positions, false_positions) = self.compile_condition(condition, out, locals);
641
642        // Patch true branches to body_start
643        let body_start = out.len();
644        for pos in &true_positions {
645            out.patch_jump(*pos, body_start);
646        }
647
648        // Compile if body
649        for s in body {
650            self.compile_statement(s, out, locals);
651        }
652
653        if !else_if.is_empty() || else_body.is_some() {
654            let end_jump_pos = out.len();
655            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
656            end_jumps.push(end_jump_pos);
657        }
658
659        // Patch false branches to else_start (right after body's Branch)
660        let else_start = out.len();
661        for pos in &false_positions {
662            out.patch_jump(*pos, else_start);
663        }
664
665        if !else_if.is_empty() {
666            // Java compiles else-if as nested: else { if (cond) { ... } else if ... }
667            // Each nesting level adds one extra Branch wrapper at the end.
668            let (first_cond, first_body, first_line) = &else_if[0];
669            let remaining = &else_if[1..];
670            // Emit line number for the else-if condition (Java does this)
671            Self::emit_line(*first_line, out);
672            self.compile_if(
673                first_cond, first_body, remaining, else_body, else_line, out, locals,
674            );
675        } else if let Some(else_stmts) = else_body {
676            // Plain else body
677            for s in else_stmts {
678                self.compile_statement(s, out, locals);
679            }
680        }
681
682        // Patch all end-jumps to here
683        let end_pos = out.len();
684        for pos in end_jumps {
685            out.patch_jump(pos, end_pos);
686        }
687    }
688
689    /// Count how many leading args are string-type expressions that should be pushed
690    /// BEFORE LineNumber in statement context (Neptune behavior).
691    /// This includes: string constants (^name), string literals, and null literals
692    /// when the command parameter type is string.
693    fn count_pre_stmt_string_args(&self, name: &str, args: &[Expr]) -> usize {
694        // Look up command parameter types to determine if null args are string-typed
695        let lookup_name = name.strip_prefix('.').unwrap_or(name);
696        let param_types: Vec<Type> = self
697            .registry
698            .command_param_types
699            .get(lookup_name)
700            .cloned()
701            .unwrap_or_default();
702
703        let mut count = 0;
704        for (i, arg) in args.iter().enumerate() {
705            let is_string_param = param_types
706                .get(i)
707                .map(|t| t.base_type() == crate::types::BaseVarType::String)
708                .unwrap_or(false);
709
710            match arg {
711                Expr::ConstantVar(cname, _) => {
712                    if let Some(sym) = self.registry.lookup_constant(cname)
713                        && let SymbolKind::Constant {
714                            string_value: Some(_),
715                            ..
716                        } = &sym.kind
717                    {
718                        count += 1;
719                        continue;
720                    }
721                    break;
722                }
723                Expr::NullLiteral if is_string_param => {
724                    count += 1;
725                    continue;
726                }
727                _ => break,
728            }
729        }
730        count
731    }
732
733    /// Test-harness commands (`test_op`, `wait_for`) accept a bare trigger or
734    /// command NAME in an `int` parameter and want it lowered to the trigger
735    /// byte / command opcode (e.g. `test_op(oploc1, ...)` → byte,
736    /// `wait_for(mes, ...)` → opcode). This is scoped to those commands ONLY,
737    /// so general identifier resolution is unchanged from pre-test behavior — a
738    /// command that shares a trigger's name (e.g. `if_close`) still compiles to
739    /// its command opcode everywhere else. Returns true (and emits the push) if
740    /// `arg` was handled here.
741    fn try_emit_test_command_id_arg(
742        &self,
743        lookup_name: &str,
744        arg: &Expr,
745        hint: Option<Type>,
746        out: &mut CompiledScript,
747    ) -> bool {
748        if !matches!(lookup_name, "test_op" | "wait_for") || hint != Some(Type::Int) {
749            return false;
750        }
751        let Expr::Identifier(ident) = arg else {
752            return false;
753        };
754        if ident.contains(':') {
755            return false;
756        }
757        if let Some(trigger_byte) = self
758            .registry
759            .trigger(ident)
760            .and_then(|trigger| trigger.byte)
761        {
762            out.push(Instruction::push_int(trigger_byte as i32));
763            return true;
764        }
765        if let Some(sym) = self
766            .registry
767            .lookup_command(ident.strip_prefix('.').unwrap_or(ident))
768            && let SymbolKind::Command { opcode, .. } = &sym.kind
769        {
770            let opcode = *opcode;
771            out.push(Instruction::push_int(opcode));
772            return true;
773        }
774        false
775    }
776
777    /// Compile a CommandCall expression starting at `args_start` (skipping already-pushed args).
778    fn compile_command_call_args_from(
779        &mut self,
780        name: &str,
781        args: &[Expr],
782        arg_lines: &[usize],
783        args_start: usize,
784        out: &mut CompiledScript,
785        locals: &mut SymbolTable,
786    ) {
787        let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
788            (stripped, 1u8)
789        } else {
790            (name, 0u8)
791        };
792        let param_types: Vec<Type> = self
793            .registry
794            .command_param_types
795            .get(lookup_name)
796            .cloned()
797            .unwrap_or_default();
798        let script_trigger = Self::command_script_trigger(lookup_name);
799        let variadic_info = Self::command_variadic_info(lookup_name);
800
801        for (i, arg) in args.iter().enumerate() {
802            if i < args_start {
803                continue;
804            }
805            if let Some(&al) = arg_lines.get(i)
806                && al > 0
807            {
808                Self::emit_line(al, out);
809            }
810            if i == 0
811                && let Some(trigger) = script_trigger
812                && let Expr::Identifier(script_name) = arg
813            {
814                let script_id = self
815                    .registry
816                    .script_id_for_trigger(trigger, script_name)
817                    .or_else(|| self.registry.proc_script_id(script_name))
818                    .or_else(|| self.registry.script_id(script_name))
819                    .unwrap_or(-1);
820                out.push(Instruction::push_int(script_id));
821                continue;
822            }
823            let hint = param_types.get(i).copied();
824            if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
825                continue;
826            }
827            self.compile_expr_hinted(arg, out, locals, hint);
828        }
829
830        if let Some(fixed_arg_count) = variadic_info {
831            let variadic_args = if args.len() > fixed_arg_count {
832                &args[fixed_arg_count..]
833            } else {
834                &[]
835            };
836            let type_desc: String = variadic_args
837                .iter()
838                .map(|arg| self.infer_type_char(arg, locals))
839                .collect();
840            out.push_string(type_desc);
841        }
842
843        let cmd_sym = self
844            .registry
845            .lookup_command(lookup_name)
846            .or_else(|| {
847                lookup_name.strip_suffix('*').and_then(|base| {
848                    let vararg_name = format!("{}vararg", base);
849                    self.registry.lookup_command(&vararg_name)
850                })
851            })
852            .cloned();
853        if let Some(sym) = cmd_sym {
854            if let SymbolKind::Command { opcode, .. } = &sym.kind {
855                let encoded = opcode | ((cmd_index as i32) << 16);
856                out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
857            }
858        } else {
859            let cmd_name_idx = out.intern_str(name.to_string());
860            out.push(Instruction::new(
861                Opcode::Command,
862                Operand::Str(cmd_name_idx),
863            ));
864        }
865    }
866
867    /// Compile a condition expression emitting Java-style BranchTrue + Branch pair.
868    /// Returns (true_branch_positions, false_branch_positions):
869    ///   true_branch_positions  = indices of BranchXxx instructions that jump to the body
870    ///   false_branch_positions = indices of Branch instructions that jump to the else/end
871    fn compile_condition(
872        &mut self,
873        condition: &Expr,
874        out: &mut CompiledScript,
875        locals: &mut SymbolTable,
876    ) -> (Vec<usize>, Vec<usize>) {
877        match condition {
878            Expr::BinaryOp { op, lhs, rhs } => {
879                // Infer lhs type to use as hint for rhs (type-aware entity ID resolution).
880                let lhs_type_hint = self.infer_type(lhs, locals);
881                self.compile_expr(lhs, out, locals);
882                let rhs_start = out.len();
883                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
884
885                // The client's compiler turns any `= 0` or `= 1` into these
886                // branches, whatever the type, and never does for `!`.
887                let shortens = if self.client {
888                    *op == BinOp::Eq
889                } else {
890                    matches!(rhs.as_ref(), Expr::BoolLiteral(_))
891                        && matches!(op, BinOp::Eq | BinOp::NotEq)
892                };
893                if shortens
894                    && let [
895                        Instruction {
896                            opcode: Opcode::PushConstantInt,
897                            operand: Operand::Int(value @ (0 | 1)),
898                        },
899                    ] = &out.instructions[rhs_start..]
900                {
901                    let opcode = if *value == 1 {
902                        Opcode::BranchIfTrue
903                    } else {
904                        Opcode::BranchIfFalse
905                    };
906                    out.instructions.pop();
907                    let equal = out.len();
908                    out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
909                    let unequal = out.len();
910                    out.push(Instruction::jump(0));
911                    return if *op == BinOp::Eq {
912                        (vec![equal], vec![unequal])
913                    } else {
914                        (vec![unequal], vec![equal])
915                    };
916                }
917
918                // Emit positive branch (branch-if-true to body)
919                let opcode = Self::comparison_opcode(*op, lhs_type_hint);
920                let true_pos = out.len();
921                out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
922
923                // Emit unconditional branch (fallthrough to else/end)
924                let false_pos = out.len();
925                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
926
927                (vec![true_pos], vec![false_pos])
928            }
929
930            Expr::LogicalOp {
931                op,
932                lhs,
933                rhs,
934                rhs_line,
935            } => {
936                match op {
937                    LogicOp::And => {
938                        // Short-circuit AND: if lhs is true continue to rhs, else → else/end
939                        let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
940
941                        // Patch lhs_true branches to rhs_start
942                        let rhs_start = out.len();
943                        for pos in &lhs_true {
944                            out.patch_jump(*pos, rhs_start);
945                        }
946
947                        // Emit LineNumber for RHS if it starts on a different line.
948                        // Writer deduplication handles same-line cases.
949                        Self::emit_line(*rhs_line, out);
950                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
951
952                        // Combined: body reached only if rhs also true
953                        // false paths: either lhs false OR rhs false
954                        let mut false_branches = lhs_false;
955                        false_branches.extend(rhs_false);
956                        (rhs_true, false_branches)
957                    }
958                    LogicOp::Or => {
959                        // Short-circuit OR: if lhs is true → body, else check rhs
960                        let (lhs_true, mut lhs_false) = self.compile_condition(lhs, out, locals);
961                        if lhs_false.last().copied() == Some(out.len() - 1) {
962                            out.instructions.pop();
963                            lhs_false.pop();
964                        }
965
966                        // Patch lhs_false branches to rhs_start
967                        let rhs_start = out.len();
968                        for pos in &lhs_false {
969                            out.patch_jump(*pos, rhs_start);
970                        }
971
972                        // Emit LineNumber for RHS if it starts on a different line.
973                        Self::emit_line(*rhs_line, out);
974                        let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
975
976                        // Combined: body reached if lhs true OR rhs true
977                        let mut true_branches = lhs_true;
978                        true_branches.extend(rhs_true);
979                        (true_branches, rhs_false)
980                    }
981                }
982            }
983
984            // For any other expression, push value and 0, branch if value != 0 (true)
985            _ => {
986                self.compile_expr(condition, out, locals);
987
988                let true_pos = out.len();
989                out.push(Instruction::new(
990                    Opcode::BranchIfTrue,
991                    Operand::JumpTarget(0),
992                ));
993
994                let false_pos = out.len();
995                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
996
997                (vec![true_pos], vec![false_pos])
998            }
999        }
1000    }
1001
1002    #[allow(clippy::too_many_arguments)]
1003    fn compile_switch(
1004        &mut self,
1005        switch_type: &str,
1006        expr: &Expr,
1007        cases: &[SwitchCase],
1008        default: &Option<Vec<Statement>>,
1009        default_index: usize,
1010        out: &mut CompiledScript,
1011        locals: &mut SymbolTable,
1012    ) {
1013        self.compile_expr(expr, out, locals);
1014        // Parse switch type to get type hint for case value resolution.
1015        let case_type_hint =
1016            Type::from_name(switch_type.strip_prefix("switch_").unwrap_or(switch_type));
1017
1018        // Emit SWITCH instruction (table to be filled in later)
1019        let switch_idx = out.len();
1020        let switch_tbl_idx = out.switch_tables.len() as u32;
1021        out.switch_tables.push(Box::default());
1022        out.push(Instruction::new(
1023            Opcode::Switch,
1024            Operand::SwitchTable(switch_tbl_idx),
1025        ));
1026
1027        // Layout (matches reference compiler):
1028        //
1029        //   default_index == 0 (default appeared FIRST):
1030        //     [Switch]          ← on no-match, falls through to sw_pos+1 = default body
1031        //     [default body]    ← at sw_pos+1
1032        //     [Branch(end)]
1033        //     [case_0 body]     ← switch table points here
1034        //     [Branch(end)]
1035        //     ...
1036        //     [end_pos]
1037        //
1038        //   default_index > 0 (default appeared after some/all cases, or absent):
1039        //     [Switch]          ← on no-match, falls through to sw_pos+1 = Branch
1040        //     [Branch(to_default_or_end)]  ← at sw_pos+1
1041        //     [case_0 body]
1042        //     [Branch(end)]
1043        //     ...
1044        //     [default body]    ← emitted at source position among cases
1045        //     [Branch(end)]
1046        //     ...
1047        //     [end_pos]
1048
1049        let mut end_jumps = Vec::new();
1050        // position of the no-match Branch (when default is not first)
1051        let default_first = default_index == 0 && default.is_some();
1052
1053        let default_branch_pos = if cases.is_empty() && default.is_none() {
1054            // An empty switch only consumes its value: nothing follows it to skip.
1055            None
1056        } else if default_first {
1057            // Default body at sw_pos+1 (direct fall-through, no Branch needed at sw_pos+1)
1058            if let Some(default_stmts) = default {
1059                for s in default_stmts {
1060                    self.compile_statement(s, out, locals);
1061                }
1062                let jump_pos = out.len();
1063                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
1064                end_jumps.push(jump_pos);
1065            }
1066            None
1067        } else {
1068            // Branch at sw_pos+1 (to skip cases and reach default, or to end if no default)
1069            let pos = out.len();
1070            out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
1071            Some(pos)
1072        };
1073
1074        // Compile case bodies in source order, inserting default at its original position
1075        let mut case_positions: Vec<(Vec<i32>, usize)> = Vec::new();
1076        let mut default_body_pos = 0usize;
1077
1078        for (i, case) in cases.iter().enumerate() {
1079            // If default appeared at this position (and wasn't first), emit it now
1080            if !default_first && i == default_index {
1081                default_body_pos = out.len();
1082                if let Some(default_stmts) = default {
1083                    for s in default_stmts {
1084                        self.compile_statement(s, out, locals);
1085                    }
1086                    let jump_pos = out.len();
1087                    out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
1088                    end_jumps.push(jump_pos);
1089                }
1090            }
1091
1092            let body_start = out.len();
1093            let mut values = Vec::new();
1094            for val in &case.values {
1095                if let Expr::IntLiteral(n) = val {
1096                    values.push(*n);
1097                } else if let Expr::BoolLiteral(value) = val {
1098                    values.push(i32::from(*value));
1099                } else if let Expr::NullLiteral = val {
1100                    values.push(-1);
1101                } else if let Expr::StringLiteral(name) = val {
1102                    if let Some(id) =
1103                        case_type_hint.and_then(|ty| self.registry.lookup_reference(name, ty))
1104                    {
1105                        values.push(id);
1106                    }
1107                } else if let Expr::ConstantVar(cname, _) = val {
1108                    // Resolve constant to integer for switch case value
1109                    if let Some(sym) = self.registry.constants.get(cname)
1110                        && let SymbolKind::Constant {
1111                            int_value: Some(value),
1112                            ..
1113                        } = &sym.kind
1114                    {
1115                        values.push(*value);
1116                    }
1117                } else if let Expr::Identifier(ident) = val {
1118                    // Component reference: interface:component → packed hash
1119                    let mut resolved = false;
1120                    if let Some((iface_name, comp_name)) = ident.split_once(':')
1121                        && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
1122                    {
1123                        values.push(packed);
1124                        resolved = true;
1125                    }
1126                    // Use switch type hint for type-aware resolution
1127                    if !resolved
1128                        && let Some(hint) = case_type_hint
1129                        && let Some(id) = self.registry.lookup_reference(ident, hint)
1130                    {
1131                        values.push(id);
1132                        resolved = true;
1133                    }
1134                    if !resolved {
1135                        if let Some(e) = self
1136                            .registry
1137                            .entity_ids
1138                            .get(ident.as_str())
1139                            .and_then(|en| en.primary)
1140                        {
1141                            values.push(e.id);
1142                        } else if let Some(sym) = self.registry.constants.get(ident.as_str())
1143                            && let SymbolKind::Constant {
1144                                int_value: Some(value),
1145                                ..
1146                            } = &sym.kind
1147                        {
1148                            values.push(*value);
1149                        }
1150                    }
1151                } else if let Expr::BinaryOp {
1152                    op: BinOp::Add,
1153                    lhs,
1154                    rhs,
1155                } = val
1156                {
1157                    // Handle entity names containing '+' (e.g. cheese+tom_batta)
1158                    if let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1159                        (lhs.as_ref(), rhs.as_ref())
1160                    {
1161                        let combined = format!("{}+{}", lhs_name, rhs_name);
1162                        if let Some(hint) = case_type_hint {
1163                            if let Some(id) = self.registry.lookup_entity_id_typed(&combined, hint)
1164                            {
1165                                values.push(id);
1166                            }
1167                        } else if let Some(e) = self.registry.lookup_entity_id(&combined) {
1168                            values.push(e.id);
1169                        }
1170                    }
1171                } else if let Expr::CoordLiteral(v) = val {
1172                    values.push(*v);
1173                }
1174            }
1175            case_positions.push((values, body_start));
1176
1177            for s in &case.body {
1178                self.compile_statement(s, out, locals);
1179            }
1180
1181            if i + 1 < cases.len() || (default.is_some() && default_index == cases.len()) {
1182                let jump_pos = out.len();
1183                out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
1184                end_jumps.push(jump_pos);
1185            }
1186        }
1187
1188        // If default appeared after ALL explicit cases (default_index == cases.len()), emit it now
1189        if !default_first && default_index >= cases.len() {
1190            default_body_pos = out.len();
1191            if let Some(default_stmts) = default {
1192                for s in default_stmts {
1193                    self.compile_statement(s, out, locals);
1194                }
1195            }
1196        }
1197
1198        let end_pos = out.len();
1199
1200        // Patch the no-match Branch (when default is not first)
1201        if let Some(dbp) = default_branch_pos {
1202            let default_target = if default.is_some() {
1203                default_body_pos
1204            } else {
1205                end_pos
1206            };
1207            out.patch_jump(dbp, default_target);
1208        }
1209
1210        // Build the switch table with body positions
1211        let mut table = Vec::new();
1212        for (values, pos) in &case_positions {
1213            for &v in values {
1214                table.push((v, *pos));
1215            }
1216        }
1217
1218        // Update the SWITCH instruction with the complete table
1219        if let Operand::SwitchTable(tbl_idx) = out.instructions[switch_idx].operand {
1220            out.switch_tables[tbl_idx as usize] = table.into_boxed_slice();
1221        }
1222
1223        // Patch end-of-case jumps to end_pos
1224        for pos in end_jumps {
1225            out.patch_jump(pos, end_pos);
1226        }
1227    }
1228
1229    fn compile_expr(&mut self, expr: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
1230        self.compile_expr_hinted(expr, out, locals, None);
1231    }
1232
1233    fn compile_expr_hinted(
1234        &mut self,
1235        expr: &Expr,
1236        out: &mut CompiledScript,
1237        locals: &mut SymbolTable,
1238        type_hint: Option<Type>,
1239    ) {
1240        let start = out.len();
1241        self.compile_expr_hinted_inner(expr, out, locals, type_hint);
1242        self.trace_expression(expr, start, out, locals);
1243    }
1244
1245    fn trace_expression(
1246        &mut self,
1247        expr: &Expr,
1248        start: usize,
1249        out: &CompiledScript,
1250        locals: &SymbolTable,
1251    ) {
1252        if self.trace.is_none() {
1253            return;
1254        }
1255        let (operation, signature) = match expr {
1256            Expr::CommandCall {
1257                name,
1258                args,
1259                call_line,
1260                ..
1261            } => {
1262                let server = hooks::server_call(self.registry, name, args, locals, *call_line)
1263                    .ok()
1264                    .flatten();
1265                let (name, args) = match &server {
1266                    Some(Expr::CommandCall { name, args, .. }) => (name, args),
1267                    _ => (name, args),
1268                };
1269                let name = name.trim_start_matches('.');
1270                let lowered = hooks::lower(self.registry, name, args, locals, *call_line)
1271                    .ok()
1272                    .flatten();
1273                let args = lowered.as_deref().unwrap_or(args);
1274                let symbol = self.registry.lookup_command(name).or_else(|| {
1275                    name.strip_suffix('*')
1276                        .and_then(|base| self.registry.lookup_command(&format!("{base}vararg")))
1277                });
1278                let signature = symbol.and_then(|symbol| {
1279                    let mut params = command_parameters(self.registry, name, args, locals);
1280                    let mut returns = command_returns(self.registry, name, args);
1281                    if self.registry.lookup_command(name).is_none()
1282                        && let SymbolKind::Command {
1283                            param_types,
1284                            return_types,
1285                            ..
1286                        } = &symbol.kind
1287                    {
1288                        params = param_types.clone();
1289                        returns = return_types.clone();
1290                    }
1291                    // An empty server signature accepts arbitrary arguments; it
1292                    // is not evidence that the VM command consumes no values.
1293                    if params.is_empty() && !args.is_empty() {
1294                        return None;
1295                    }
1296                    if let Some(fixed) = Self::command_variadic_info(name) {
1297                        if params.len() < fixed {
1298                            return None;
1299                        }
1300                        params.truncate(fixed);
1301                        params.extend(
1302                            args.iter()
1303                                .skip(fixed)
1304                                .flat_map(|arg| expression_types(arg, self.registry, locals)),
1305                        );
1306                        params.push(Type::String);
1307                    }
1308                    if matches!(name, "db_find" | "db_find_refine") {
1309                        params.push(Type::Int);
1310                    }
1311                    if params
1312                        .iter()
1313                        .chain(&returns)
1314                        .any(|ty| matches!(ty, Type::Any | Type::Error))
1315                    {
1316                        return None;
1317                    }
1318                    Some((params, returns))
1319                });
1320                (
1321                    (!name.starts_with("__")).then_some(Opcode::Command),
1322                    signature,
1323                )
1324            }
1325            Expr::Identifier(name) => {
1326                let Some(symbol) = self.registry.lookup_command(name.trim_start_matches('.'))
1327                else {
1328                    return;
1329                };
1330                let SymbolKind::Command {
1331                    param_types,
1332                    return_types,
1333                    ..
1334                } = &symbol.kind
1335                else {
1336                    return;
1337                };
1338                if !out
1339                    .instructions
1340                    .last()
1341                    .is_some_and(|i| i.opcode == Opcode::Command)
1342                {
1343                    return;
1344                }
1345                (
1346                    Some(Opcode::Command),
1347                    Some((param_types.clone(), return_types.clone())),
1348                )
1349            }
1350            Expr::ProcCall { name, .. } | Expr::JumpCall { name, .. } => {
1351                let jump = matches!(expr, Expr::JumpCall { .. });
1352                let symbol = self
1353                    .registry
1354                    .lookup_script_by_trigger(if jump { "label" } else { "proc" }, name)
1355                    .or_else(|| {
1356                        (!jump)
1357                            .then(|| self.registry.lookup_script_by_trigger("clientscript", name))
1358                            .flatten()
1359                    });
1360                let signature = symbol.and_then(|symbol| match &symbol.kind {
1361                    SymbolKind::Script {
1362                        param_types,
1363                        return_types,
1364                        ..
1365                    } => Some((
1366                        param_types.clone(),
1367                        if jump {
1368                            Vec::new()
1369                        } else {
1370                            return_types.clone()
1371                        },
1372                    )),
1373                    _ => None,
1374                });
1375                (
1376                    Some(if jump {
1377                        Opcode::JumpWithParams
1378                    } else {
1379                        Opcode::GosubWithParams
1380                    }),
1381                    signature,
1382                )
1383            }
1384            _ => return,
1385        };
1386        let operation = out
1387            .instructions
1388            .len()
1389            .checked_sub(1)
1390            .filter(|&pc| pc >= start && Some(out.instructions[pc].opcode) == operation);
1391        self.trace.as_mut().unwrap().push(ExpressionTrace {
1392            expression: expr as *const Expr as usize,
1393            instructions: start..out.len(),
1394            operation,
1395            signature,
1396        });
1397    }
1398
1399    fn compile_expr_hinted_inner(
1400        &mut self,
1401        expr: &Expr,
1402        out: &mut CompiledScript,
1403        locals: &mut SymbolTable,
1404        type_hint: Option<Type>,
1405    ) {
1406        match expr {
1407            Expr::IntLiteral(n) => {
1408                out.push(Instruction::push_int(*n));
1409            }
1410
1411            Expr::LongLiteral(n) => {
1412                out.push(Instruction::push_long(*n));
1413            }
1414
1415            Expr::StringLiteral(s) => {
1416                if let Some(h) = type_hint
1417                    && h.base_type() == BaseVarType::Integer
1418                    && h != Type::Int
1419                    && h != Type::Boolean
1420                {
1421                    if let Some(id) = self.registry.lookup_reference(s, h) {
1422                        out.push(Instruction::push_int(id));
1423                        return;
1424                    }
1425                    if let Some(e) = self.registry.lookup_entity_id(s) {
1426                        out.push(Instruction::push_int(e.id));
1427                        return;
1428                    }
1429                }
1430                out.push_string(s.clone());
1431            }
1432
1433            Expr::BoolLiteral(b) => {
1434                out.push(Instruction::push_int(if *b { 1 } else { 0 }));
1435            }
1436
1437            Expr::NullLiteral => {
1438                // For string-typed parameters, null is the string "null".
1439                // For all other types, null is integer -1.
1440                if matches!(type_hint, Some(Type::String)) {
1441                    out.push_string("null".to_string());
1442                } else if type_hint.is_some_and(|ty| ty.base_type() == BaseVarType::Long) {
1443                    out.push(Instruction::push_long(-1));
1444                } else {
1445                    out.push(Instruction::push_int(-1));
1446                }
1447            }
1448
1449            Expr::CharLiteral(c) => {
1450                out.push(Instruction::push_int(*c as i32));
1451            }
1452
1453            Expr::CoordLiteral(c) => {
1454                out.push(Instruction::push_int(*c));
1455            }
1456
1457            Expr::LocalVar(name, _var_line) => {
1458                if let Some(sym) = locals.lookup(name) {
1459                    let (slot, base) = match &sym.kind {
1460                        SymbolKind::LocalVar { var_type, slot, .. } => {
1461                            (*slot, var_type.base_type())
1462                        }
1463                        SymbolKind::ScriptParam { param_type, slot } => {
1464                            (*slot, param_type.base_type())
1465                        }
1466                        _ => (0, BaseVarType::Integer),
1467                    };
1468                    let opcode = match base {
1469                        BaseVarType::Integer => Opcode::PushIntLocal,
1470                        BaseVarType::String => Opcode::PushStringLocal,
1471                        BaseVarType::Long => Opcode::PushLongLocal,
1472                    };
1473                    out.push(Instruction::new(opcode, Operand::Int(slot)));
1474                } else {
1475                    // Variable not found - push 0 as fallback
1476                    out.push(Instruction::push_int(0));
1477                }
1478            }
1479
1480            Expr::GameVar(name, _var_line) => {
1481                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
1482                // Encoding: (1 << 16) | var_id in the operand.
1483                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1484                    (stripped, true)
1485                } else {
1486                    (name.as_str(), false)
1487                };
1488                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1489                    && let SymbolKind::GameVar {
1490                        var_id, category, ..
1491                    } = &sym.kind
1492                {
1493                    let opcode = Opcode::push_var(category);
1494                    let encoded_id = if secondary {
1495                        (1 << 16) | *var_id
1496                    } else {
1497                        *var_id
1498                    };
1499                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1500                }
1501            }
1502
1503            Expr::ConstantVar(name, const_line) => {
1504                if let Some(sym) = self.registry.lookup_constant(name).cloned()
1505                    && let SymbolKind::Constant {
1506                        int_value,
1507                        string_value,
1508                        ..
1509                    } = &sym.kind
1510                {
1511                    if let Some(v) = int_value {
1512                        out.push(Instruction::push_int(*v));
1513                    } else if let Some(s) = string_value {
1514                        // String constants: emit line - 1 to match Java compiler.
1515                        // The Java type checker resolves ^constant to a StringLiteral
1516                        // with NodeSourceLocation(line - 1, col - 1), converting from
1517                        // 1-based ANTLR lines to a 0-based offset. Integer constants
1518                        // are re-parsed via ANTLR with the offset, so they keep the
1519                        // original line (1 + (line-1) = line).
1520                        if *const_line > 0 {
1521                            Self::emit_line(*const_line - 1, out);
1522                        }
1523                        out.push_string(s.clone());
1524                    }
1525                }
1526            }
1527
1528            Expr::Identifier(name) => {
1529                // Component reference: interface_name:component_name → (iface_id << 16) | comp_id
1530                if let Some((iface_name, comp_name)) = name.split_once(':')
1531                    && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
1532                {
1533                    out.push(Instruction::push_int(packed));
1534                    return;
1535                }
1536
1537                // Resolution order: entity IDs (stat/npc/loc/etc.) > constants (.constant)
1538                // > commands > game vars > script IDs > fallback -1.
1539                // This matches Java: plain identifiers use entity IDs, not .constant overrides.
1540                //
1541                // When a type hint is available (propagated from the enclosing command call's
1542                // parameter types), prefer the type-specific entity ID. This handles cases where
1543                // the same name exists in multiple pack files (e.g. `smokepuff` in both synth.pack
1544                // and spotanim.pack) — the correct ID is chosen based on the expected parameter type.
1545                //
1546                // Script reference type hints (proc, label, queue, etc.) bypass entity IDs and
1547                // go directly to trigger-specific script ID lookup.
1548                if let Some(hint) = type_hint {
1549                    let trigger_opt: Option<&'static str> = match hint {
1550                        Type::Proc => Some("proc"),
1551                        Type::ClientScript => Some("clientscript"),
1552                        Type::Label => Some("label"),
1553                        Type::Queue => Some("queue"),
1554                        Type::SoftTimer => Some("softtimer"),
1555                        Type::Timer => Some("timer"),
1556                        Type::Walktrigger => Some("walktrigger"),
1557                        Type::ControllerQueue => Some("controller_queue"),
1558                        Type::NpcQueue => Some("npc_queue"),
1559                        _ => None,
1560                    };
1561                    if let Some(trigger) = trigger_opt {
1562                        let script_id = self
1563                            .registry
1564                            .script_id_for_trigger(trigger, name)
1565                            .or_else(|| self.registry.proc_script_id(name))
1566                            .or_else(|| self.registry.script_id(name))
1567                            .unwrap_or(-1);
1568                        out.push(Instruction::push_int(script_id));
1569                        return;
1570                    }
1571                    if let Some(id) = self.registry.lookup_reference(name, hint) {
1572                        out.push(Instruction::push_int(id));
1573                        return;
1574                    }
1575                }
1576                if let Some(e) = self.registry.lookup_entity_id(name)
1577                    && !self.registry.command_fills(name, type_hint)
1578                {
1579                    // Param entities should NOT shadow type name identifiers unless
1580                    // we have a Param-typed hint. This allows "namedobj" etc. to resolve
1581                    // to their type chars in enum(int, namedobj, ...) contexts.
1582                    let skip_for_type_char = e.const_type == Type::Param
1583                        && type_hint != Some(Type::Param)
1584                        && self.registry.type_chars.contains_key(name);
1585                    if !skip_for_type_char {
1586                        // Entity ids are always integer ids (string_value is never set).
1587                        out.push(Instruction::push_int(e.id));
1588                        // If skip_for_type_char, fall through to commands/type_chars below
1589                        return;
1590                    }
1591                }
1592                // NOTE: a bare trigger/command NAME used as an int literal (the
1593                // test harness's `test_op(oploc1, ...)` / `wait_for(mes, ...)`)
1594                // is resolved at the *call site* of those specific commands (see
1595                // `try_emit_test_command_id_arg`), NOT here. Resolving it here
1596                // (for any int-hinted identifier) shadowed real commands that
1597                // share a trigger's name — notably `if_close`, both the close
1598                // command (opcode 2033) and the `[if_close,...]` trigger (byte
1599                // 148) — so a bare `if_close` statement compiled to
1600                // `push_int(148)` and the close was silently dropped.
1601                // Note: we fall through here only if entity lookup found a Param-type entity
1602                // that should be overridden by a type_char, or if entity lookup returned None.
1603                if let Some(sym) = self.registry.lookup_constant(name).cloned() {
1604                    if let SymbolKind::Constant {
1605                        int_value,
1606                        string_value,
1607                        ..
1608                    } = &sym.kind
1609                    {
1610                        if let Some(v) = int_value {
1611                            out.push(Instruction::push_int(*v));
1612                        } else if let Some(s) = string_value {
1613                            out.push_string(s.clone());
1614                        }
1615                    }
1616                } else {
1617                    let (lookup, idx) = if let Some(stripped) = name.strip_prefix('.') {
1618                        (stripped, 1u8)
1619                    } else {
1620                        (name.as_str(), 0u8)
1621                    };
1622                    let resolved = if let Some(sym) = self.registry.lookup_command(lookup).cloned()
1623                    {
1624                        if let SymbolKind::Command { opcode, .. } = &sym.kind {
1625                            let encoded = opcode | ((idx as i32) << 16);
1626                            out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1627                        }
1628                        true
1629                    } else {
1630                        false
1631                    };
1632                    if !resolved {
1633                        if let Some(sym) = self.registry.lookup_game_var(name).cloned()
1634                            && let SymbolKind::GameVar {
1635                                var_id, category, ..
1636                            } = &sym.kind
1637                        {
1638                            let push_op = Opcode::push_var(category);
1639                            out.push(Instruction::new(push_op, Operand::Int(*var_id)));
1640                        } else if let Some(&type_char) = self.registry.type_chars.get(name) {
1641                            out.push(Instruction::push_int(type_char));
1642                        } else if let Some(script_id) = self
1643                            .registry
1644                            .proc_script_id(name)
1645                            .or_else(|| self.registry.script_id(name))
1646                        {
1647                            out.push(Instruction::push_int(script_id));
1648                        } else {
1649                            out.push(Instruction::push_int(-1));
1650                        }
1651                    }
1652                }
1653            }
1654
1655            Expr::ArrayAccess { name, index } => {
1656                // Push index
1657                self.compile_expr(index, out, locals);
1658
1659                // Push array element
1660                if let Some(sym) = locals.lookup(name) {
1661                    let slot = match &sym.kind {
1662                        SymbolKind::LocalVar { slot, .. } => *slot,
1663                        _ => 0,
1664                    };
1665                    out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(slot)));
1666                }
1667            }
1668
1669            Expr::BinaryOp { op, lhs, rhs } => {
1670                // Handle entity names that contain '+' (e.g. "cheese+tom_batta").
1671                // The parser splits these into BinaryOp::Add, but they should resolve
1672                // as a single entity identifier.
1673                if matches!(op, BinOp::Add)
1674                    && let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1675                        (lhs.as_ref(), rhs.as_ref())
1676                {
1677                    let combined = format!("{}+{}", lhs_name, rhs_name);
1678                    if let Some(e) = self.registry.lookup_entity_id(&combined) {
1679                        out.push(Instruction::push_int(e.id));
1680                        return;
1681                    }
1682                }
1683
1684                // For comparisons, infer the type of lhs to use as a hint for rhs.
1685                // This allows e.g. `$struct = blamish_oil` to correctly resolve
1686                // `blamish_oil` from struct.pack rather than a higher-priority pack.
1687                let lhs_type_hint = match op {
1688                    BinOp::Eq
1689                    | BinOp::NotEq
1690                    | BinOp::Lt
1691                    | BinOp::Gt
1692                    | BinOp::LtEq
1693                    | BinOp::GtEq => self.infer_type(lhs, locals),
1694                    _ => None,
1695                };
1696                self.compile_expr(lhs, out, locals);
1697                self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
1698
1699                let opcode = match op {
1700                    BinOp::Add => Opcode::Add,
1701                    BinOp::Sub => Opcode::Sub,
1702                    BinOp::Mul => Opcode::Multiply,
1703                    BinOp::Div => Opcode::Divide,
1704                    BinOp::Mod => Opcode::Modulo,
1705                    BinOp::BitAnd => Opcode::And,
1706                    BinOp::BitOr => Opcode::Or,
1707                    BinOp::Eq => {
1708                        Self::emit_comparison_value(
1709                            Self::comparison_opcode(*op, lhs_type_hint),
1710                            0,
1711                            1,
1712                            out,
1713                        );
1714                        return;
1715                    }
1716                    BinOp::NotEq => {
1717                        Self::emit_comparison_value(
1718                            Self::comparison_opcode(BinOp::Eq, lhs_type_hint),
1719                            1,
1720                            0,
1721                            out,
1722                        );
1723                        return;
1724                    }
1725                    BinOp::Lt => {
1726                        Self::emit_comparison_value(
1727                            Self::comparison_opcode(*op, lhs_type_hint),
1728                            0,
1729                            1,
1730                            out,
1731                        );
1732                        return;
1733                    }
1734                    BinOp::Gt => {
1735                        Self::emit_comparison_value(
1736                            Self::comparison_opcode(*op, lhs_type_hint),
1737                            0,
1738                            1,
1739                            out,
1740                        );
1741                        return;
1742                    }
1743                    BinOp::LtEq => {
1744                        Self::emit_comparison_value(
1745                            Self::comparison_opcode(*op, lhs_type_hint),
1746                            0,
1747                            1,
1748                            out,
1749                        );
1750                        return;
1751                    }
1752                    BinOp::GtEq => {
1753                        Self::emit_comparison_value(
1754                            Self::comparison_opcode(*op, lhs_type_hint),
1755                            0,
1756                            1,
1757                            out,
1758                        );
1759                        return;
1760                    }
1761                };
1762                self.emit_arithmetic(opcode, out);
1763            }
1764
1765            Expr::LogicalOp { op, lhs, rhs, .. } => {
1766                self.compile_expr(lhs, out, locals);
1767                self.compile_expr(rhs, out, locals);
1768                match op {
1769                    LogicOp::And => self.emit_arithmetic(Opcode::And, out),
1770                    LogicOp::Or => self.emit_arithmetic(Opcode::Or, out),
1771                }
1772            }
1773
1774            Expr::Calc(inner) => {
1775                self.compile_expr(inner, out, locals);
1776            }
1777
1778            Expr::CommandCall {
1779                name,
1780                args,
1781                arg_lines,
1782                call_line,
1783            } => {
1784                let call = match hooks::server_call(self.registry, name, args, locals, *call_line) {
1785                    Ok(call) => call,
1786                    Err(error) => {
1787                        self.errors.push(error);
1788                        return;
1789                    }
1790                };
1791                let (name, args, arg_lines, call_line) = match &call {
1792                    Some(Expr::CommandCall {
1793                        name,
1794                        args,
1795                        arg_lines,
1796                        call_line,
1797                    }) => (name, args, arg_lines, call_line),
1798                    _ => (name, args, arg_lines, call_line),
1799                };
1800                if self.compile_intrinsic(name, args, out, locals) {
1801                    return;
1802                }
1803                // Dot-prefixed commands address the secondary active entity (operand = 1).
1804                let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
1805                    (stripped, 1u8)
1806                } else {
1807                    (name.as_str(), 0u8)
1808                };
1809
1810                let lowered =
1811                    match hooks::lower(self.registry, lookup_name, args, locals, *call_line) {
1812                        Ok(args) => args,
1813                        Err(error) => {
1814                            self.errors.push(error);
1815                            return;
1816                        }
1817                    };
1818                let args = lowered.as_deref().unwrap_or(args);
1819                let hints = command_hints(self.registry, lookup_name, args, locals);
1820
1821                // Commands that take a script reference as their first argument and
1822                // variadic extra arguments (described by a type-string pushed after them).
1823                let script_trigger = Self::command_script_trigger(lookup_name);
1824                let variadic_info = Self::command_variadic_info(lookup_name);
1825
1826                // Compile arguments, with special handling for the script-name first arg.
1827                let mut order = (0..args.len()).collect::<Vec<_>>();
1828                if self.registry.component_first_command(lookup_name) && !order.is_empty() {
1829                    order.rotate_left(1);
1830                }
1831                for i in order {
1832                    let arg = &args[i];
1833                    // Emit LineNumber before each arg to track multi-line calls.
1834                    if let Some(&al) = arg_lines.get(i)
1835                        && al > 0
1836                    {
1837                        Self::emit_line(al, out);
1838                    }
1839                    if i == 0
1840                        && let Some(trigger) = script_trigger
1841                    {
1842                        // First arg is a script name identifier: resolve to trigger-specific ID.
1843                        if let Expr::Identifier(script_name) = arg {
1844                            let script_id = self
1845                                .registry
1846                                .script_id_for_trigger(trigger, script_name)
1847                                .or_else(|| self.registry.proc_script_id(script_name))
1848                                .or_else(|| self.registry.script_id(script_name))
1849                                .unwrap_or(-1);
1850                            out.push(Instruction::push_int(script_id));
1851                            continue;
1852                        }
1853                    }
1854                    // For 'enum' command, args 0 and 1 are input/output type chars.
1855                    // Resolve plain identifiers as type chars before falling through to commands.
1856                    if (lookup_name == "enum"
1857                        || lookup_name == "enum2"
1858                        || lookup_name == "db_getfield"
1859                        || lookup_name == "db_find"
1860                        || lookup_name == "db_find_refine"
1861                        || lookup_name == "db_findbyindex"
1862                        || lookup_name == "db_find_with_count"
1863                        || lookup_name == "param"
1864                        || self
1865                            .registry
1866                            .type_arguments
1867                            .get(lookup_name)
1868                            .is_some_and(|&n| i < n))
1869                        && (i == 0 || i == 1)
1870                        && let Expr::Identifier(n) = arg
1871                        && let Some(&tc) = self.registry.type_chars.get(n.as_str())
1872                    {
1873                        out.push(Instruction::push_int(tc));
1874                        continue;
1875                    }
1876                    let hint = hints.get(i).copied().flatten();
1877                    if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
1878                        continue;
1879                    }
1880                    self.compile_expr_hinted(arg, out, locals, hint);
1881                }
1882
1883                // Push the variadic type-descriptor string for commands that support it.
1884                if let Some(fixed_arg_count) = variadic_info {
1885                    let variadic_args = if args.len() > fixed_arg_count {
1886                        &args[fixed_arg_count..]
1887                    } else {
1888                        &[]
1889                    };
1890                    let type_desc: String = variadic_args
1891                        .iter()
1892                        .map(|arg| self.infer_type_char(arg, locals))
1893                        .collect();
1894                    out.push_string(type_desc);
1895                }
1896
1897                // db_find needs an implicit extra push_int argument: the Java BaseVarType
1898                // ordinal of the column's first field type (INT=0, LONG=1, STRING=2).
1899                if lookup_name == "db_find" || lookup_name == "db_find_refine" {
1900                    let base_type_ordinal = if let Some(Expr::Identifier(col_name)) = args.first() {
1901                        self.registry
1902                            .dbcolumn_types
1903                            .get(col_name.as_str())
1904                            .and_then(|types| types.first())
1905                            .map(|t| match t.base_type() {
1906                                crate::types::BaseVarType::Integer => 0,
1907                                crate::types::BaseVarType::Long => 1,
1908                                crate::types::BaseVarType::String => 2,
1909                            })
1910                            .unwrap_or(0)
1911                    } else {
1912                        0
1913                    };
1914                    out.push(Instruction::push_int(base_type_ordinal));
1915                }
1916
1917                // Re-emit the call expression's line before the final command instruction.
1918                // The reference compiler does lineInstruction(expr) after visiting args.
1919                if *call_line > 0 {
1920                    Self::emit_line(*call_line, out);
1921                }
1922
1923                // Look up command opcode and emit.
1924                // For variadic variants (name*), also check the "namevararg" form
1925                // used in command.pack.
1926                let cmd_sym = self
1927                    .registry
1928                    .lookup_command(lookup_name)
1929                    .or_else(|| {
1930                        lookup_name.strip_suffix('*').and_then(|base| {
1931                            let vararg_name = format!("{}vararg", base);
1932                            self.registry.lookup_command(&vararg_name)
1933                        })
1934                    })
1935                    .cloned();
1936                if let Some(sym) = cmd_sym {
1937                    if let SymbolKind::Command { opcode, .. } = &sym.kind {
1938                        let encoded = (*opcode) | ((cmd_index as i32) << 16);
1939                        out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1940                    }
1941                } else {
1942                    let cmd_name_idx = out.intern_str(name.to_string());
1943                    out.push(Instruction::new(
1944                        Opcode::Command,
1945                        Operand::Str(cmd_name_idx),
1946                    ));
1947                }
1948
1949                // Note: db_find and db_find_refine do NOT push a count value.
1950                // Only db_find_with_count and db_find_refine_with_count push a count.
1951            }
1952
1953            Expr::ProcCall {
1954                name,
1955                args,
1956                arg_lines,
1957                call_line,
1958            } => {
1959                let hints = proc_hints(self.registry, name, args, locals);
1960                for (i, arg) in args.iter().enumerate() {
1961                    if let Some(&al) = arg_lines.get(i)
1962                        && al > 0
1963                    {
1964                        Self::emit_line(al, out);
1965                    }
1966                    let hint = hints.get(i).copied().flatten();
1967                    self.compile_expr_hinted(arg, out, locals, hint);
1968                }
1969
1970                // Re-emit call expression's line before final gosub.
1971                if *call_line > 0 {
1972                    Self::emit_line(*call_line, out);
1973                }
1974
1975                // `~name(...)` resolves ONLY against `[proc,name]` — matching
1976                // RuneScriptTS. A silent fallback to any script with this name
1977                // (debugproc / label / timer) lets `~foo` bind to an unrelated
1978                // trigger; if that trigger's body also calls `~foo`, you get
1979                // infinite recursion at runtime. The type checker emits an
1980                // error diagnostic for unresolved procs, so `-1` here only
1981                // fires in paths that already produced an error.
1982                let script_id = self
1983                    .registry
1984                    .proc_script_id(name)
1985                    .or_else(|| self.registry.script_id_for_trigger("clientscript", name))
1986                    .unwrap_or(-1);
1987                out.push(Instruction::gosub_with_params(script_id));
1988            }
1989
1990            Expr::JumpCall {
1991                name,
1992                args,
1993                arg_lines,
1994                call_line,
1995            } => {
1996                // Get parameter types from target label for type-aware arg compilation
1997                let param_types: Vec<Type> = self
1998                    .registry
1999                    .lookup_script(name)
2000                    .and_then(|sym| {
2001                        if let SymbolKind::Script { param_types, .. } = &sym.kind {
2002                            Some(param_types.clone())
2003                        } else {
2004                            None
2005                        }
2006                    })
2007                    .unwrap_or_default();
2008                for (i, arg) in args.iter().enumerate() {
2009                    if let Some(&al) = arg_lines.get(i)
2010                        && al > 0
2011                    {
2012                        Self::emit_line(al, out);
2013                    }
2014                    let hint = param_types.get(i).copied();
2015                    self.compile_expr_hinted(arg, out, locals, hint);
2016                }
2017                // Re-emit call expression's line before final jump.
2018                if *call_line > 0 {
2019                    Self::emit_line(*call_line, out);
2020                }
2021
2022                let script_id = self
2023                    .registry
2024                    .label_script_id(name)
2025                    .or_else(|| self.registry.script_id(name))
2026                    .unwrap_or(-1);
2027                out.push(Instruction::new(
2028                    Opcode::JumpWithParams,
2029                    Operand::Int(script_id),
2030                ));
2031            }
2032
2033            Expr::JoinedString { parts } => {
2034                let mut count = 0u32;
2035                for part in parts {
2036                    match part {
2037                        StringPart::Literal(s) => {
2038                            out.push_string(s.clone());
2039                            count += 1;
2040                        }
2041                        StringPart::Expr(e) => {
2042                            self.compile_expr(e, out, locals);
2043                            count += 1;
2044                        }
2045                    }
2046                }
2047                out.push(Instruction::join_string(count));
2048            }
2049
2050            Expr::Tuple(values) => {
2051                for value in values {
2052                    self.compile_expr(value, out, locals);
2053                }
2054            }
2055            Expr::MultiAssign(..) => {
2056                // Multi-assign targets handled at statement level; no-op as expression
2057            }
2058        }
2059    }
2060
2061    fn comparison_opcode(op: BinOp, ty: Option<Type>) -> Opcode {
2062        match (op, ty.is_some_and(|ty| ty.base_type() == BaseVarType::Long)) {
2063            (BinOp::Eq, false) => Opcode::BranchEquals,
2064            (BinOp::Eq, true) => Opcode::LongBranchEquals,
2065            (BinOp::NotEq, false) => Opcode::BranchNot,
2066            (BinOp::NotEq, true) => Opcode::LongBranchNot,
2067            (BinOp::Lt, false) => Opcode::BranchLessThan,
2068            (BinOp::Lt, true) => Opcode::LongBranchLessThan,
2069            (BinOp::Gt, false) => Opcode::BranchGreaterThan,
2070            (BinOp::Gt, true) => Opcode::LongBranchGreaterThan,
2071            (BinOp::LtEq, false) => Opcode::BranchLessThanOrEquals,
2072            (BinOp::LtEq, true) => Opcode::LongBranchLessThanOrEquals,
2073            (BinOp::GtEq, false) => Opcode::BranchGreaterThanOrEquals,
2074            (BinOp::GtEq, true) => Opcode::LongBranchGreaterThanOrEquals,
2075            _ => Opcode::BranchNot,
2076        }
2077    }
2078
2079    fn compile_intrinsic(
2080        &mut self,
2081        name: &str,
2082        args: &[Expr],
2083        out: &mut CompiledScript,
2084        locals: &mut SymbolTable,
2085    ) -> bool {
2086        match (name, args) {
2087            ("__label", [Expr::Identifier(label)]) => {
2088                if self.labels.insert(label.clone(), out.len()).is_some() {
2089                    self.errors.push(format!("Duplicate label {label}"));
2090                }
2091            }
2092            ("__jump", [Expr::Identifier(label)]) => {
2093                self.label_jumps.push((out.len(), label.clone()));
2094                out.push(Instruction::jump(0));
2095            }
2096            ("__branch", [Expr::Identifier(code), Expr::Identifier(label), values @ ..]) => {
2097                let Some(opcode) = Opcode::core(code).filter(|opcode| {
2098                    matches!(
2099                        opcode,
2100                        Opcode::BranchNot
2101                            | Opcode::BranchEquals
2102                            | Opcode::BranchLessThan
2103                            | Opcode::BranchGreaterThan
2104                            | Opcode::BranchLessThanOrEquals
2105                            | Opcode::BranchGreaterThanOrEquals
2106                            | Opcode::LongBranchNot
2107                            | Opcode::LongBranchEquals
2108                            | Opcode::LongBranchLessThan
2109                            | Opcode::LongBranchGreaterThan
2110                            | Opcode::LongBranchLessThanOrEquals
2111                            | Opcode::LongBranchGreaterThanOrEquals
2112                            | Opcode::BranchIfTrue
2113                            | Opcode::BranchIfFalse
2114                    )
2115                }) else {
2116                    self.errors.push(format!("Invalid branch {code}"));
2117                    return true;
2118                };
2119                for value in values {
2120                    self.compile_expr(value, out, locals);
2121                }
2122                self.label_jumps.push((out.len(), label.clone()));
2123                out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
2124            }
2125            ("__switch", [value, cases @ ..]) => {
2126                self.compile_expr(value, out, locals);
2127                let index = out.switch_tables.len();
2128                let mut table = Vec::new();
2129                if cases.len() % 2 != 0 {
2130                    self.errors.push("Expected switch key/label pairs".into());
2131                }
2132                for pair in cases.as_chunks::<2>().0 {
2133                    if let [Expr::IntLiteral(key), Expr::Identifier(label)] = pair {
2134                        self.label_switches
2135                            .push((index, table.len(), label.clone()));
2136                        table.push((*key, 0));
2137                    } else {
2138                        self.errors.push("Invalid switch key/label".into());
2139                    }
2140                }
2141                out.switch_tables.push(table.into_boxed_slice());
2142                out.push(Instruction::new(
2143                    Opcode::Switch,
2144                    Operand::SwitchTable(index as u32),
2145                ));
2146            }
2147            ("__opcode", [Expr::Identifier(name), Expr::IntLiteral(value)]) => {
2148                if let Some(opcode) = Opcode::core(name) {
2149                    out.push(Instruction::new(opcode, Operand::Int(*value)));
2150                } else {
2151                    self.errors.push(format!("Unknown instruction {name}"));
2152                }
2153            }
2154            ("__opcode", [Expr::IntLiteral(code), Expr::IntLiteral(value)]) => {
2155                if !(0..=65535).contains(code) {
2156                    self.errors
2157                        .push(format!("Invalid integer instruction {code}"));
2158                } else {
2159                    out.push(Instruction::new(
2160                        Opcode::Raw,
2161                        Operand::Long(((*code as i64) << 32) | *value as u32 as i64),
2162                    ));
2163                }
2164            }
2165            ("__push", values) => {
2166                for value in values {
2167                    self.compile_expr(value, out, locals);
2168                }
2169            }
2170            ("__pop_int" | "__pop_string" | "__pop_long", []) => {}
2171            ("__join", values) => {
2172                for value in values {
2173                    self.compile_expr(value, out, locals);
2174                }
2175                out.push(Instruction::join_string(values.len() as u32));
2176            }
2177            ("__get_array", [Expr::IntLiteral(id), index]) => {
2178                self.compile_expr(index, out, locals);
2179                out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(*id)));
2180            }
2181            ("__set_array", [Expr::IntLiteral(id), index, value]) => {
2182                self.compile_expr(index, out, locals);
2183                self.compile_expr(value, out, locals);
2184                out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(*id)));
2185            }
2186            ("__define_array", [Expr::IntLiteral(id), Expr::IntLiteral(kind), size]) => {
2187                self.compile_expr(size, out, locals);
2188                out.push(Instruction::new(
2189                    Opcode::DefineArray,
2190                    Operand::ArrayDef(*id, *kind as u8),
2191                ));
2192            }
2193            _ if name.starts_with("__") => {
2194                self.errors.push(format!("Invalid intrinsic {name}"));
2195            }
2196            _ => return false,
2197        }
2198        true
2199    }
2200
2201    fn compile_store(&mut self, target: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
2202        match target {
2203            Expr::LocalVar(name, _var_line) => {
2204                if let Some(sym) = locals.lookup(name) {
2205                    let (slot, base) = match &sym.kind {
2206                        SymbolKind::LocalVar { var_type, slot, .. } => {
2207                            (*slot, var_type.base_type())
2208                        }
2209                        SymbolKind::ScriptParam { param_type, slot } => {
2210                            (*slot, param_type.base_type())
2211                        }
2212                        _ => (0, BaseVarType::Integer),
2213                    };
2214                    let opcode = match base {
2215                        BaseVarType::Integer => Opcode::PopIntLocal,
2216                        BaseVarType::String => Opcode::PopStringLocal,
2217                        BaseVarType::Long => Opcode::PopLongLocal,
2218                    };
2219                    out.push(Instruction::new(opcode, Operand::Int(slot)));
2220                }
2221            }
2222
2223            Expr::GameVar(name, _var_line) => {
2224                // Dot-prefixed game vars (e.g. .%tradepartner) address secondary entity.
2225                // Encoding: (1 << 16) | var_id in the operand.
2226                let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
2227                    (stripped, true)
2228                } else {
2229                    (name.as_str(), false)
2230                };
2231                if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
2232                    && let SymbolKind::GameVar {
2233                        var_id, category, ..
2234                    } = &sym.kind
2235                {
2236                    let opcode = Opcode::pop_var(category);
2237                    let encoded_id = if secondary {
2238                        (1 << 16) | *var_id
2239                    } else {
2240                        *var_id
2241                    };
2242                    out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
2243                }
2244            }
2245
2246            Expr::ArrayAccess { name, index } => {
2247                // For array store: push index, then value is already on stack
2248                self.compile_expr(index, out, locals);
2249                if let Some(sym) = locals.lookup(name) {
2250                    let slot = match &sym.kind {
2251                        SymbolKind::LocalVar { slot, .. } => *slot,
2252                        _ => 0,
2253                    };
2254                    out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
2255                }
2256            }
2257
2258            Expr::MultiAssign(targets, target_lines) => {
2259                // Multi-return: pop return values in reverse order (last target = top of stack)
2260                for (i, target) in targets.iter().enumerate().rev() {
2261                    // Emit LineNumber for each target's source line
2262                    if let Some(&tl) = target_lines.get(i)
2263                        && tl > 0
2264                    {
2265                        Self::emit_line(tl, out);
2266                    }
2267                    self.compile_store(target, out, locals);
2268                }
2269            }
2270
2271            _ => {
2272                // Invalid store target - should be caught by type checker
2273            }
2274        }
2275    }
2276
2277    /// Returns the trigger type for commands whose first argument is a script name.
2278    pub(crate) fn command_script_trigger(cmd_name: &str) -> Option<&'static str> {
2279        match cmd_name {
2280            "queue" | "queue*" | "longqueue" | "longqueue*" | "strongqueue" | "strongqueue*"
2281            | "weakqueue" | "weakqueue*" | "clearqueue" => Some("queue"),
2282            "softtimer" | "softtimer*" => Some("softtimer"),
2283            "settimer" | "settimer*" | "cleartimer" => Some("timer"),
2284            "walktrigger" => Some("walktrigger"),
2285            "controller_queue*" => Some("controller_queue"),
2286            "npc_queue*" => Some("npc_queue"),
2287            _ => None,
2288        }
2289    }
2290
2291    /// Number of fixed (non-variadic) arguments for commands that push a type descriptor.
2292    /// Returns None for commands that don't use a type descriptor at all.
2293    pub(crate) fn command_variadic_info(cmd_name: &str) -> Option<usize> {
2294        match cmd_name {
2295            // queue/strongqueue/weakqueue have separate * variants (different opcodes)
2296            "queue*" | "strongqueue*" | "weakqueue*" | "controller_queue*" | "npc_queue*" => {
2297                Some(2)
2298            }
2299            "longqueue*" => Some(3),
2300            // settimer/softtimer are always variadic (no separate * variant)
2301            "settimer" | "softtimer" => Some(2),
2302            // runclientscript* has 1 fixed arg (script_id) + variadic params
2303            "runclientscript*" => Some(1),
2304            _ => None,
2305        }
2306    }
2307
2308    /// Infer the RS2 type character for an expression (used for variadic type descriptors).
2309    fn infer_type_char(&self, expr: &Expr, locals: &SymbolTable) -> char {
2310        match expr {
2311            Expr::StringLiteral(_) | Expr::JoinedString { .. } => 's',
2312            Expr::LongLiteral(_) => 'l',
2313            Expr::IntLiteral(_)
2314            | Expr::BoolLiteral(_)
2315            | Expr::CoordLiteral(_)
2316            | Expr::CharLiteral(_) => 'i',
2317            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
2318                if let Some(sym) = locals.lookup(name) {
2319                    match &sym.kind {
2320                        SymbolKind::LocalVar { var_type, .. } => self.type_to_type_char(*var_type),
2321                        SymbolKind::ScriptParam { param_type, .. } => {
2322                            self.type_to_type_char(*param_type)
2323                        }
2324                        _ => 'i',
2325                    }
2326                } else {
2327                    'i'
2328                }
2329            }
2330            Expr::GameVar(name, _var_line) => {
2331                if let Some(sym) = self.registry.lookup_game_var(name)
2332                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
2333                {
2334                    return self.type_to_type_char(*var_type);
2335                }
2336                'i'
2337            }
2338            Expr::CommandCall { name, args, .. } => command_returns(self.registry, name, args)
2339                .first()
2340                .map_or_else(
2341                    || Self::known_command_type_char(name.trim_start_matches('.')),
2342                    |ty| self.type_to_type_char(*ty),
2343                ),
2344            Expr::ProcCall { name, .. } => {
2345                if let Some(sym) = self.registry.lookup_script(name)
2346                    && let SymbolKind::Script { return_types, .. } = &sym.kind
2347                    && let Some(rt) = return_types.first()
2348                {
2349                    return self.type_to_type_char(*rt);
2350                }
2351                'i'
2352            }
2353            Expr::Identifier(name) => {
2354                // Bare identifier (no parens) - might be a zero-arg command like `uid`
2355                let lookup = name.trim_start_matches('.');
2356                if let Some(sym) = self.registry.lookup_command(lookup)
2357                    && let SymbolKind::Command { return_types, .. } = &sym.kind
2358                    && let Some(rt) = return_types.first()
2359                {
2360                    return self.type_to_type_char(*rt);
2361                }
2362                Self::known_command_type_char(lookup)
2363            }
2364            Expr::ConstantVar(name, _) => {
2365                if let Some(sym) = self.registry.lookup_constant(name)
2366                    && let SymbolKind::Constant { const_type, .. } = &sym.kind
2367                {
2368                    return self.type_to_type_char(*const_type);
2369                }
2370                'i'
2371            }
2372            Expr::BinaryOp { .. } | Expr::Calc(_) => 'i',
2373            Expr::NullLiteral => 'i',
2374            _ => 'i',
2375        }
2376    }
2377
2378    /// Infer the type of an assignment target (lvalue) for type-hinted value compilation.
2379    fn infer_target_type(&self, target: &Expr, locals: &SymbolTable) -> Option<Type> {
2380        match target {
2381            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
2382                if let Some(sym) = locals.lookup(name) {
2383                    match &sym.kind {
2384                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
2385                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
2386                        _ => None,
2387                    }
2388                } else {
2389                    None
2390                }
2391            }
2392            Expr::GameVar(name, _var_line) => {
2393                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
2394                    stripped
2395                } else {
2396                    name.as_str()
2397                };
2398                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
2399                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
2400                {
2401                    return Some(*var_type);
2402                }
2403                None
2404            }
2405            _ => None,
2406        }
2407    }
2408
2409    /// Infer the `Type` of an expression for use as a comparison type hint.
2410    fn infer_type(&self, expr: &Expr, locals: &SymbolTable) -> Option<Type> {
2411        match expr {
2412            Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
2413                if let Some(sym) = locals.lookup(name) {
2414                    match &sym.kind {
2415                        SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
2416                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
2417                        _ => None,
2418                    }
2419                } else {
2420                    None
2421                }
2422            }
2423            Expr::GameVar(name, _var_line) => {
2424                let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
2425                    stripped
2426                } else {
2427                    name.as_str()
2428                };
2429                if let Some(sym) = self.registry.lookup_game_var(lookup_name)
2430                    && let SymbolKind::GameVar { var_type, .. } = &sym.kind
2431                {
2432                    return Some(*var_type);
2433                }
2434                None
2435            }
2436            Expr::CommandCall { name, args, .. } => {
2437                command_returns(self.registry, name, args).first().copied()
2438            }
2439            Expr::Identifier(name) => {
2440                // Zero-arg commands used without parens (e.g. `loc_category`)
2441                let lookup = name.trim_start_matches('.');
2442                if let Some(sym) = self.registry.lookup_command(lookup)
2443                    && let SymbolKind::Command { return_types, .. } = &sym.kind
2444                {
2445                    return return_types.first().copied();
2446                }
2447                None
2448            }
2449            _ => None,
2450        }
2451    }
2452
2453    fn type_to_type_char(&self, t: Type) -> char {
2454        match t.base_type() {
2455            BaseVarType::String => 's',
2456            BaseVarType::Long => 'l',
2457            BaseVarType::Integer => {
2458                // Use the type_chars map for more precise type chars
2459                // (e.g., namedobj='O', playeruid='p')
2460                for (name, &tc) in &self.registry.type_chars {
2461                    if let Some(from_type) = Type::from_name(name)
2462                        && from_type == t
2463                    {
2464                        return (tc as u8) as char;
2465                    }
2466                }
2467                'i'
2468            }
2469        }
2470    }
2471
2472    fn known_command_type_char(name: &str) -> char {
2473        // Commands whose return type is not in the sym file but is known
2474        match name {
2475            "uid" => 'p',     // PlayerUid
2476            "npc_uid" => 'u', // NpcUid
2477            "displayname" | "name" | "npc_name" | "oc_name" | "oc_cert" => 's',
2478            _ => 'i',
2479        }
2480    }
2481
2482    /// Returns `Some(error message)` if `[trigger,entity_name]` resolved a
2483    /// trigger byte but failed to resolve `entity_name` to a real subject,
2484    /// which would silently produce an unreachable script (lookup_key = -1).
2485    /// Returns `None` for legitimate cases:
2486    ///   - bare `_` wildcard (global trigger, no subject)
2487    ///   - `_category` form (category lookup — caller validates separately)
2488    ///   - coord-shaped triggers (`zone`, `zoneexit`, `mapzone`, `mapzoneexit`)
2489    ///   - name-keyed triggers (`queue`, `timer`, `walktrigger`, `proc`, `label`, …)
2490    pub fn validate_trigger_subject(
2491        trigger: &str,
2492        entity_name: &str,
2493        registry: &SymbolRegistry,
2494    ) -> Option<String> {
2495        if entity_name.is_empty() || entity_name == "_" {
2496            return None;
2497        }
2498        // Category subjects are validated by their own path; skip.
2499        if entity_name.starts_with('_') {
2500            return None;
2501        }
2502        // Triggers whose subject is a coord, has no subject at all, or is
2503        // historically not validated (ai_queue/ai_timer) — see trigger_table.
2504        if !registry
2505            .trigger(trigger)
2506            .is_some_and(|trigger| trigger.validates_subject)
2507        {
2508            return None;
2509        }
2510        let key = Self::compute_lookup_key(trigger, entity_name, registry);
2511        if key == -1 {
2512            let hint = if entity_name.contains(':') {
2513                let (iface, comp) = entity_name.split_once(':').unwrap();
2514                format!(
2515                    "interface:component subject — check interface.pack for either an if3 entry \
2516                     `<iface_id>:<comp_id>=<comp_name>` (with iface_id matching `{iface}`) \
2517                     or an if1 entry `<flat_id>={iface}:{comp}`"
2518                )
2519            } else {
2520                "Likely a typo or missing pack entry (check interface.pack / npc.pack / obj.pack / loc.pack)".to_string()
2521            };
2522            return Some(format!(
2523                "[{trigger},{entity_name}] — subject `{entity_name}` did not resolve to an entity. \
2524                 {hint}. Script will compile but never dispatch."
2525            ));
2526        }
2527        None
2528    }
2529
2530    /// Compute the CS2 Neptune lookup key for a script.
2531    /// Formula: `entity_id * 1024 + 512 + trigger_byte`, or -1 if not applicable.
2532    /// For global scripts (entity="_"), returns just `trigger_byte`.
2533    pub fn compute_lookup_key(trigger: &str, entity_name: &str, registry: &SymbolRegistry) -> i32 {
2534        if let Some(resolver) = registry
2535            .profile
2536            .as_ref()
2537            .and_then(|profile| profile.lookup_key)
2538        {
2539            return resolver(trigger, entity_name, registry);
2540        }
2541        // Trigger byte from the central trigger_table. Unknown triggers
2542        // (queue, softtimer, timer, walktrigger, proc, label, command,
2543        // clientscript, debugproc) are name-keyed and have no byte.
2544        let trigger_byte = match registry.trigger(trigger).and_then(|trigger| trigger.byte) {
2545            Some(b) => b as i64,
2546            None => return -1,
2547        };
2548
2549        // Global scripts with no specific entity return just the trigger byte
2550        if entity_name == "_" {
2551            return trigger_byte as i32;
2552        }
2553
2554        // Coordinate-based triggers: parse "level_bx_by" format
2555        if matches!(trigger, "mapzone" | "mapzoneexit") {
2556            let parts: Vec<&str> = entity_name.splitn(4, '_').collect();
2557            if parts.len() >= 3
2558                && let (Ok(bx), Ok(by)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>())
2559            {
2560                let entity_id: i64 = ((bx & 3) << 20) | (by << 6);
2561                return (entity_id * 1024 + 512 + trigger_byte) as i32;
2562            }
2563            return -1;
2564        }
2565
2566        // Coordinate-based triggers: parse "level_bx_by_lx_lz" format
2567        if matches!(trigger, "zone" | "zoneexit") {
2568            let parts: Vec<&str> = entity_name.splitn(6, '_').collect();
2569            if parts.len() >= 5
2570                && let (Ok(bx), Ok(by), Ok(lx), Ok(lz)) = (
2571                    parts[1].parse::<i64>(),
2572                    parts[2].parse::<i64>(),
2573                    parts[3].parse::<i64>(),
2574                    parts[4].parse::<i64>(),
2575                )
2576            {
2577                let entity_id: i64 = ((bx & 3) << 20) | (by << 6) | (lx << 14) | lz;
2578                return (entity_id * 1024 + 512 + trigger_byte) as i32;
2579            }
2580            return -1;
2581        }
2582
2583        // Category-based entities: entity names starting with '_' reference a category
2584        // (e.g. [opheldu,_alcoholic_drinks] → category "alcoholic_drinks").
2585        // These use offset 256 instead of 512 in the lookupKey formula.
2586        //
2587        // NOTE: the bare `_` (pure wildcard) case is handled earlier in
2588        // this function (entity_name == "_" → returns just trigger_byte).
2589        if let Some(cat_name) = entity_name.strip_prefix('_') {
2590            if let Some(sym) = registry.lookup_entity_id_typed(cat_name, Type::Category) {
2591                return (sym as i64 * 1024 + 256 + trigger_byte) as i32;
2592            }
2593            return -1;
2594        }
2595
2596        // Component subject in `interface:component` form (e.g. `options:com_14`).
2597        // The subject is the packed `(iface_id << 16) | comp_id` registered by
2598        // symloader's `registry.components` map. Used by if_button / inv_button
2599        // triggers — their dispatch hashes iface+comp into 32 bits.
2600        if let Some((iface_name, comp_name)) = entity_name.split_once(':') {
2601            if let Some(packed) = registry.lookup_component(iface_name, comp_name) {
2602                return (packed as i64 * 1024 + 512 + trigger_byte) as i32;
2603            }
2604            return -1;
2605        }
2606
2607        // Type-aware entity lookup so that e.g. "potato" resolves to loc_id
2608        // for [oploc2,potato] rather than the obj_id that has higher flat
2609        // priority. Trigger → entity-type routing lives in trigger_table.
2610        if let Some(entity_type) = registry
2611            .trigger(trigger)
2612            .and_then(|trigger| trigger.subject_type)
2613            && let Some(entity_id) = registry.lookup_entity_id_typed(entity_name, entity_type)
2614        {
2615            return (entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2616        }
2617
2618        // Fallback: flat entity_ids lookup
2619        if let Some(e) = registry.lookup_entity_id(entity_name) {
2620            return (e.id as i64 * 1024 + 512 + trigger_byte) as i32;
2621        }
2622        -1
2623    }
2624}
2625
2626#[cfg(test)]
2627mod tests {
2628    use super::*;
2629    use crate::types::Type;
2630
2631    /// Build a registry seeded with a few entities and one interface+component
2632    /// pair, mimicking the shape symloader produces from interface.pack /
2633    /// npc.pack / obj.pack.
2634    fn seed_registry() -> SymbolRegistry {
2635        let mut r = SymbolRegistry::new();
2636        // Interface 261 = "options", with component 14 = "com_14".
2637        // Key uses normalized form (com14) matching what symloader produces.
2638        r.register_entity_id("options".into(), Type::Interface, 261);
2639        r.register_entity_id("com14".into(), Type::Component, 14);
2640        r.components
2641            .insert("options:com14".into(), (261 << 16) | 14);
2642        // An npc + obj entity for non-interface trigger tests.
2643        r.register_entity_id("man".into(), Type::Npc, 1);
2644        r.register_entity_id("bronze_axe".into(), Type::Obj, 1351);
2645        r
2646    }
2647
2648    #[test]
2649    fn if_button_resolves_interface_component_form() {
2650        let r = seed_registry();
2651        let key = Compiler::compute_lookup_key("if_button", "options:com_14", &r);
2652        let expected = ((261i64 << 16 | 14) * 1024 + 512 + 147) as i32;
2653        assert_eq!(key, expected);
2654        // And the lookup-key wraps to match the engine's
2655        // ServerTriggerType::IfButton::lookup_key_subject(com_hash) where
2656        // com_hash = iface*65536 + comp.
2657        let com_hash = (261i64 << 16 | 14) as i32;
2658        let engine_key = (com_hash as i64 * 1024 + 512 + 147) as i32;
2659        assert_eq!(key, engine_key);
2660    }
2661
2662    #[test]
2663    fn validate_warns_on_unresolved_if_button_subject() {
2664        let r = seed_registry();
2665        // Unknown component name — old bug shape (would silently never dispatch).
2666        let warning =
2667            Compiler::validate_trigger_subject("if_button", "options:com_does_not_exist", &r);
2668        assert!(
2669            warning.is_some(),
2670            "expected a warning for unresolved subject"
2671        );
2672        assert!(warning.unwrap().contains("did not resolve"));
2673    }
2674
2675    #[test]
2676    fn validate_silent_on_resolvable_subject() {
2677        let r = seed_registry();
2678        assert!(Compiler::validate_trigger_subject("if_button", "options:com_14", &r).is_none());
2679        assert!(Compiler::validate_trigger_subject("opnpc1", "man", &r).is_none());
2680        assert!(Compiler::validate_trigger_subject("opheld1", "bronze_axe", &r).is_none());
2681    }
2682
2683    #[test]
2684    fn validate_silent_on_wildcards_and_categories() {
2685        let r = seed_registry();
2686        // Bare `_` — global trigger, no subject.
2687        assert!(Compiler::validate_trigger_subject("opheld1", "_", &r).is_none());
2688        // `_category` form — caller validates separately.
2689        assert!(Compiler::validate_trigger_subject("opheldu", "_alcoholic_drinks", &r).is_none());
2690    }
2691
2692    #[test]
2693    fn validate_silent_on_name_keyed_triggers() {
2694        let r = seed_registry();
2695        // queue/timer/walktrigger/proc are name-keyed; `lookup_key = -1` is correct.
2696        assert!(Compiler::validate_trigger_subject("queue", "my_queue", &r).is_none());
2697        assert!(Compiler::validate_trigger_subject("timer", "my_timer", &r).is_none());
2698        assert!(Compiler::validate_trigger_subject("proc", "my_proc", &r).is_none());
2699    }
2700
2701    #[test]
2702    fn validate_silent_on_coord_triggers() {
2703        let r = seed_registry();
2704        // Coord-shaped names are parsed from the entity string itself.
2705        assert!(Compiler::validate_trigger_subject("zone", "0_50_50_10_10", &r).is_none());
2706    }
2707
2708    #[test]
2709    fn validate_warns_on_unknown_npc_subject() {
2710        let r = seed_registry();
2711        let warning = Compiler::validate_trigger_subject("opnpc1", "not_a_real_npc", &r);
2712        assert!(warning.is_some());
2713    }
2714
2715    /// An npc AI trigger binds its subject as the npc even when an obj of the
2716    /// same name was registered after it (obj.pack loads after npc.pack, so
2717    /// the obj owns the untyped name). Rev 647 names npc 708 and a dummy obj
2718    /// 9952 both `imp`: `[ai_timer,imp]` keyed to the obj and never ran.
2719    #[test]
2720    fn npc_ai_triggers_bind_the_npc_over_a_same_named_obj() {
2721        let mut r = SymbolRegistry::new();
2722        r.register_entity_id("imp".into(), Type::Npc, 708);
2723        r.register_entity_id("imp".into(), Type::Obj, 9952);
2724        for (trigger, byte) in [
2725            ("ai_timer", 139),
2726            ("ai_queue2", 118),
2727            ("ai_applayer2", 102),
2728            ("ai_opplayer2", 109),
2729            ("ai_oploc1", 80),
2730            ("ai_apobj1", 45),
2731            ("ai_spawn", 166),
2732            ("ai_despawn", 167),
2733        ] {
2734            assert_eq!(
2735                Compiler::compute_lookup_key(trigger, "imp", &r),
2736                708 * 1024 + 512 + byte,
2737                "[{trigger},imp]"
2738            );
2739        }
2740        // An npc category still keys by the category.
2741        r.register_entity_id("demons".into(), Type::Category, 7);
2742        assert_eq!(
2743            Compiler::compute_lookup_key("ai_timer", "_demons", &r),
2744            7 * 1024 + 256 + 139
2745        );
2746        // A held-item trigger still binds the obj.
2747        assert_eq!(
2748            Compiler::compute_lookup_key("opheld1", "imp", &r),
2749            9952 * 1024 + 512 + 140
2750        );
2751    }
2752
2753    #[test]
2754    fn a_type_argument_names_the_type_before_any_command() {
2755        let mut r = seed_registry();
2756        r.register_command("stat".into(), 3, vec![Type::Stat], vec![Type::Int]);
2757        r.register_command(
2758            "enum_hasoutput".into(),
2759            4,
2760            vec![Type::Int, Type::Enum, Type::Int],
2761            vec![Type::Boolean],
2762        );
2763        r.type_chars.insert("stat".into(), 'S' as i32);
2764        r.type_arguments.insert("enum_hasoutput".into(), 1);
2765        let mut c = Compiler::new(&r);
2766        let mut out = CompiledScript::new("t".into(), 0);
2767        let mut locals = SymbolTable::new();
2768        c.compile_expr_hinted(
2769            &Expr::CommandCall {
2770                name: "enum_hasoutput".into(),
2771                args: vec![
2772                    Expr::Identifier("stat".into()),
2773                    Expr::IntLiteral(5472),
2774                    Expr::IntLiteral(0),
2775                ],
2776                arg_lines: vec![],
2777                call_line: 0,
2778            },
2779            &mut out,
2780            &mut locals,
2781            None,
2782        );
2783        assert!(
2784            matches!(out.instructions[0].operand, Operand::Int(83)),
2785            "{:?}",
2786            out.instructions
2787        );
2788        assert!(
2789            !out.instructions
2790                .iter()
2791                .any(|i| i.opcode == Opcode::Command && matches!(i.operand, Operand::Int(3))),
2792            "{:?}",
2793            out.instructions
2794        );
2795    }
2796
2797    #[test]
2798    fn bare_command_sharing_a_trigger_name_compiles_to_the_command() {
2799        // `if_close` is BOTH the close command (opcode 2033) and the
2800        // `[if_close,...]` trigger (byte 148). A bare `if_close` statement must
2801        // compile to the COMMAND. Regression: the trigger byte used to shadow
2802        // the command in general identifier resolution, so `if_close` silently
2803        // compiled to `push_int(148)` and the close was dropped at runtime.
2804        let mut r = seed_registry();
2805        r.register_command("if_close".into(), 2033, vec![], vec![]);
2806        let mut c = Compiler::new(&r);
2807        let mut out = CompiledScript::new("t".into(), 0);
2808        let mut locals = SymbolTable::new();
2809        c.compile_expr_hinted(
2810            &Expr::Identifier("if_close".into()),
2811            &mut out,
2812            &mut locals,
2813            None,
2814        );
2815        assert!(
2816            out.instructions
2817                .iter()
2818                .any(|i| i.opcode == Opcode::Command && matches!(i.operand, Operand::Int(2033))),
2819            "bare `if_close` should emit Command(2033), got {:?}",
2820            out.instructions
2821        );
2822        assert!(
2823            !out.instructions
2824                .iter()
2825                .any(|i| matches!(i.operand, Operand::Int(148))),
2826            "bare `if_close` must NOT emit the trigger byte 148: {:?}",
2827            out.instructions
2828        );
2829    }
2830
2831    #[test]
2832    fn test_commands_resolve_names_to_ids_but_only_for_themselves() {
2833        // The name->int resolution is scoped to test_op/wait_for arguments only;
2834        // it must never leak into general identifier resolution.
2835        let mut r = seed_registry();
2836        r.register_command("mes".into(), 2064, vec![Type::String], vec![]);
2837        r.register_command("if_close".into(), 2033, vec![], vec![]);
2838        let c = Compiler::new(&r);
2839
2840        // test_op(oploc1, ...): trigger name -> trigger byte (oploc1 = 66).
2841        let mut out = CompiledScript::new("t".into(), 0);
2842        assert!(c.try_emit_test_command_id_arg(
2843            "test_op",
2844            &Expr::Identifier("oploc1".into()),
2845            Some(Type::Int),
2846            &mut out
2847        ));
2848        let last = out.instructions.last().expect("an instruction");
2849        assert!(
2850            matches!(last.operand, Operand::Int(66)),
2851            "got {:?}",
2852            last.operand
2853        );
2854
2855        // wait_for(mes, ...): command name -> command opcode (mes = 2064).
2856        let mut out = CompiledScript::new("t".into(), 0);
2857        assert!(c.try_emit_test_command_id_arg(
2858            "wait_for",
2859            &Expr::Identifier("mes".into()),
2860            Some(Type::Int),
2861            &mut out
2862        ));
2863        let last = out.instructions.last().expect("an instruction");
2864        assert!(
2865            matches!(last.operand, Operand::Int(2064)),
2866            "got {:?}",
2867            last.operand
2868        );
2869
2870        // A NON-test command does not trigger the resolution, so `if_close`
2871        // is left for normal resolution (→ its command opcode) downstream.
2872        let mut out = CompiledScript::new("t".into(), 0);
2873        assert!(!c.try_emit_test_command_id_arg(
2874            "mes",
2875            &Expr::Identifier("if_close".into()),
2876            Some(Type::Int),
2877            &mut out
2878        ));
2879        assert!(out.instructions.is_empty());
2880
2881        // A non-int parameter position is never treated as an id.
2882        let mut out = CompiledScript::new("t".into(), 0);
2883        assert!(!c.try_emit_test_command_id_arg(
2884            "test_op",
2885            &Expr::Identifier("oploc1".into()),
2886            Some(Type::Loc),
2887            &mut out
2888        ));
2889    }
2890}