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