Skip to main content

runec/
compiler.rs

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