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