Skip to main content

runec/
typechecker.rs

1use crate::diagnostic_messages as msg;
2use crate::diagnostics::{DiagnosticsCollector, Phase};
3use crate::parser::*;
4use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
5use crate::types::{BaseVarType, Type};
6use std::path::{Path, PathBuf};
7
8const TEST_COMMAND_PREFIXES: &[&str] = &[
9    "assert_",
10    "test_",
11    "setup_",
12    "mock_",
13    "verify_",
14    "wait_for_",
15];
16
17const LITERAL_TYPES: &[Type] = &[
18    Type::Int,
19    Type::Boolean,
20    Type::Coord,
21    Type::String,
22    Type::Char,
23    Type::Long,
24];
25
26fn is_literal_type(t: Type) -> bool {
27    LITERAL_TYPES.contains(&t)
28}
29
30pub struct TypeChecker<'a> {
31    pub diagnostics: DiagnosticsCollector,
32    pub registry: &'a SymbolRegistry,
33    file_path: PathBuf,
34    current_script_is_test: bool,
35}
36
37impl<'a> TypeChecker<'a> {
38    pub fn new(registry: &'a SymbolRegistry) -> Self {
39        TypeChecker {
40            diagnostics: DiagnosticsCollector::new(),
41            registry,
42            file_path: PathBuf::new(),
43            current_script_is_test: false,
44        }
45    }
46
47    pub fn check_file(&mut self, file: &ScriptFile, file_path: &Path) {
48        self.check_file_with_test_boundary(file, file_path, None);
49    }
50
51    pub fn check_file_with_test_boundary(
52        &mut self,
53        file: &ScriptFile,
54        file_path: &Path,
55        testscript_line: Option<usize>,
56    ) {
57        self.file_path = file_path.to_path_buf();
58        for script in &file.scripts {
59            self.current_script_is_test = match testscript_line {
60                Some(ts_line) => script.line >= ts_line,
61                None => false,
62            };
63            self.check_script(script);
64        }
65    }
66
67    fn is_test_command(name: &str) -> bool {
68        TEST_COMMAND_PREFIXES
69            .iter()
70            .any(|prefix| name.starts_with(prefix))
71    }
72
73    fn check_script(&mut self, script: &ScriptDeclaration) {
74        let mut locals = SymbolTable::new();
75
76        // Check for duplicate parameter names and invalid parameter types
77        let mut seen_params = std::collections::HashSet::new();
78        for param in &script.params {
79            if !seen_params.insert(param.name.clone()) {
80                self.error(
81                    script.line,
82                    msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[&param.name]),
83                );
84            }
85            // LOCAL_PARAMETER_INVALID_TYPE: certain types can't be used as parameters
86            if !Self::type_allows_parameter(param.param_type) {
87                self.error(
88                    script.line,
89                    msg::fmt(
90                        msg::LOCAL_PARAMETER_INVALID_TYPE,
91                        &[param.param_type.name()],
92                    ),
93                );
94            }
95            locals.define_param(param.name.clone(), param.param_type);
96        }
97
98        // Validate trigger constraints
99        self.check_trigger_constraints(script);
100
101        for stmt in &script.body {
102            self.check_statement(stmt, &mut locals, Some(&script.return_types));
103        }
104    }
105
106    // ──────────────────── Trigger validation ────────────────────
107    // Matching TS ScriptRegistration: checkScriptParameters, checkScriptReturns,
108    // checkScriptSubject
109
110    fn check_trigger_constraints(&mut self, script: &ScriptDeclaration) {
111        let trigger = script.trigger.as_str();
112
113        // Triggers that don't allow parameters.
114        // Most AP/OP/event triggers don't allow parameters (default in TS).
115        // PROC, LABEL, DEBUGPROC, QUEUE, SOFTTIMER, TIMER all allow parameters.
116        match trigger {
117            "walktrigger" | "login" | "logout" if !script.params.is_empty() => {
118                self.error(
119                    script.line,
120                    msg::fmt(msg::SCRIPT_TRIGGER_NO_PARAMETERS, &[trigger]),
121                );
122            }
123            _ => {}
124        }
125
126        // Triggers with required parameter types
127        if let Some(expected_params) = self.trigger_expected_params(trigger) {
128            let actual: Vec<&str> = script.params.iter().map(|p| p.param_type.name()).collect();
129            let expected: Vec<&str> = expected_params.iter().map(|t| t.name()).collect();
130            if actual != expected && !expected.is_empty() {
131                self.error(
132                    script.line,
133                    msg::fmt(
134                        msg::SCRIPT_TRIGGER_EXPECTED_PARAMETERS,
135                        &[trigger, &expected.join(", ")],
136                    ),
137                );
138            }
139        }
140
141        // Triggers that don't allow return values (TS: allowReturns=false default).
142        // Only PROC and LOGOUT have allowReturns=true.
143        match trigger {
144            "debugproc" | "label" | "queue" | "softtimer" | "timer" | "walktrigger" | "login"
145                if !script.return_types.is_empty() =>
146            {
147                self.error(
148                    script.line,
149                    msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[trigger]),
150                );
151            }
152            _ => {}
153        }
154
155        // Triggers with required return types
156        if let Some(expected_returns) = self.trigger_expected_returns(trigger)
157            && script.return_types != expected_returns
158            && !expected_returns.is_empty()
159        {
160            let expected: Vec<&str> = expected_returns.iter().map(|t| t.name()).collect();
161            self.error(
162                script.line,
163                msg::fmt(
164                    msg::SCRIPT_TRIGGER_EXPECTED_RETURNS,
165                    &[trigger, &expected.join(", ")],
166                ),
167            );
168        }
169
170        // Subject validation
171        let subject = &script.name;
172        match trigger {
173            // Global-only triggers: subject must be the script name (no entity reference)
174            "debugproc" | "command" => {}
175
176            // Triggers that reference entity types — validate subject constraints
177            "opnpc1" | "opnpc2" | "opnpc3" | "opnpc4" | "opnpc5" | "opobj1" | "opobj2"
178            | "opobj3" | "opobj4" | "opobj5" | "oploc1" | "oploc2" | "oploc3" | "oploc4"
179            | "oploc5" | "opplayer1" | "opplayer2" | "opplayer3" | "opplayer4" | "opplayer5"
180            | "opnpct" | "opobjt" | "oploct" | "opplayert" | "opnpcu" | "opobju" | "oplocu"
181            | "opplayeru" | "ai_opnpc1" | "ai_opnpc2" | "ai_opnpc3" | "ai_opnpc4" | "ai_opnpc5"
182            | "ai_oploc1" | "ai_oploc2" | "ai_oploc3" | "ai_oploc4" | "ai_oploc5" | "ai_opobj1"
183            | "ai_opobj2" | "ai_opobj3" | "ai_opobj4" | "ai_opobj5" | "ai_opplayer1"
184            | "ai_opplayer2" | "ai_opplayer3" | "ai_opplayer4" | "ai_opplayer5" => {
185                if subject == "_" {
186                    // Global subject is allowed for entity triggers
187                } else if subject.starts_with('_') {
188                    // Category subject — allowed for entity triggers
189                } else if subject.contains(' ') {
190                    self.error(
191                        script.line,
192                        msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
193                    );
194                }
195            }
196
197            // Triggers that only allow global subjects
198            "login" | "logout" | "mapenter" | "mapleave" | "map_enter" | "worldinit"
199            | "worldshutdown"
200                if subject != "_" && !subject.is_empty() =>
201            {
202                self.error(
203                    script.line,
204                    msg::fmt(msg::SCRIPT_SUBJECT_ONLY_GLOBAL, &[trigger]),
205                );
206            }
207
208            // Proc/label/queue: no spaces, no global-only constraint
209            "proc" | "label" | "queue" | "softtimer" | "timer" => {
210                if subject.contains(' ') {
211                    self.error(
212                        script.line,
213                        msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
214                    );
215                }
216                if subject == "_" {
217                    self.error(
218                        script.line,
219                        msg::fmt(msg::SCRIPT_SUBJECT_NO_GLOBAL, &[trigger]),
220                    );
221                }
222                if subject.starts_with('_') && subject.len() > 1 {
223                    self.error(
224                        script.line,
225                        msg::fmt(msg::SCRIPT_SUBJECT_NO_CATEGORY, &[trigger]),
226                    );
227                }
228            }
229
230            _ => {}
231        }
232
233        // SCRIPT_COMMAND_ONLY: '*' suffix is only for command triggers
234        if script.name.ends_with('*') && trigger != "command" {
235            self.error(script.line, msg::SCRIPT_COMMAND_ONLY.to_string());
236        }
237    }
238
239    fn trigger_expected_params(&self, _trigger: &str) -> Option<Vec<Type>> {
240        None
241    }
242
243    fn trigger_expected_returns(&self, _trigger: &str) -> Option<Vec<Type>> {
244        None
245    }
246
247    fn type_allows_declaration(t: Type) -> bool {
248        !matches!(t, Type::Void | Type::Error | Type::Any)
249    }
250
251    fn type_allows_array(t: Type) -> bool {
252        !matches!(t, Type::Void | Type::Error | Type::Any | Type::Long)
253    }
254
255    fn type_allows_parameter(t: Type) -> bool {
256        !matches!(t, Type::Void | Type::Error)
257    }
258
259    fn check_block(
260        &mut self,
261        stmts: &[Statement],
262        parent: &SymbolTable,
263        return_types: Option<&[Type]>,
264    ) {
265        let mut child = parent.new_child();
266        for s in stmts {
267            self.check_statement(s, &mut child, return_types);
268        }
269    }
270
271    fn check_statement(
272        &mut self,
273        stmt: &Statement,
274        locals: &mut SymbolTable,
275        return_types: Option<&[Type]>,
276    ) {
277        match stmt {
278            Statement::VarDeclaration {
279                var_type,
280                name,
281                value,
282                line,
283            } => {
284                // SCRIPT_LOCAL_REDECLARATION
285                if locals.lookup(name).is_some() {
286                    self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
287                }
288                // LOCAL_DECLARATION_INVALID_TYPE
289                if !Self::type_allows_declaration(*var_type) {
290                    self.error(
291                        *line,
292                        msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[var_type.name()]),
293                    );
294                }
295
296                if let Some(init_expr) = value {
297                    self.warn_if_bare_command_value(init_expr, *line);
298                    let expr_type = self.infer_expr_type(init_expr, locals, *line, Some(*var_type));
299                    if let Some(et) = expr_type
300                        && !self.types_compatible(et, *var_type)
301                    {
302                        self.emit_type_mismatch(*line, et, *var_type);
303                    }
304                }
305                locals.define_local(name.clone(), *var_type, false);
306            }
307
308            Statement::ArrayDeclaration {
309                element_type,
310                name,
311                size,
312                line,
313            } => {
314                // SCRIPT_LOCAL_REDECLARATION
315                if locals.lookup(name).is_some() {
316                    self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
317                }
318                // LOCAL_DECLARATION_INVALID_TYPE + LOCAL_ARRAY_INVALID_TYPE
319                if !Self::type_allows_declaration(*element_type) {
320                    self.error(
321                        *line,
322                        msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[element_type.name()]),
323                    );
324                }
325                if !Self::type_allows_array(*element_type) {
326                    self.error(
327                        *line,
328                        msg::fmt(msg::LOCAL_ARRAY_INVALID_TYPE, &[element_type.name()]),
329                    );
330                }
331
332                let size_type = self.infer_expr_type(size, locals, *line, Some(Type::Int));
333                if let Some(st) = size_type
334                    && !self.types_compatible(st, Type::Int)
335                {
336                    self.emit_type_mismatch(*line, st, Type::Int);
337                }
338                locals.define_local(name.clone(), *element_type, true);
339            }
340
341            Statement::Assignment {
342                target,
343                value,
344                line,
345            } => {
346                self.warn_if_bare_command_value(value, *line);
347                let target_type = self.infer_expr_type(target, locals, *line, None);
348                let value_type = self.infer_expr_type(value, locals, *line, target_type);
349                if let (Some(tt), Some(vt)) = (target_type, value_type)
350                    && !self.types_compatible(vt, tt)
351                {
352                    self.emit_type_mismatch(*line, vt, tt);
353                }
354            }
355
356            Statement::If {
357                condition,
358                body,
359                else_if,
360                else_body,
361                line,
362                ..
363            } => {
364                self.check_condition(condition, locals, *line);
365                self.check_block(body, locals, return_types);
366                for (cond, stmts, ei_line) in else_if {
367                    self.check_condition(cond, locals, *ei_line);
368                    self.check_block(stmts, locals, return_types);
369                }
370                if let Some(else_stmts) = else_body {
371                    self.check_block(else_stmts, locals, return_types);
372                }
373            }
374
375            Statement::While {
376                condition,
377                body,
378                line,
379            } => {
380                self.check_condition(condition, locals, *line);
381                self.check_block(body, locals, return_types);
382            }
383
384            Statement::Switch {
385                switch_type,
386                expr,
387                cases,
388                default,
389                line,
390                ..
391            } => {
392                let type_name = switch_type.strip_prefix("switch_").unwrap_or(switch_type);
393                let resolved_type = Type::from_name(type_name);
394                if resolved_type.is_none() {
395                    self.error(*line, msg::fmt(msg::GENERIC_INVALID_TYPE, &[type_name]));
396                }
397                let switch_ty = resolved_type.unwrap_or(Type::Error);
398
399                // SWITCH_INVALID_TYPE: check if the type supports switch
400                if switch_ty != Type::Error && !switch_ty.allow_switch() {
401                    self.error(
402                        *line,
403                        msg::fmt(msg::SWITCH_INVALID_TYPE, &[switch_ty.name()]),
404                    );
405                }
406
407                let expr_type = self.infer_expr_type(expr, locals, *line, Some(switch_ty));
408                if let Some(et) = expr_type
409                    && switch_ty != Type::Error
410                    && !self.types_compatible(et, switch_ty)
411                {
412                    self.emit_type_mismatch(*line, et, switch_ty);
413                }
414
415                // SWITCH_DUPLICATE_DEFAULT: the parser only stores one default block,
416                // so duplicate default detection happens at parse time.
417
418                for case in cases {
419                    self.check_switch_case(case, Some(switch_ty), locals, return_types, *line);
420                }
421                if let Some(default_stmts) = default {
422                    self.check_block(default_stmts, locals, return_types);
423                }
424            }
425
426            Statement::Return { values, line } => {
427                let script_returns = match return_types {
428                    Some(rt) => rt,
429                    None => {
430                        self.error(*line, msg::RETURN_ORPHAN.to_string());
431                        return;
432                    }
433                };
434                let is_single_proc_call = values.len() == 1
435                    && matches!(&values[0], Expr::ProcCall { .. } | Expr::CommandCall { .. });
436                if values.len() != script_returns.len() && !is_single_proc_call {
437                    self.error(
438                        *line,
439                        msg::fmt(
440                            msg::GENERIC_TYPE_MISMATCH,
441                            &[
442                                &format!("{} value(s)", values.len()),
443                                &format!("{} value(s)", script_returns.len()),
444                            ],
445                        ),
446                    );
447                }
448                for (i, val) in values.iter().enumerate() {
449                    let hint = script_returns.get(i).copied();
450                    let val_type = self.infer_expr_type(val, locals, *line, hint);
451                    if let Some(vt) = val_type
452                        && let Some(expected) = hint
453                        && !self.types_compatible(vt, expected)
454                    {
455                        self.emit_type_mismatch(*line, vt, expected);
456                    }
457                }
458            }
459
460            Statement::Expression { expr, line } => {
461                // A bare command reference used as a statement (e.g. `mes;`)
462                // compiles to its opcode and is discarded — flag it specifically.
463                let bare_cmd = self.warn_if_bare_command_value(expr, *line);
464                let expr_type = self.infer_expr_type(expr, locals, *line, None);
465                if !bare_cmd
466                    && let Some(et) = expr_type
467                    && et != Type::Error
468                    && !self.expression_has_side_effects(expr)
469                {
470                    self.warning(*line, msg::EXPRESSION_STATEMENT_NO_SIDE_EFFECT.to_string());
471                }
472            }
473            Statement::OrphanCase { case, line } => {
474                self.check_switch_case(case, None, locals, return_types, *line);
475            }
476            Statement::Empty => {}
477        }
478    }
479
480    fn check_condition(&mut self, expr: &Expr, locals: &SymbolTable, line: usize) {
481        match expr {
482            Expr::BinaryOp { op, lhs, rhs } => {
483                // CONDITION_NOT_VALID: non-logical operators can't have condition
484                // sub-expressions (e.g. `if (($a < $b) = ($c < $d))` is invalid)
485                match op {
486                    BinOp::Eq
487                    | BinOp::NotEq
488                    | BinOp::Lt
489                    | BinOp::Gt
490                    | BinOp::LtEq
491                    | BinOp::GtEq
492                        if (self.is_condition_expr(lhs) || self.is_condition_expr(rhs)) =>
493                    {
494                        self.error(line, msg::CONDITION_NOT_VALID.to_string());
495                        return;
496                    }
497                    _ => {}
498                }
499
500                let lt = self.infer_expr_type(lhs, locals, line, None);
501                let rhs_hint = lt;
502                let rt = self.infer_expr_type(rhs, locals, line, rhs_hint);
503
504                match op {
505                    BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
506                        if let Some(ref lt) = lt
507                            && lt.base_type() == BaseVarType::String
508                            && *lt != Type::Error
509                            && *lt != Type::Any
510                        {
511                            self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
512                        }
513                        if let Some(ref rt) = rt
514                            && rt.base_type() == BaseVarType::String
515                            && *rt != Type::Error
516                            && *rt != Type::Any
517                        {
518                            self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
519                        }
520                    }
521                    BinOp::Eq | BinOp::NotEq => {
522                        if let (Some(lt), Some(rt)) = (&lt, &rt)
523                            && *lt == Type::String
524                            && *rt == Type::String
525                        {
526                            let op_str = if *op == BinOp::Eq { "=" } else { "!" };
527                            self.error(
528                                line,
529                                msg::fmt(msg::BINOP_INVALID_TYPES, &[op_str, lt.name(), rt.name()]),
530                            );
531                        }
532                    }
533                    _ => {}
534                }
535            }
536            Expr::LogicalOp { lhs, rhs, .. } => {
537                self.check_condition(lhs, locals, line);
538                self.check_condition(rhs, locals, line);
539            }
540            _ => {
541                self.error(line, msg::CONDITION_INVALID_NODE_TYPE.to_string());
542            }
543        }
544    }
545
546    fn is_condition_expr(&self, expr: &Expr) -> bool {
547        match expr {
548            Expr::BinaryOp { op, .. } => matches!(
549                op,
550                BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq
551            ),
552            Expr::LogicalOp { .. } => true,
553            _ => false,
554        }
555    }
556
557    /// Mirrors TS `visitSwitchCase`: type-checks a single switch case entry.
558    /// `parent_switch_type` is `Some` when the case is inside a switch statement,
559    /// `None` if the case was somehow orphaned (CASE_WITHOUT_SWITCH).
560    fn check_switch_case(
561        &mut self,
562        case: &SwitchCase,
563        parent_switch_type: Option<Type>,
564        locals: &SymbolTable,
565        return_types: Option<&[Type]>,
566        line: usize,
567    ) {
568        let switch_ty = match parent_switch_type {
569            Some(t) => t,
570            None => {
571                self.error(line, msg::CASE_WITHOUT_SWITCH.to_string());
572                return;
573            }
574        };
575
576        for val in &case.values {
577            if !self.is_constant_expression(val) {
578                self.warning(line, msg::SWITCH_CASE_NOT_CONSTANT.to_string());
579            }
580            let val_type = self.infer_expr_type(val, locals, line, Some(switch_ty));
581            if let Some(vt) = val_type
582                && switch_ty != Type::Error
583                && !self.types_compatible(vt, switch_ty)
584            {
585                self.emit_type_mismatch(line, vt, switch_ty);
586            }
587        }
588        self.check_block(&case.body, locals, return_types);
589    }
590
591    /// Infer the type of an expression with an optional type hint.
592    /// The hint flows top-down from context (command params, variable type, etc.)
593    /// and is used for context-aware identifier/literal resolution — the same
594    /// approach codegen uses via `compile_expr_hinted`.
595    fn infer_expr_type(
596        &mut self,
597        expr: &Expr,
598        locals: &SymbolTable,
599        line: usize,
600        hint: Option<Type>,
601    ) -> Option<Type> {
602        match expr {
603            Expr::IntLiteral(_) => {
604                // Matching TS visitIntegerLiteral: if hint is a non-literal type,
605                // the integer is treated as a symbol reference of that type.
606                if let Some(h) = hint {
607                    if !is_literal_type(h) && h != Type::Error && h != Type::Any {
608                        return Some(h);
609                    }
610                    if h == Type::Boolean {
611                        return Some(Type::Boolean);
612                    }
613                }
614                Some(Type::Int)
615            }
616            Expr::LongLiteral(_) => Some(Type::Long),
617            Expr::StringLiteral(s) => {
618                // Matching TS visitStringLiteral: if hint is a non-literal type,
619                // the string is treated as a symbol reference (e.g. "sailing journey"
620                // with hint=midi resolves to a midi entity).
621                if let Some(h) = hint
622                    && !is_literal_type(h)
623                    && h != Type::Error
624                    && h != Type::Any
625                {
626                    // Verify the name resolves against the registry.
627                    // If it doesn't, surface a warning so silent
628                    // fallthrough to `push_string` at codegen doesn't
629                    // produce a runtime bug.
630                    //
631                    // Mirror the identifier-path resolution cascade:
632                    //   1. typed entity table (strict)
633                    //   2. untyped entity table (subtype tolerance,
634                    //      e.g. obj ⊂ namedobj)
635                    //   3. proc/script registries (for proc/label/
636                    //      queue/timer/walktrigger hints)
637                    let typed_ok = self.registry.lookup_entity_id_typed(s, h).is_some();
638                    let untyped_ok = self.registry.lookup_entity_id(s).is_some();
639                    let script_ok = self.registry.proc_script_id(s).is_some()
640                        || self.registry.script_id(s).is_some();
641                    if !typed_ok && !untyped_ok && !script_ok {
642                        self.emit_unresolved_entity_warning(line, s, h);
643                    } else if is_valid_bare_ident(s) {
644                        // The string literal resolves AND its name is a
645                        // legal bare identifier — recommend the bare form
646                        // for clarity.
647                        self.emit_prefer_bare_ident_warning(line, s, h);
648                    }
649                    return Some(h);
650                }
651                Some(Type::String)
652            }
653            Expr::BoolLiteral(_) => Some(Type::Boolean),
654            Expr::NullLiteral => {
655                // Matching TS visitNullLiteral: use hint if provided
656                if let Some(h) = hint
657                    && h != Type::Error
658                {
659                    return Some(h);
660                }
661                Some(Type::Int)
662            }
663            Expr::CharLiteral(_) => Some(Type::Char),
664            Expr::CoordLiteral(_) => Some(Type::Coord),
665
666            Expr::LocalVar(name, src_line) => {
667                if let Some(sym) = locals.lookup(name) {
668                    match &sym.kind {
669                        SymbolKind::LocalVar {
670                            var_type, is_array, ..
671                        } => {
672                            // LOCAL_ARRAY_REFERENCE_NOINDEX: array var used without index
673                            if *is_array {
674                                self.error(
675                                    *src_line,
676                                    msg::fmt(msg::LOCAL_ARRAY_REFERENCE_NOINDEX, &[name]),
677                                );
678                                return Some(Type::Error);
679                            }
680                            Some(*var_type)
681                        }
682                        SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
683                        _ => None,
684                    }
685                } else {
686                    self.error(
687                        *src_line,
688                        msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]),
689                    );
690                    Some(Type::Error)
691                }
692            }
693
694            Expr::ArrayAccess { name, index } => {
695                if let Some(sym) = locals.lookup(name) {
696                    match &sym.kind {
697                        SymbolKind::LocalVar {
698                            var_type, is_array, ..
699                        } => {
700                            if !is_array {
701                                // LOCAL_REFERENCE_NOT_ARRAY: indexing a non-array
702                                self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
703                            }
704                            let idx_type =
705                                self.infer_expr_type(index, locals, line, Some(Type::Int));
706                            if let Some(it) = idx_type
707                                && !self.types_compatible(it, Type::Int)
708                            {
709                                self.emit_type_mismatch(line, it, Type::Int);
710                            }
711                            Some(*var_type)
712                        }
713                        SymbolKind::ScriptParam { param_type, .. } => {
714                            self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
715                            Some(*param_type)
716                        }
717                        _ => None,
718                    }
719                } else {
720                    self.error(line, msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]));
721                    Some(Type::Error)
722                }
723            }
724
725            Expr::GameVar(name, src_line) => {
726                if let Some(sym) = self.registry.lookup_game_var(name) {
727                    match &sym.kind {
728                        SymbolKind::GameVar { var_type, .. } => Some(*var_type),
729                        _ => None,
730                    }
731                } else {
732                    self.error(*src_line, msg::fmt(msg::GAME_REFERENCE_UNRESOLVED, &[name]));
733                    Some(Type::Error)
734                }
735            }
736
737            Expr::ConstantVar(name, src_line) => {
738                if let Some(sym) = self.registry.lookup_constant(name) {
739                    match &sym.kind {
740                        SymbolKind::Constant { const_type, .. } => Some(*const_type),
741                        _ => None,
742                    }
743                } else {
744                    self.error(
745                        *src_line,
746                        msg::fmt(msg::CONSTANT_REFERENCE_UNRESOLVED, &[name]),
747                    );
748                    Some(Type::Error)
749                }
750            }
751
752            Expr::Identifier(name) => {
753                // Type-aware resolution: if hint is provided and there's a typed entity match, use it.
754                // This mirrors codegen's compile_expr_hinted (compiler.rs:1079).
755                if let Some(h) = hint
756                    && h != Type::Error
757                    && h != Type::Any
758                    && self.registry.lookup_entity_id_typed(name, h).is_some()
759                {
760                    return Some(h);
761                }
762
763                // When hint is Int, type chars (coord, obj, stat, …) take
764                // priority over same-named commands so that e.g.
765                // enum(int, coord, …) resolves `coord` as the type-char
766                // constant rather than the `coord` command.
767                if hint == Some(Type::Int) && self.registry.type_chars.contains_key(name) {
768                    return Some(Type::Int);
769                }
770
771                // Fallback: constants → entity IDs → commands → type chars
772                if let Some(sym) = self.registry.lookup_constant(name) {
773                    match &sym.kind {
774                        SymbolKind::Constant { const_type, .. } => Some(*const_type),
775                        other => {
776                            let kind_name = other.kind_name();
777                            self.error(
778                                line,
779                                msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[kind_name]),
780                            );
781                            Some(Type::Error)
782                        }
783                    }
784                } else if let Some(sym) = self.registry.lookup_entity_id(name) {
785                    match &sym.kind {
786                        SymbolKind::Constant { const_type, .. } => Some(*const_type),
787                        other => {
788                            let kind_name = other.kind_name();
789                            self.error(
790                                line,
791                                msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[kind_name]),
792                            );
793                            Some(Type::Error)
794                        }
795                    }
796                } else if let Some(sym) = self.registry.lookup_command(name).cloned() {
797                    if let SymbolKind::Command { return_types, .. } = &sym.kind {
798                        return return_types.first().copied();
799                    }
800                    self.error(
801                        line,
802                        msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[sym.kind.kind_name()]),
803                    );
804                    Some(Type::Error)
805                } else if self.registry.type_chars.contains_key(name) {
806                    Some(Type::Int)
807                } else if name.contains(':') {
808                    // Component reference: "interface:component"
809                    let parts: Vec<&str> = name.splitn(2, ':').collect();
810                    if parts.len() == 2
811                        && self.registry.lookup_component(parts[0], parts[1]).is_some()
812                    {
813                        Some(hint.unwrap_or(Type::Component))
814                    } else if let Some(h) = hint {
815                        if h != Type::Error {
816                            Some(h)
817                        } else {
818                            Some(Type::Error)
819                        }
820                    } else {
821                        self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
822                        Some(Type::Error)
823                    }
824                } else {
825                    // Matching TS resolveSymbol:
826                    // - If hint is String, treat identifier as string (allowToString)
827                    // - If hint exists, trust it (codegen resolves via entity_ids_typed)
828                    // - If no hint and no match, emit error
829                    if let Some(h) = hint {
830                        if h == Type::String {
831                            return Some(Type::String);
832                        }
833                        if h != Type::Error {
834                            // Before "trusting the hint", verify the name
835                            // actually resolves somewhere. If not, codegen
836                            // will silently emit push_int(-1) for unknown
837                            // identifiers — surface a warning so the typo is
838                            // visible at compile time.
839                            //
840                            // Resolution sources (matching codegen's cascade
841                            // in compile_expr for Ident):
842                            //   1. entity_ids_typed (typed entities)
843                            //   2. entity_ids (untyped entity fallback)
844                            //   3. trigger_table::byte (server trigger names
845                            //      like `oploc1`, `apnpc1`)
846                            //   4. command_opcode (bare command names used as
847                            //      the opcode literal when hint is Int)
848                            //   5. proc_script_id / script_id (script refs
849                            //      for proc/label/queue/timer/walktrigger
850                            //      params)
851                            let resolved = self.registry.lookup_entity_id_typed(name, h).is_some()
852                                || self.registry.lookup_entity_id(name).is_some()
853                                || crate::trigger_table::byte(name).is_some()
854                                || (h == Type::Int && self.registry.command_opcode(name).is_some())
855                                || self.registry.proc_script_id(name).is_some()
856                                || self.registry.script_id(name).is_some();
857                            if !resolved {
858                                self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
859                                return Some(Type::Error);
860                            }
861                            return Some(h);
862                        }
863                    }
864                    self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
865                    Some(Type::Error)
866                }
867            }
868
869            Expr::BinaryOp { op, lhs, rhs } => match op {
870                BinOp::Add
871                | BinOp::Sub
872                | BinOp::Mul
873                | BinOp::Div
874                | BinOp::Mod
875                | BinOp::BitAnd
876                | BinOp::BitOr => {
877                    // Entity names may contain `+` (e.g. `cheese+tom_batta`,
878                    // `premade_cheese+tom_batta`). The parser represents these
879                    // as BinaryOp::Add with two Identifier children. Before
880                    // descending (which would fire spurious "unresolved"
881                    // warnings on each half), check if the combined name
882                    // resolves as a single entity and short-circuit.
883                    if matches!(op, BinOp::Add)
884                        && let (Expr::Identifier(lname), Expr::Identifier(rname)) =
885                            (lhs.as_ref(), rhs.as_ref())
886                    {
887                        let combined = format!("{}+{}", lname, rname);
888                        if let Some(h) = hint {
889                            if self.registry.lookup_entity_id_typed(&combined, h).is_some()
890                                || self.registry.lookup_entity_id(&combined).is_some()
891                            {
892                                return Some(h);
893                            }
894                        } else if self.registry.lookup_entity_id(&combined).is_some()
895                            && let Some(sym) = self.registry.lookup_entity_id(&combined)
896                            && let SymbolKind::Constant { const_type, .. } = &sym.kind
897                        {
898                            return Some(*const_type);
899                        }
900                    }
901
902                    let expected = hint.unwrap_or(Type::Int);
903                    let lt = self.infer_expr_type(lhs, locals, line, Some(expected));
904                    let rt = self.infer_expr_type(rhs, locals, line, Some(expected));
905                    if let Some(ref lt) = lt
906                        && lt.base_type() == BaseVarType::String
907                        && *lt != Type::Error
908                        && *lt != Type::Any
909                    {
910                        self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
911                    }
912                    if let Some(ref rt) = rt
913                        && rt.base_type() == BaseVarType::String
914                        && *rt != Type::Error
915                        && *rt != Type::Any
916                    {
917                        self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
918                    }
919                    if matches!(lt, Some(Type::Long)) || matches!(rt, Some(Type::Long)) {
920                        Some(Type::Long)
921                    } else {
922                        Some(hint.unwrap_or(Type::Int))
923                    }
924                }
925                BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
926                    let lt = self.infer_expr_type(lhs, locals, line, None);
927                    let _ = self.infer_expr_type(rhs, locals, line, lt);
928                    Some(Type::Boolean)
929                }
930            },
931
932            Expr::LogicalOp { lhs, rhs, .. } => {
933                let _ = self.infer_expr_type(lhs, locals, line, None);
934                let _ = self.infer_expr_type(rhs, locals, line, None);
935                Some(Type::Boolean)
936            }
937
938            Expr::Calc(inner) => {
939                let expected = hint.unwrap_or(Type::Int);
940                let inner_type = self.infer_expr_type(inner, locals, line, Some(expected));
941                if let Some(ref it) = inner_type
942                    && it.base_type() == BaseVarType::String
943                    && *it != Type::Error
944                    && *it != Type::Any
945                {
946                    self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[it.name()]));
947                }
948                inner_type
949            }
950
951            Expr::CommandCall {
952                name,
953                args,
954                call_line,
955                ..
956            } => {
957                let lookup_name = name.strip_prefix('.').unwrap_or(name);
958
959                if !self.current_script_is_test && Self::is_test_command(lookup_name) {
960                    self.error(
961                        *call_line,
962                        msg::fmt(msg::TEST_COMMAND_FROM_PRODUCTION, &[lookup_name]),
963                    );
964                }
965
966                // Look up command param types for hinting (same as compiler.rs:1345-1399)
967                let param_types: Vec<Type> = self
968                    .registry
969                    .command_param_types
970                    .get(lookup_name)
971                    .cloned()
972                    .unwrap_or_default();
973
974                let arg_types: Vec<Option<Type>> = args
975                    .iter()
976                    .enumerate()
977                    .map(|(i, a)| {
978                        let arg_hint = param_types.get(i).copied();
979                        self.infer_expr_type(a, locals, *call_line, arg_hint)
980                    })
981                    .collect();
982
983                let is_variadic = lookup_name.ends_with('*');
984                let cmd_sym = self
985                    .registry
986                    .lookup_command(lookup_name)
987                    .cloned()
988                    .or_else(|| {
989                        lookup_name.strip_suffix('*').and_then(|base| {
990                            let vararg_name = format!("{}vararg", base);
991                            self.registry.lookup_command(&vararg_name).cloned()
992                        })
993                    });
994                if let Some(sym) = cmd_sym {
995                    if let SymbolKind::Command {
996                        param_types: cmd_params,
997                        return_types,
998                        ..
999                    } = &sym.kind
1000                    {
1001                        if !is_variadic {
1002                            self.check_call_arguments(
1003                                name,
1004                                cmd_params,
1005                                &arg_types,
1006                                args,
1007                                *call_line,
1008                                CallKind::Command,
1009                            );
1010                        }
1011                        return return_types.first().copied();
1012                    }
1013                } else {
1014                    self.error(
1015                        *call_line,
1016                        msg::fmt(msg::COMMAND_REFERENCE_UNRESOLVED, &[name]),
1017                    );
1018                    return Some(Type::Error);
1019                }
1020                None
1021            }
1022
1023            Expr::ProcCall {
1024                name,
1025                args,
1026                call_line,
1027                ..
1028            } => {
1029                // Use trigger-scoped lookup to avoid name collisions
1030                let script_sym = self
1031                    .registry
1032                    .lookup_script_by_trigger("proc", name)
1033                    .cloned();
1034
1035                if self.registry.proc_script_id(name).is_none() {
1036                    self.error(
1037                        *call_line,
1038                        msg::fmt(msg::PROC_REFERENCE_UNRESOLVED, &[name]),
1039                    );
1040                    // Still infer arg types even on error
1041                    for arg in args {
1042                        let _ = self.infer_expr_type(arg, locals, *call_line, None);
1043                    }
1044                    return Some(Type::Error);
1045                }
1046
1047                if !self.current_script_is_test && self.registry.is_test_script("proc", name) {
1048                    self.error(
1049                        *call_line,
1050                        msg::fmt(msg::TEST_PROC_FROM_PRODUCTION, &[name]),
1051                    );
1052                }
1053
1054                let (p_types, r_types) = if let Some(ref sym) = script_sym {
1055                    if let SymbolKind::Script {
1056                        param_types,
1057                        return_types,
1058                        ..
1059                    } = &sym.kind
1060                    {
1061                        (param_types.clone(), return_types.clone())
1062                    } else {
1063                        (vec![], vec![])
1064                    }
1065                } else {
1066                    (vec![], vec![])
1067                };
1068
1069                let arg_types: Vec<Option<Type>> = args
1070                    .iter()
1071                    .enumerate()
1072                    .map(|(i, a)| {
1073                        let arg_hint = p_types.get(i).copied();
1074                        self.infer_expr_type(a, locals, *call_line, arg_hint)
1075                    })
1076                    .collect();
1077
1078                if script_sym.is_some() {
1079                    self.check_call_arguments(
1080                        name,
1081                        &p_types,
1082                        &arg_types,
1083                        args,
1084                        *call_line,
1085                        CallKind::Proc,
1086                    );
1087                }
1088                r_types.first().copied()
1089            }
1090
1091            Expr::JumpCall {
1092                name,
1093                args,
1094                call_line,
1095                ..
1096            } => {
1097                let script_sym = self
1098                    .registry
1099                    .lookup_script_by_trigger("label", name)
1100                    .cloned();
1101
1102                if self.registry.label_script_id(name).is_none() {
1103                    self.error(
1104                        *call_line,
1105                        msg::fmt(msg::JUMP_REFERENCE_UNRESOLVED, &[name]),
1106                    );
1107                    for arg in args {
1108                        let _ = self.infer_expr_type(arg, locals, *call_line, None);
1109                    }
1110                    return Some(Type::Error);
1111                }
1112
1113                if !self.current_script_is_test && self.registry.is_test_script("label", name) {
1114                    self.error(
1115                        *call_line,
1116                        msg::fmt(msg::TEST_LABEL_FROM_PRODUCTION, &[name]),
1117                    );
1118                }
1119
1120                let p_types = if let Some(ref sym) = script_sym {
1121                    if let SymbolKind::Script { param_types, .. } = &sym.kind {
1122                        param_types.clone()
1123                    } else {
1124                        vec![]
1125                    }
1126                } else {
1127                    vec![]
1128                };
1129
1130                let arg_types: Vec<Option<Type>> = args
1131                    .iter()
1132                    .enumerate()
1133                    .map(|(i, a)| {
1134                        let arg_hint = p_types.get(i).copied();
1135                        self.infer_expr_type(a, locals, *call_line, arg_hint)
1136                    })
1137                    .collect();
1138
1139                if script_sym.is_some() {
1140                    self.check_call_arguments(
1141                        name,
1142                        &p_types,
1143                        &arg_types,
1144                        args,
1145                        *call_line,
1146                        CallKind::Jump,
1147                    );
1148                }
1149                None
1150            }
1151
1152            Expr::JoinedString { parts } => {
1153                for part in parts {
1154                    if let StringPart::Expr(e) = part {
1155                        let _ = self.infer_expr_type(e, locals, line, Some(Type::String));
1156                    }
1157                }
1158                Some(Type::String)
1159            }
1160
1161            Expr::MultiAssign(targets, _) => {
1162                // ASSIGN_MULTI_ARRAY: arrays are not allowed in multi-assignment
1163                for target in targets {
1164                    if let Expr::ArrayAccess { name, .. } = target {
1165                        self.error(line, msg::fmt(msg::ASSIGN_MULTI_ARRAY, &[name]));
1166                    }
1167                }
1168                None
1169            }
1170        }
1171    }
1172
1173    // ──────────────────── Call argument validation ────────────────────
1174
1175    fn check_call_arguments(
1176        &mut self,
1177        name: &str,
1178        expected_types: &[Type],
1179        actual_types: &[Option<Type>],
1180        args: &[Expr],
1181        line: usize,
1182        kind: CallKind,
1183    ) {
1184        // For commands, empty param_types means "signature unknown"
1185        if expected_types.is_empty() {
1186            if kind == CallKind::Command {
1187                return;
1188            }
1189            // A single null arg to a no-param proc is valid (null = unit)
1190            let is_single_null = args.len() == 1 && matches!(&args[0], Expr::NullLiteral);
1191            if !actual_types.is_empty() && !is_single_null {
1192                let actual_desc = actual_types
1193                    .iter()
1194                    .map(|t| t.map_or("unknown".to_string(), |t| t.name().to_string()))
1195                    .collect::<Vec<_>>()
1196                    .join(", ");
1197                let template = match kind {
1198                    CallKind::Proc => msg::PROC_NOARGS_EXPECTED,
1199                    CallKind::Jump => msg::JUMP_NOARGS_EXPECTED,
1200                    CallKind::Command => msg::COMMAND_NOARGS_EXPECTED,
1201                };
1202                self.error(line, msg::fmt(template, &[name, &actual_desc]));
1203            }
1204            return;
1205        }
1206
1207        // Proc/command call args can produce multiple return values,
1208        // making the actual arg count less than the number of values produced.
1209        // Skip count validation when any arg is a multi-return call.
1210        let has_call_arg = args
1211            .iter()
1212            .any(|a| matches!(a, Expr::ProcCall { .. } | Expr::CommandCall { .. }));
1213
1214        if expected_types.len() != actual_types.len() {
1215            if has_call_arg {
1216                return;
1217            }
1218            // Strict command arg-count was tightened for the #testscript
1219            // assertion framework. Production keeps main's behaviour: a command
1220            // signature may be variadic or only partially known in the symbol
1221            // set, so enforcing exact arity on commands false-positives on
1222            // production content (esp. 225). Only procs/jumps are strictly
1223            // arg-counted outside test scripts.
1224            if kind == CallKind::Command && !self.current_script_is_test {
1225                return;
1226            }
1227            self.error(
1228                line,
1229                msg::fmt(
1230                    msg::GENERIC_TYPE_MISMATCH,
1231                    &[
1232                        &format!("{} arg(s)", actual_types.len()),
1233                        &format!("{} arg(s)", expected_types.len()),
1234                    ],
1235                ),
1236            );
1237            return;
1238        }
1239
1240        for (i, (expected, actual)) in expected_types.iter().zip(actual_types.iter()).enumerate() {
1241            if let Some(actual_ty) = actual
1242                && !self.types_compatible(*actual_ty, *expected)
1243            {
1244                self.error(
1245                    line,
1246                    msg::fmt(
1247                        msg::GENERIC_TYPE_MISMATCH,
1248                        &[actual_ty.name(), expected.name()],
1249                    ),
1250                );
1251                let _ = i;
1252            }
1253        }
1254    }
1255
1256    // ──────────────────── Constant expression check ────────────────────
1257
1258    fn is_constant_expression(&self, expr: &Expr) -> bool {
1259        match expr {
1260            Expr::IntLiteral(_)
1261            | Expr::LongLiteral(_)
1262            | Expr::StringLiteral(_)
1263            | Expr::BoolLiteral(_)
1264            | Expr::NullLiteral
1265            | Expr::CharLiteral(_)
1266            | Expr::CoordLiteral(_) => true,
1267            Expr::ConstantVar(..) => true,
1268            Expr::Identifier(name) => {
1269                self.registry.lookup_constant(name).is_some()
1270                    || self.registry.lookup_entity_id(name).is_some()
1271                    || self.registry.type_chars.contains_key(name)
1272                    // Component references: "interface:component"
1273                    || name.contains(':') && {
1274                        let parts: Vec<&str> = name.splitn(2, ':').collect();
1275                        parts.len() == 2
1276                            && self
1277                                .registry
1278                                .lookup_component(parts[0], parts[1])
1279                                .is_some()
1280                    }
1281            }
1282            // Entity names containing '+' (e.g. cheese+tom_batta): the parser
1283            // splits these into BinaryOp::Add but codegen recombines them.
1284            Expr::BinaryOp {
1285                op: BinOp::Add,
1286                lhs,
1287                rhs,
1288            } => {
1289                if let (Expr::Identifier(l), Expr::Identifier(r)) = (lhs.as_ref(), rhs.as_ref()) {
1290                    let combined = format!("{}+{}", l, r);
1291                    self.registry.lookup_entity_id(&combined).is_some()
1292                } else {
1293                    false
1294                }
1295            }
1296            _ => false,
1297        }
1298    }
1299
1300    // ──────────────────── Side-effect analysis ────────────────────
1301
1302    fn expression_has_side_effects(&self, expr: &Expr) -> bool {
1303        match expr {
1304            Expr::CommandCall { .. } | Expr::ProcCall { .. } | Expr::JumpCall { .. } => true,
1305            Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
1306                self.expression_has_side_effects(lhs) || self.expression_has_side_effects(rhs)
1307            }
1308            Expr::Calc(inner) => self.expression_has_side_effects(inner),
1309            Expr::JoinedString { parts } => parts.iter().any(|p| {
1310                if let StringPart::Expr(e) = p {
1311                    self.expression_has_side_effects(e)
1312                } else {
1313                    false
1314                }
1315            }),
1316            _ => false,
1317        }
1318    }
1319
1320    // ──────────────────── Type compatibility ────────────────────
1321    // Matching TS compiler's registered TypeCheckers (ScriptCompiler.ts:129-189)
1322
1323    fn types_compatible(&self, actual: Type, expected: Type) -> bool {
1324        // Rule 1: Any accepts anything
1325        if expected == Type::Any {
1326            return true;
1327        }
1328        // Rule 2: Error on either side prevents cascading
1329        if expected == Type::Error || actual == Type::Error {
1330            return true;
1331        }
1332        // Rule 3: Exact match
1333        if actual == expected {
1334            return true;
1335        }
1336        // Rule 4 (server): obj and namedobj are interchangeable
1337        if (expected == Type::Obj && actual == Type::NamedObj)
1338            || (expected == Type::NamedObj && actual == Type::Obj)
1339        {
1340            return true;
1341        }
1342        // Rule 5: Any actual also matches (symmetric with rule 1)
1343        if actual == Type::Any {
1344            return true;
1345        }
1346        // Rule 6: Int widens to any integer-base named type. Scripts use
1347        // `def_int` for computed IDs (interface, component, npc, etc.) and
1348        // pass them to commands expecting a named type. The reverse (named
1349        // type → int) is NOT allowed — catches errors like passing
1350        // npc_mode to tostring(int).
1351        if actual == Type::Int && expected.base_type() == BaseVarType::Integer {
1352            return true;
1353        }
1354        // Rule 7: Boolean and Obj narrow to Int. These types are
1355        // semantically raw integers (boolean=0/1, obj=entity ID) and
1356        // scripts pass them to int-typed commands like assert_eq.
1357        if matches!(actual, Type::Boolean | Type::Obj) && expected == Type::Int {
1358            return true;
1359        }
1360        // Rule 8 (production only): integer-base interchangeability. Any two
1361        // integer-base named types (interface, queue, timer, label, obj, …) are
1362        // mutually compatible *outside* test scripts. This restores the
1363        // pre-#testscript behaviour: hint-based resolution isn't yet complete
1364        // enough to pick the right namespace when a name exists in several
1365        // (e.g. a `queue` shadowed by an interface of the same name), so without
1366        // this, valid production scripts — especially 225 content — false
1367        // positive. The strict Rules 6–7 still apply under `#testscript`, where
1368        // assertions (assert_eq, …) need exact types.
1369        if !self.current_script_is_test
1370            && actual.base_type() == BaseVarType::Integer
1371            && expected.base_type() == BaseVarType::Integer
1372        {
1373            return true;
1374        }
1375        false
1376    }
1377
1378    /// Lint a value-context expression (declaration initializer / assignment
1379    /// RHS, or a standalone expression statement): a lone bare command
1380    /// reference there compiles to the command's opcode (an int literal),
1381    /// not the result of calling it. Passing a command's opcode as an
1382    /// *argument* (e.g. `wait_for(mes, 20)`) is a legitimate test pattern,
1383    /// which is why this only fires in value/statement contexts — not on
1384    /// command/proc arguments. Returns true if a warning was emitted.
1385    fn warn_if_bare_command_value(&mut self, expr: &Expr, line: usize) -> bool {
1386        if let Expr::Identifier(name) = expr {
1387            let requires_args = self
1388                .registry
1389                .command_param_types
1390                .get(name)
1391                .is_some_and(|p| !p.is_empty());
1392            // Only commands (not constants/entities/locals) reach here as a
1393            // mistake; the registry lookup confirms it's a command.
1394            if requires_args && self.registry.lookup_command(name).is_some() {
1395                self.warning(
1396                    line,
1397                    msg::fmt(msg::COMMAND_BARE_REQUIRES_ARGS, &[name, name]),
1398                );
1399                return true;
1400            }
1401        }
1402        false
1403    }
1404
1405    // ──────────────────── Diagnostic helpers ────────────────────
1406
1407    fn emit_type_mismatch(&mut self, line: usize, actual: Type, expected: Type) {
1408        self.error(
1409            line,
1410            msg::fmt(
1411                msg::GENERIC_TYPE_MISMATCH,
1412                &[actual.name(), expected.name()],
1413            ),
1414        );
1415    }
1416
1417    fn error(&mut self, line: usize, message: String) {
1418        self.diagnostics.error(
1419            self.file_path.clone(),
1420            line,
1421            0,
1422            message,
1423            Phase::TypeChecking,
1424        );
1425    }
1426
1427    fn warning(&mut self, line: usize, message: String) {
1428        self.diagnostics.warning(
1429            self.file_path.clone(),
1430            line,
1431            0,
1432            message,
1433            Phase::TypeChecking,
1434        );
1435    }
1436
1437    /// Emit a warning with attached Help (and optional Suggestion) in one
1438    /// call — mirrors `warning` but threads a `Help` block through.
1439    fn warning_with_help(&mut self, line: usize, message: String, help: crate::diagnostics::Help) {
1440        use crate::diagnostics::{Diagnostic, Severity};
1441        self.diagnostics.add(Diagnostic {
1442            file: self.file_path.clone(),
1443            line,
1444            column: 0,
1445            message,
1446            severity: Severity::Warning,
1447            phase: Phase::TypeChecking,
1448            help: vec![help],
1449        });
1450    }
1451
1452    /// Emit UNRESOLVED_ENTITY_REF with a "did you mean?" suggestion list
1453    /// pulled from the nearest names in the expected type's entity table.
1454    fn emit_unresolved_entity_warning(&mut self, line: usize, name: &str, expected: Type) {
1455        use crate::diagnostics::{Applicability, Help};
1456
1457        let message = msg::fmt(msg::UNRESOLVED_ENTITY_REF, &[name, expected.name()]);
1458
1459        let near = self.near_entity_names(name, expected, 2, 3);
1460        let help_message = if near.is_empty() {
1461            format!(
1462                "Check the `{}` pack/registry for the canonical name, or remove \
1463                 the reference if it's stale.",
1464                expected.name()
1465            )
1466        } else {
1467            let suggestions = near
1468                .iter()
1469                .map(|n| format!("`{}`", n))
1470                .collect::<Vec<_>>()
1471                .join(", ");
1472            format!("Did you mean one of: {}?", suggestions)
1473        };
1474
1475        self.warning_with_help(
1476            line,
1477            message,
1478            Help {
1479                message: help_message,
1480                suggestions: Vec::new(),
1481                applicability: Applicability::MaybeIncorrect,
1482            },
1483        );
1484    }
1485
1486    /// Emit PREFER_BARE_IDENT with a one-line rewrite suggestion.
1487    fn emit_prefer_bare_ident_warning(&mut self, line: usize, name: &str, expected: Type) {
1488        use crate::diagnostics::{Applicability, Help};
1489
1490        let message = msg::fmt(msg::PREFER_BARE_IDENT, &[name, expected.name()]);
1491        self.warning_with_help(
1492            line,
1493            message,
1494            Help {
1495                message: format!(
1496                    "Replace `\"{}\"` with the bare identifier `{}` — same \
1497                     resolution, one fewer layer of indirection.",
1498                    name, name
1499                ),
1500                suggestions: Vec::new(),
1501                applicability: Applicability::MachineApplicable,
1502            },
1503        );
1504    }
1505
1506    /// Search the registry for up to `limit` entity names whose edit distance
1507    /// from `name` is within `max_edits`.
1508    ///
1509    /// Optimized for large registries (100k+ entries) via:
1510    ///   1. Length pre-filter — skip candidates whose byte length differs by
1511    ///      more than `max_edits` (eliminates 90%+ without any computation).
1512    ///   2. Bounded Levenshtein — early-terminates rows whose minimum exceeds
1513    ///      the threshold.
1514    fn near_entity_names(
1515        &self,
1516        name: &str,
1517        expected: Type,
1518        max_edits: usize,
1519        limit: usize,
1520    ) -> Vec<String> {
1521        use std::collections::HashSet;
1522        let target = name.to_lowercase();
1523        let target_len = target.len();
1524        let mut seen: HashSet<String> = HashSet::new();
1525        let mut scored: Vec<(usize, String)> = Vec::new();
1526
1527        let consider =
1528            |cand: &str, scored: &mut Vec<(usize, String)>, seen: &mut HashSet<String>| {
1529                if cand.len().abs_diff(target_len) > max_edits {
1530                    return;
1531                }
1532                let key = cand.to_lowercase();
1533                if !seen.insert(key.clone()) {
1534                    return;
1535                }
1536                let d = levenshtein_bounded(&target, &key, max_edits);
1537                if d == 0 || d > max_edits {
1538                    return;
1539                }
1540                scored.push((d, cand.to_string()));
1541            };
1542
1543        for (cand, by_type) in self.registry.entity_ids_typed.iter() {
1544            if by_type.contains_key(&expected) {
1545                consider(cand, &mut scored, &mut seen);
1546            }
1547        }
1548        for cand in self.registry.entity_ids.keys() {
1549            consider(cand, &mut scored, &mut seen);
1550        }
1551
1552        scored.sort_by_key(|(d, _)| *d);
1553        scored.into_iter().take(limit).map(|(_, n)| n).collect()
1554    }
1555}
1556
1557/// Levenshtein edit distance with early termination. Returns `max + 1`
1558/// if the true distance exceeds `max`, avoiding full-matrix computation
1559/// for distant strings.
1560fn levenshtein_bounded(a: &str, b: &str, max: usize) -> usize {
1561    let a: Vec<char> = a.chars().collect();
1562    let b: Vec<char> = b.chars().collect();
1563    let (n, m) = (a.len(), b.len());
1564    if n.abs_diff(m) > max {
1565        return max + 1;
1566    }
1567    if n == 0 {
1568        return m;
1569    }
1570    if m == 0 {
1571        return n;
1572    }
1573    let mut prev: Vec<usize> = (0..=m).collect();
1574    let mut curr = vec![0usize; m + 1];
1575    for i in 1..=n {
1576        curr[0] = i;
1577        let mut row_min = curr[0];
1578        for j in 1..=m {
1579            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
1580            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
1581            row_min = row_min.min(curr[j]);
1582        }
1583        if row_min > max {
1584            return max + 1;
1585        }
1586        std::mem::swap(&mut prev, &mut curr);
1587    }
1588    prev[m]
1589}
1590
1591/// An RS2 bare identifier must start with a letter / underscore and
1592/// consist only of `[A-Za-z0-9_+]` (the `+` variant is supported via the
1593/// parser's `cheese+tom_batta` handling). Names with spaces or other
1594/// characters must use the quoted string form.
1595fn is_valid_bare_ident(name: &str) -> bool {
1596    let mut chars = name.chars();
1597    match chars.next() {
1598        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1599        _ => return false,
1600    }
1601    name.chars()
1602        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '+')
1603}
1604
1605#[derive(Debug, Clone, Copy, PartialEq)]
1606enum CallKind {
1607    Command,
1608    Proc,
1609    Jump,
1610}