1use crate::arguments::{command_hints, command_returns, proc_hints, stack_hints};
2use crate::clientscript::hooks;
3use crate::diagnostic_messages as msg;
4use crate::diagnostics::{DiagnosticsCollector, Phase};
5use crate::parser::*;
6use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
7use crate::types::{BaseVarType, Type};
8use std::path::{Path, PathBuf};
9use std::slice::from_ref;
10
11const TEST_COMMAND_PREFIXES: &[&str] = &[
12 "assert_",
13 "test_",
14 "setup_",
15 "mock_",
16 "verify_",
17 "wait_for_",
18];
19
20const LITERAL_TYPES: &[Type] = &[
21 Type::Int,
22 Type::Boolean,
23 Type::Coord,
24 Type::String,
25 Type::Char,
26 Type::Long,
27];
28
29fn is_literal_type(t: Type) -> bool {
30 LITERAL_TYPES.contains(&t)
31}
32
33pub struct TypeChecker<'a> {
34 stack_returns: bool,
35 pub diagnostics: DiagnosticsCollector,
36 pub registry: &'a SymbolRegistry,
37 file_path: PathBuf,
38 current_script_is_test: bool,
39 current_script_is_proc: bool,
40}
41
42impl<'a> TypeChecker<'a> {
43 pub fn new(registry: &'a SymbolRegistry) -> Self {
44 TypeChecker {
45 stack_returns: false,
46 diagnostics: DiagnosticsCollector::new(),
47 registry,
48 file_path: PathBuf::new(),
49 current_script_is_test: false,
50 current_script_is_proc: false,
51 }
52 }
53
54 pub fn check_file(&mut self, file: &ScriptFile, file_path: &Path) {
55 self.check_file_with_test_boundary(file, file_path, None);
56 }
57
58 pub fn check_file_with_test_boundary(
59 &mut self,
60 file: &ScriptFile,
61 file_path: &Path,
62 testscript_line: Option<usize>,
63 ) {
64 self.file_path = file_path.to_path_buf();
65 for script in &file.scripts {
66 self.current_script_is_test = match testscript_line {
67 Some(ts_line) => script.line >= ts_line,
68 None => false,
69 };
70 self.check_script(script);
71 }
72 }
73
74 fn is_test_command(name: &str) -> bool {
75 TEST_COMMAND_PREFIXES
76 .iter()
77 .any(|prefix| name.starts_with(prefix))
78 }
79
80 fn check_script(&mut self, script: &ScriptDeclaration) {
81 self.current_script_is_proc = script.trigger == "proc";
82 if let Some(message) =
83 self.registry
84 .visibility
85 .declaration(&self.file_path, &script.trigger, &script.name)
86 {
87 self.error(script.line, message);
88 }
89 self.stack_returns = self
90 .registry
91 .stack_scripts
92 .contains(&format!("{}:{}", script.trigger, script.name));
93 let mut locals = SymbolTable::new();
94
95 let mut seen_params = std::collections::HashSet::new();
97 for param in &script.params {
98 if !seen_params.insert(param.name.clone()) {
99 self.error(
100 script.line,
101 msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[¶m.name]),
102 );
103 }
104 if !Self::type_allows_parameter(param.param_type) {
106 self.error(
107 script.line,
108 msg::fmt(
109 msg::LOCAL_PARAMETER_INVALID_TYPE,
110 &[param.param_type.name()],
111 ),
112 );
113 }
114 locals.define_param(param.name.clone(), param.param_type);
115 }
116
117 self.check_trigger_constraints(script);
119 if !script.name.starts_with('_')
120 && let Some(ty) = self
121 .registry
122 .trigger(&script.trigger)
123 .and_then(|trigger| trigger.subject_type)
124 && let Some(message) = self.registry.visibility.reference(
125 &self.file_path,
126 &script
127 .name
128 .parse::<i32>()
129 .map(Expr::IntLiteral)
130 .unwrap_or_else(|_| Expr::Identifier(script.name.clone())),
131 Some(if script.name.contains(':') {
132 Type::Component
133 } else {
134 ty
135 }),
136 self.registry,
137 )
138 {
139 self.error(script.line, message);
140 }
141
142 for stmt in &script.body {
143 self.check_statement(stmt, &mut locals, Some(&script.return_types));
144 }
145 }
146
147 fn check_trigger_constraints(&mut self, script: &ScriptDeclaration) {
152 let trigger = script.trigger.as_str();
153
154 match trigger {
158 "walktrigger" | "login" | "logout" if !script.params.is_empty() => {
159 self.error(
160 script.line,
161 msg::fmt(msg::SCRIPT_TRIGGER_NO_PARAMETERS, &[trigger]),
162 );
163 }
164 _ => {}
165 }
166
167 if let Some(expected_params) = self.trigger_expected_params(trigger) {
169 let actual: Vec<&str> = script.params.iter().map(|p| p.param_type.name()).collect();
170 let expected: Vec<&str> = expected_params.iter().map(|t| t.name()).collect();
171 if actual != expected && !expected.is_empty() {
172 self.error(
173 script.line,
174 msg::fmt(
175 msg::SCRIPT_TRIGGER_EXPECTED_PARAMETERS,
176 &[trigger, &expected.join(", ")],
177 ),
178 );
179 }
180 }
181
182 match trigger {
185 "debugproc" | "label" | "queue" | "softtimer" | "timer" | "walktrigger" | "login"
186 if !script.return_types.is_empty() =>
187 {
188 self.error(
189 script.line,
190 msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[trigger]),
191 );
192 }
193 _ => {}
194 }
195
196 if let Some(expected_returns) = self.trigger_expected_returns(trigger)
198 && script.return_types != expected_returns
199 && !expected_returns.is_empty()
200 {
201 let expected: Vec<&str> = expected_returns.iter().map(|t| t.name()).collect();
202 self.error(
203 script.line,
204 msg::fmt(
205 msg::SCRIPT_TRIGGER_EXPECTED_RETURNS,
206 &[trigger, &expected.join(", ")],
207 ),
208 );
209 }
210
211 let subject = &script.name;
213 match trigger {
214 "debugproc" | "command" => {}
216
217 "opnpc1" | "opnpc2" | "opnpc3" | "opnpc4" | "opnpc5" | "opobj1" | "opobj2"
219 | "opobj3" | "opobj4" | "opobj5" | "oploc1" | "oploc2" | "oploc3" | "oploc4"
220 | "oploc5" | "opplayer1" | "opplayer2" | "opplayer3" | "opplayer4" | "opplayer5"
221 | "opnpct" | "opobjt" | "oploct" | "opplayert" | "opnpcu" | "opobju" | "oplocu"
222 | "opplayeru" | "ai_opnpc1" | "ai_opnpc2" | "ai_opnpc3" | "ai_opnpc4" | "ai_opnpc5"
223 | "ai_oploc1" | "ai_oploc2" | "ai_oploc3" | "ai_oploc4" | "ai_oploc5" | "ai_opobj1"
224 | "ai_opobj2" | "ai_opobj3" | "ai_opobj4" | "ai_opobj5" | "ai_opplayer1"
225 | "ai_opplayer2" | "ai_opplayer3" | "ai_opplayer4" | "ai_opplayer5" => {
226 if subject == "_" {
227 } else if subject.starts_with('_') {
229 } else if subject.contains(' ') {
231 self.error(
232 script.line,
233 msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
234 );
235 }
236 }
237
238 "login" | "logout" | "mapenter" | "mapleave" | "map_enter" | "worldinit"
240 | "worldshutdown"
241 if subject != "_" && !subject.is_empty() =>
242 {
243 self.error(
244 script.line,
245 msg::fmt(msg::SCRIPT_SUBJECT_ONLY_GLOBAL, &[trigger]),
246 );
247 }
248
249 "proc" | "label" | "queue" | "softtimer" | "timer" => {
251 if subject.contains(' ') {
252 self.error(
253 script.line,
254 msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
255 );
256 }
257 if subject == "_" {
258 self.error(
259 script.line,
260 msg::fmt(msg::SCRIPT_SUBJECT_NO_GLOBAL, &[trigger]),
261 );
262 }
263 if subject.starts_with('_') && subject.len() > 1 {
264 self.error(
265 script.line,
266 msg::fmt(msg::SCRIPT_SUBJECT_NO_CATEGORY, &[trigger]),
267 );
268 }
269 }
270
271 _ => {}
272 }
273
274 if script.name.ends_with('*') && trigger != "command" {
276 self.error(script.line, msg::SCRIPT_COMMAND_ONLY.to_string());
277 }
278 }
279
280 fn trigger_expected_params(&self, _trigger: &str) -> Option<Vec<Type>> {
281 None
282 }
283
284 fn trigger_expected_returns(&self, _trigger: &str) -> Option<Vec<Type>> {
285 None
286 }
287
288 fn type_allows_declaration(t: Type) -> bool {
289 !matches!(t, Type::Void | Type::Error | Type::Any)
290 }
291
292 fn type_allows_array(t: Type) -> bool {
293 !matches!(t, Type::Void | Type::Error | Type::Any | Type::Long)
294 }
295
296 fn type_allows_parameter(t: Type) -> bool {
297 !matches!(t, Type::Void | Type::Error)
298 }
299
300 fn check_block(
301 &mut self,
302 stmts: &[Statement],
303 parent: &SymbolTable,
304 return_types: Option<&[Type]>,
305 ) {
306 let mut child = parent.new_child();
307 for s in stmts {
308 self.check_statement(s, &mut child, return_types);
309 }
310 }
311
312 fn check_statement(
313 &mut self,
314 stmt: &Statement,
315 locals: &mut SymbolTable,
316 return_types: Option<&[Type]>,
317 ) {
318 match stmt {
319 Statement::VarDeclaration {
320 var_type,
321 name,
322 value,
323 line,
324 } => {
325 if locals.lookup(name).is_some() {
327 self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
328 }
329 if !Self::type_allows_declaration(*var_type) {
331 self.error(
332 *line,
333 msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[var_type.name()]),
334 );
335 }
336
337 if self.stack_returns {
339 locals.define_local(name.clone(), *var_type, false);
340 }
341 if let Some(init_expr) = value {
342 self.warn_if_bare_command_value(init_expr, *line);
343 let expr_type = self.infer_expr_type(init_expr, locals, *line, Some(*var_type));
344 if let Some(et) = expr_type
345 && !self.types_compatible(et, *var_type)
346 {
347 self.emit_type_mismatch(*line, et, *var_type);
348 }
349 }
350 locals.define_local(name.clone(), *var_type, false);
351 }
352
353 Statement::ArrayDeclaration {
354 element_type,
355 name,
356 size,
357 line,
358 } => {
359 if locals.lookup(name).is_some_and(|symbol| {
361 !matches!(symbol.kind, SymbolKind::LocalVar { is_array: true, .. })
362 }) {
363 self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
364 }
365 if !Self::type_allows_declaration(*element_type) {
367 self.error(
368 *line,
369 msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[element_type.name()]),
370 );
371 }
372 if !Self::type_allows_array(*element_type) {
373 self.error(
374 *line,
375 msg::fmt(msg::LOCAL_ARRAY_INVALID_TYPE, &[element_type.name()]),
376 );
377 }
378
379 let size_type = self.infer_expr_type(size, locals, *line, Some(Type::Int));
380 if let Some(st) = size_type
381 && !self.types_compatible(st, Type::Int)
382 {
383 self.emit_type_mismatch(*line, st, Type::Int);
384 }
385 locals.define_local(name.clone(), *element_type, true);
386 }
387
388 Statement::Assignment {
389 target,
390 value,
391 line,
392 } => {
393 self.warn_if_bare_command_value(value, *line);
394 if matches!(target, Expr::MultiAssign(..)) || matches!(value, Expr::Tuple(_)) {
395 let targets = match target {
396 Expr::MultiAssign(targets, _) => targets.as_slice(),
397 _ => from_ref(target),
398 };
399 let values = match value {
400 Expr::Tuple(values) => values.as_slice(),
401 _ => from_ref(value),
402 };
403 let expected: Vec<_> = targets
404 .iter()
405 .filter_map(|target| self.infer_expr_type(target, locals, *line, None))
406 .collect();
407 let hints = stack_hints(self.registry, &expected, values, locals);
408 let actual: Vec<_> = values
409 .iter()
410 .zip(hints)
411 .map(|(value, hint)| self.infer_expr_type(value, locals, *line, hint))
412 .collect();
413 let actual = self.expand_call_types(values, &actual);
414 if actual
415 .iter()
416 .any(|ty| ty.is_none() || *ty == Some(Type::Any))
417 {
418 return;
419 }
420 for base in [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long] {
421 let expected: Vec<_> = expected
422 .iter()
423 .copied()
424 .filter(|ty| ty.base_type() == base)
425 .collect();
426 let actual: Vec<_> = actual
427 .iter()
428 .filter_map(|ty| *ty)
429 .filter(|ty| ty.base_type() == base)
430 .collect();
431 if expected.len() != actual.len() {
432 self.error(
433 *line,
434 "Assignment value count does not match its targets".into(),
435 );
436 }
437 for (actual, expected) in actual.into_iter().zip(expected) {
438 if !self.types_compatible(actual, expected) {
439 self.emit_type_mismatch(*line, actual, expected);
440 }
441 }
442 }
443 return;
444 }
445 let target_type = self.infer_expr_type(target, locals, *line, None);
446 let value_type = self.infer_expr_type(value, locals, *line, target_type);
447 if let (Some(tt), Some(vt)) = (target_type, value_type)
448 && !self.types_compatible(vt, tt)
449 {
450 self.emit_type_mismatch(*line, vt, tt);
451 }
452 }
453
454 Statement::If {
455 condition,
456 body,
457 else_if,
458 else_body,
459 line,
460 ..
461 } => {
462 self.check_condition(condition, locals, *line);
463 self.check_block(body, locals, return_types);
464 for (cond, stmts, ei_line) in else_if {
465 self.check_condition(cond, locals, *ei_line);
466 self.check_block(stmts, locals, return_types);
467 }
468 if let Some(else_stmts) = else_body {
469 self.check_block(else_stmts, locals, return_types);
470 }
471 }
472
473 Statement::While {
474 condition,
475 body,
476 line,
477 } => {
478 self.check_condition(condition, locals, *line);
479 self.check_block(body, locals, return_types);
480 }
481
482 Statement::Switch {
483 switch_type,
484 expr,
485 cases,
486 default,
487 line,
488 ..
489 } => {
490 let type_name = switch_type.strip_prefix("switch_").unwrap_or(switch_type);
491 let resolved_type = Type::from_name(type_name);
492 if resolved_type.is_none() {
493 self.error(*line, msg::fmt(msg::GENERIC_INVALID_TYPE, &[type_name]));
494 }
495 let switch_ty = resolved_type.unwrap_or(Type::Error);
496
497 if switch_ty != Type::Error && !switch_ty.allow_switch() {
499 self.error(
500 *line,
501 msg::fmt(msg::SWITCH_INVALID_TYPE, &[switch_ty.name()]),
502 );
503 }
504
505 let expr_type = self.infer_expr_type(expr, locals, *line, Some(switch_ty));
506 if let Some(et) = expr_type
507 && switch_ty != Type::Error
508 && !self.types_compatible(et, switch_ty)
509 {
510 self.emit_type_mismatch(*line, et, switch_ty);
511 }
512
513 for case in cases {
517 self.check_switch_case(case, Some(switch_ty), locals, return_types, *line);
518 }
519 if let Some(default_stmts) = default {
520 self.check_block(default_stmts, locals, return_types);
521 }
522 }
523
524 Statement::Return { values, line } => {
525 let script_returns = match return_types {
526 Some(rt) => rt,
527 None => {
528 self.error(*line, msg::RETURN_ORPHAN.to_string());
529 return;
530 }
531 };
532 if self.stack_returns {
533 let hints = stack_hints(self.registry, script_returns, values, locals);
534 let actual: Vec<_> = values
535 .iter()
536 .zip(hints)
537 .map(|(value, hint)| self.infer_expr_type(value, locals, *line, hint))
538 .collect();
539 self.check_call_arguments(
540 "return",
541 script_returns,
542 &actual,
543 values,
544 *line,
545 CallKind::Proc,
546 );
547 return;
548 }
549 let is_single_proc_call = values.len() == 1
550 && matches!(&values[0], Expr::ProcCall { .. } | Expr::CommandCall { .. });
551 if values.len() != script_returns.len() && !is_single_proc_call {
552 self.error(
553 *line,
554 msg::fmt(
555 msg::GENERIC_TYPE_MISMATCH,
556 &[
557 &format!("{} value(s)", values.len()),
558 &format!("{} value(s)", script_returns.len()),
559 ],
560 ),
561 );
562 }
563 for (i, val) in values.iter().enumerate() {
564 let hint = script_returns.get(i).copied();
565 let val_type = self.infer_expr_type(val, locals, *line, hint);
566 if let Some(vt) = val_type
567 && let Some(expected) = hint
568 && !self.types_compatible(vt, expected)
569 {
570 self.emit_type_mismatch(*line, vt, expected);
571 }
572 }
573 }
574
575 Statement::Expression { expr, line } => {
576 let bare_cmd = self.warn_if_bare_command_value(expr, *line);
579 let expr_type = self.infer_expr_type(expr, locals, *line, None);
580 if !bare_cmd
581 && let Some(et) = expr_type
582 && et != Type::Error
583 && !self.expression_has_side_effects(expr)
584 {
585 self.warning(*line, msg::EXPRESSION_STATEMENT_NO_SIDE_EFFECT.to_string());
586 }
587 }
588 Statement::OrphanCase { case, line } => {
589 self.check_switch_case(case, None, locals, return_types, *line);
590 }
591 Statement::Empty => {}
592 }
593 }
594
595 fn check_condition(&mut self, expr: &Expr, locals: &SymbolTable, line: usize) {
596 match expr {
597 Expr::BinaryOp { op, lhs, rhs } => {
598 match op {
601 BinOp::Eq
602 | BinOp::NotEq
603 | BinOp::Lt
604 | BinOp::Gt
605 | BinOp::LtEq
606 | BinOp::GtEq
607 if (self.is_condition_expr(lhs) || self.is_condition_expr(rhs)) =>
608 {
609 self.error(line, msg::CONDITION_NOT_VALID.to_string());
610 return;
611 }
612 _ => {}
613 }
614
615 let lt = self.infer_expr_type(lhs, locals, line, None);
616 let rhs_hint = lt;
617 let rt = self.infer_expr_type(rhs, locals, line, rhs_hint);
618
619 match op {
620 BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
621 if let Some(ref lt) = lt
622 && lt.base_type() == BaseVarType::String
623 && *lt != Type::Error
624 && *lt != Type::Any
625 {
626 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
627 }
628 if let Some(ref rt) = rt
629 && rt.base_type() == BaseVarType::String
630 && *rt != Type::Error
631 && *rt != Type::Any
632 {
633 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
634 }
635 }
636 BinOp::Eq | BinOp::NotEq => {
637 if let (Some(lt), Some(rt)) = (<, &rt)
638 && *lt == Type::String
639 && *rt == Type::String
640 {
641 let op_str = if *op == BinOp::Eq { "=" } else { "!" };
642 self.error(
643 line,
644 msg::fmt(msg::BINOP_INVALID_TYPES, &[op_str, lt.name(), rt.name()]),
645 );
646 }
647 }
648 _ => {}
649 }
650 }
651 Expr::LogicalOp { lhs, rhs, .. } => {
652 self.check_condition(lhs, locals, line);
653 self.check_condition(rhs, locals, line);
654 }
655 _ => {
656 if let Some(ty) = self.infer_expr_type(expr, locals, line, None)
657 && ty.base_type() != BaseVarType::Integer
658 {
659 self.error(
660 line,
661 format!("Condition requires a boolean or integer, got {}", ty.name()),
662 );
663 }
664 }
665 }
666 }
667
668 fn is_condition_expr(&self, expr: &Expr) -> bool {
669 match expr {
670 Expr::BinaryOp { op, .. } => matches!(
671 op,
672 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq
673 ),
674 Expr::LogicalOp { .. } => true,
675 _ => false,
676 }
677 }
678
679 fn check_switch_case(
683 &mut self,
684 case: &SwitchCase,
685 parent_switch_type: Option<Type>,
686 locals: &SymbolTable,
687 return_types: Option<&[Type]>,
688 line: usize,
689 ) {
690 let switch_ty = match parent_switch_type {
691 Some(t) => t,
692 None => {
693 self.error(line, msg::CASE_WITHOUT_SWITCH.to_string());
694 return;
695 }
696 };
697
698 for val in &case.values {
699 if !self.is_constant_expression(val) {
700 self.warning(line, msg::SWITCH_CASE_NOT_CONSTANT.to_string());
701 }
702 let val_type = self.infer_expr_type(val, locals, line, Some(switch_ty));
703 if let Some(vt) = val_type
704 && switch_ty != Type::Error
705 && !self.types_compatible(vt, switch_ty)
706 {
707 self.emit_type_mismatch(line, vt, switch_ty);
708 }
709 }
710 self.check_block(&case.body, locals, return_types);
711 }
712
713 fn infer_expr_type(
718 &mut self,
719 expr: &Expr,
720 locals: &SymbolTable,
721 line: usize,
722 hint: Option<Type>,
723 ) -> Option<Type> {
724 if let Some(message) =
725 self.registry
726 .visibility
727 .reference(&self.file_path, expr, hint, self.registry)
728 {
729 self.error(line, message);
730 return Some(Type::Error);
731 }
732 match expr {
733 Expr::IntLiteral(_) => {
734 if let Some(h) = hint {
737 if !is_literal_type(h) && h != Type::Error && h != Type::Any {
738 return Some(h);
739 }
740 if h == Type::Boolean {
741 return Some(Type::Boolean);
742 }
743 }
744 Some(Type::Int)
745 }
746 Expr::LongLiteral(_) => Some(Type::Long),
747 Expr::StringLiteral(s) => {
748 if let Some(h) = hint
752 && !is_literal_type(h)
753 && h != Type::Error
754 && h != Type::Any
755 {
756 let typed_ok = self.registry.lookup_reference(s, h).is_some();
768 let untyped_ok = self.registry.lookup_entity_id(s).is_some();
769 let script_ok = self.registry.proc_script_id(s).is_some()
770 || self.registry.script_id(s).is_some();
771 if !typed_ok && !untyped_ok && !script_ok {
772 self.emit_unresolved_entity_warning(line, s, h);
773 } else if is_valid_bare_ident(s) {
774 self.emit_prefer_bare_ident_warning(line, s, h);
778 }
779 return Some(h);
780 }
781 Some(Type::String)
782 }
783 Expr::BoolLiteral(_) => Some(Type::Boolean),
784 Expr::NullLiteral => {
785 if let Some(h) = hint
787 && h != Type::Error
788 {
789 return Some(h);
790 }
791 Some(Type::Int)
792 }
793 Expr::CharLiteral(_) => Some(Type::Char),
794 Expr::CoordLiteral(_) => Some(Type::Coord),
795
796 Expr::LocalVar(name, src_line) => {
797 if let Some(sym) = locals.lookup(name) {
798 match &sym.kind {
799 SymbolKind::LocalVar {
800 var_type, is_array, ..
801 } => {
802 if *is_array {
804 self.error(
805 *src_line,
806 msg::fmt(msg::LOCAL_ARRAY_REFERENCE_NOINDEX, &[name]),
807 );
808 return Some(Type::Error);
809 }
810 Some(*var_type)
811 }
812 SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
813 _ => None,
814 }
815 } else {
816 self.error(
817 *src_line,
818 msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]),
819 );
820 Some(Type::Error)
821 }
822 }
823
824 Expr::ArrayAccess { name, index } => {
825 if let Some(sym) = locals.lookup(name) {
826 match &sym.kind {
827 SymbolKind::LocalVar {
828 var_type, is_array, ..
829 } => {
830 if !is_array {
831 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
833 }
834 let idx_type =
835 self.infer_expr_type(index, locals, line, Some(Type::Int));
836 if let Some(it) = idx_type
837 && !self.types_compatible(it, Type::Int)
838 {
839 self.emit_type_mismatch(line, it, Type::Int);
840 }
841 Some(*var_type)
842 }
843 SymbolKind::ScriptParam { param_type, .. } => {
844 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
845 Some(*param_type)
846 }
847 _ => None,
848 }
849 } else {
850 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]));
851 Some(Type::Error)
852 }
853 }
854
855 Expr::GameVar(name, src_line) => {
856 if let Some(sym) = self.registry.lookup_game_var(name) {
857 match &sym.kind {
858 SymbolKind::GameVar { var_type, .. } => Some(*var_type),
859 _ => None,
860 }
861 } else {
862 self.error(*src_line, msg::fmt(msg::GAME_REFERENCE_UNRESOLVED, &[name]));
863 Some(Type::Error)
864 }
865 }
866
867 Expr::ConstantVar(name, src_line) => {
868 if let Some(sym) = self.registry.lookup_constant(name) {
869 match &sym.kind {
870 SymbolKind::Constant { const_type, .. } => Some(*const_type),
871 _ => None,
872 }
873 } else {
874 self.error(
875 *src_line,
876 msg::fmt(msg::CONSTANT_REFERENCE_UNRESOLVED, &[name]),
877 );
878 Some(Type::Error)
879 }
880 }
881
882 Expr::Identifier(name) => {
883 if let Some(h) = hint
886 && h != Type::Error
887 && h != Type::Any
888 && self.registry.lookup_reference(name, h).is_some()
889 {
890 return Some(h);
891 }
892
893 if hint == Some(Type::Int) && self.registry.type_chars.contains_key(name) {
898 return Some(Type::Int);
899 }
900
901 if let Some(sym) = self.registry.lookup_constant(name) {
903 match &sym.kind {
904 SymbolKind::Constant { const_type, .. } => Some(*const_type),
905 other => {
906 let kind_name = other.kind_name();
907 self.error(
908 line,
909 msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[kind_name]),
910 );
911 Some(Type::Error)
912 }
913 }
914 } else if let Some(e) = self.registry.lookup_entity_id(name) {
915 Some(e.const_type)
916 } else if let Some(sym) = self.registry.lookup_command(name).cloned() {
917 if let SymbolKind::Command { return_types, .. } = &sym.kind {
918 return return_types.first().copied();
919 }
920 self.error(
921 line,
922 msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[sym.kind.kind_name()]),
923 );
924 Some(Type::Error)
925 } else if self.registry.type_chars.contains_key(name) {
926 Some(Type::Int)
927 } else if name.contains(':') {
928 let parts: Vec<&str> = name.splitn(2, ':').collect();
930 if parts.len() == 2
931 && self.registry.lookup_component(parts[0], parts[1]).is_some()
932 {
933 Some(hint.unwrap_or(Type::Component))
934 } else if let Some(h) = hint {
935 if h != Type::Error {
936 Some(h)
937 } else {
938 Some(Type::Error)
939 }
940 } else {
941 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
942 Some(Type::Error)
943 }
944 } else {
945 if let Some(h) = hint {
950 if h == Type::String {
951 return Some(Type::String);
952 }
953 if h != Type::Error {
954 let resolved = self.registry.lookup_entity_id_typed(name, h).is_some()
972 || self.registry.lookup_entity_id(name).is_some()
973 || self
974 .registry
975 .trigger(name)
976 .is_some_and(|trigger| trigger.byte.is_some())
977 || (h == Type::Int && self.registry.command_opcode(name).is_some())
978 || self.registry.proc_script_id(name).is_some()
979 || self.registry.script_id(name).is_some();
980 if !resolved {
981 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
982 return Some(Type::Error);
983 }
984 return Some(h);
985 }
986 }
987 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
988 Some(Type::Error)
989 }
990 }
991
992 Expr::BinaryOp { op, lhs, rhs } => match op {
993 BinOp::Add
994 | BinOp::Sub
995 | BinOp::Mul
996 | BinOp::Div
997 | BinOp::Mod
998 | BinOp::BitAnd
999 | BinOp::BitOr => {
1000 if matches!(op, BinOp::Add)
1007 && let (Expr::Identifier(lname), Expr::Identifier(rname)) =
1008 (lhs.as_ref(), rhs.as_ref())
1009 {
1010 let combined = format!("{}+{}", lname, rname);
1011 if let Some(h) = hint {
1012 if self.registry.lookup_entity_id_typed(&combined, h).is_some()
1013 || self.registry.lookup_entity_id(&combined).is_some()
1014 {
1015 return Some(h);
1016 }
1017 } else if let Some(e) = self.registry.lookup_entity_id(&combined) {
1018 return Some(e.const_type);
1019 }
1020 }
1021
1022 let expected = hint.unwrap_or(Type::Int);
1023 let lt = self.infer_expr_type(lhs, locals, line, Some(expected));
1024 let rt = self.infer_expr_type(rhs, locals, line, Some(expected));
1025 if let Some(ref lt) = lt
1026 && lt.base_type() == BaseVarType::String
1027 && *lt != Type::Error
1028 && *lt != Type::Any
1029 {
1030 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
1031 }
1032 if let Some(ref rt) = rt
1033 && rt.base_type() == BaseVarType::String
1034 && *rt != Type::Error
1035 && *rt != Type::Any
1036 {
1037 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
1038 }
1039 if matches!(lt, Some(Type::Long)) || matches!(rt, Some(Type::Long)) {
1040 Some(Type::Long)
1041 } else {
1042 Some(hint.unwrap_or(Type::Int))
1043 }
1044 }
1045 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
1046 let lt = self.infer_expr_type(lhs, locals, line, None);
1047 let _ = self.infer_expr_type(rhs, locals, line, lt);
1048 Some(Type::Boolean)
1049 }
1050 },
1051
1052 Expr::LogicalOp { lhs, rhs, .. } => {
1053 let _ = self.infer_expr_type(lhs, locals, line, None);
1054 let _ = self.infer_expr_type(rhs, locals, line, None);
1055 Some(Type::Boolean)
1056 }
1057
1058 Expr::Calc(inner) => {
1059 let expected = hint.unwrap_or(Type::Int);
1060 let inner_type = self.infer_expr_type(inner, locals, line, Some(expected));
1061 if let Some(ref it) = inner_type
1062 && it.base_type() == BaseVarType::String
1063 && *it != Type::Error
1064 && *it != Type::Any
1065 {
1066 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[it.name()]));
1067 }
1068 inner_type
1069 }
1070
1071 Expr::CommandCall {
1072 name,
1073 args,
1074 call_line,
1075 ..
1076 } => {
1077 let call = match hooks::server_call(self.registry, name, args, locals, *call_line) {
1078 Ok(call) => call,
1079 Err(error) => {
1080 self.error(*call_line, error);
1081 return Some(Type::Error);
1082 }
1083 };
1084 let (name, args, call_line) = match &call {
1085 Some(Expr::CommandCall {
1086 name,
1087 args,
1088 call_line,
1089 ..
1090 }) => (name, args, call_line),
1091 _ => (name, args, call_line),
1092 };
1093 let lookup_name = name.strip_prefix('.').unwrap_or(name);
1094 if lookup_name.starts_with("__") {
1095 let (values, result): (Vec<&Expr>, Option<Type>) = match lookup_name {
1096 "__label" | "__jump" | "__opcode" => (vec![], None),
1097 "__branch" => (args.iter().skip(2).collect(), None),
1098 "__switch" => (args.first().into_iter().collect(), None),
1099 "__push" => (args.iter().collect(), None),
1100 "__pop_int" => (vec![], Some(Type::Int)),
1101 "__pop_string" => (vec![], Some(Type::String)),
1102 "__pop_long" => (vec![], Some(Type::Long)),
1103 "__join" => (args.iter().collect(), Some(Type::String)),
1104 "__get_array" => (args.iter().collect(), Some(Type::Int)),
1105 "__set_array" | "__define_array" => (args.iter().collect(), None),
1106 _ => {
1107 self.error(*call_line, format!("Unknown intrinsic {name}"));
1108 (vec![], None)
1109 }
1110 };
1111 for value in values {
1112 self.infer_expr_type(value, locals, *call_line, None);
1113 }
1114 return result;
1115 }
1116
1117 if !self.current_script_is_test
1118 && Self::is_test_command(lookup_name)
1119 && !self.registry.stack_commands.contains(lookup_name)
1120 {
1121 self.error(
1122 *call_line,
1123 msg::fmt(msg::TEST_COMMAND_FROM_PRODUCTION, &[lookup_name]),
1124 );
1125 }
1126
1127 let lowered =
1128 match hooks::lower(self.registry, lookup_name, args, locals, *call_line) {
1129 Ok(args) => args,
1130 Err(error) => {
1131 self.error(*call_line, error);
1132 return Some(Type::Error);
1133 }
1134 };
1135 let args = lowered.as_deref().unwrap_or(args);
1136 let hints = command_hints(self.registry, lookup_name, args, locals);
1137
1138 let arg_types: Vec<Option<Type>> = args
1139 .iter()
1140 .enumerate()
1141 .map(|(i, a)| {
1142 let arg_hint = hints.get(i).copied().flatten();
1143 self.infer_expr_type(a, locals, *call_line, arg_hint)
1144 })
1145 .collect();
1146
1147 let is_variadic = lookup_name.ends_with('*');
1148 let cmd_sym = self
1149 .registry
1150 .lookup_command(lookup_name)
1151 .cloned()
1152 .or_else(|| {
1153 lookup_name.strip_suffix('*').and_then(|base| {
1154 let vararg_name = format!("{}vararg", base);
1155 self.registry.lookup_command(&vararg_name).cloned()
1156 })
1157 });
1158 if let Some(sym) = cmd_sym {
1159 if let SymbolKind::Command {
1160 param_types: cmd_params,
1161 ..
1162 } = &sym.kind
1163 {
1164 if self.registry.stack_commands.contains(lookup_name) {
1165 let counts = |types: &[Type]| {
1166 let mut counts = [0usize; 3];
1167 for ty in types {
1168 counts[match ty.base_type() {
1169 BaseVarType::Integer => 0,
1170 BaseVarType::String => 1,
1171 BaseVarType::Long => 2,
1172 }] += 1;
1173 }
1174 counts
1175 };
1176 let expanded = self.expand_call_types(args, &arg_types);
1177 let actual =
1178 counts(&expanded.iter().filter_map(|t| *t).collect::<Vec<_>>());
1179 let mut expected = counts(cmd_params);
1180 if let Some(&explicit) = self.registry.hook_commands.get(lookup_name) {
1181 if let Some(Expr::StringLiteral(signature)) = args
1182 .iter()
1183 .rev()
1184 .find(|arg| matches!(arg, Expr::StringLiteral(_)))
1185 {
1186 expected = [1 + usize::from(explicit), 1, 0];
1187 for ch in signature.trim_end_matches('Y').chars() {
1188 expected[match ch {
1189 's' => 1,
1190 '§' => 2,
1191 _ => 0,
1192 }] += 1;
1193 }
1194 if signature.ends_with('Y') {
1195 let ints: Vec<_> = args
1196 .iter()
1197 .zip(&arg_types)
1198 .filter_map(|(arg, ty)| {
1199 ty.is_some_and(|ty| {
1200 ty.base_type() == BaseVarType::Integer
1201 })
1202 .then_some(arg)
1203 })
1204 .collect();
1205 let index =
1206 ints.len().checked_sub(1 + usize::from(explicit));
1207 if let Some(Expr::IntLiteral(n)) =
1208 index.and_then(|index| ints.get(index).copied())
1209 && *n >= 0
1210 {
1211 expected[0] += *n as usize + 1;
1212 }
1213 }
1214 } else {
1215 self.error(
1216 *call_line,
1217 "Client hook needs a constant signature".into(),
1218 );
1219 }
1220 }
1221 if actual != expected {
1222 self.error(*call_line, format!("{name} expects {expected:?} int/string/long arguments, got {actual:?}"));
1223 }
1224 } else if !is_variadic {
1225 self.check_call_arguments(
1226 name,
1227 cmd_params,
1228 &arg_types,
1229 args,
1230 *call_line,
1231 CallKind::Command,
1232 );
1233 }
1234 return command_returns(self.registry, lookup_name, args)
1235 .first()
1236 .copied();
1237 }
1238 } else {
1239 self.error(
1240 *call_line,
1241 msg::fmt(msg::COMMAND_REFERENCE_UNRESOLVED, &[name]),
1242 );
1243 return Some(Type::Error);
1244 }
1245 None
1246 }
1247
1248 Expr::ProcCall {
1249 name,
1250 args,
1251 call_line,
1252 ..
1253 } => {
1254 let script_sym = self
1256 .registry
1257 .lookup_script_by_trigger("proc", name)
1258 .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name))
1259 .cloned();
1260
1261 if self.registry.proc_script_id(name).is_none() && script_sym.is_none() {
1262 self.error(
1263 *call_line,
1264 msg::fmt(msg::PROC_REFERENCE_UNRESOLVED, &[name]),
1265 );
1266 for arg in args {
1268 let _ = self.infer_expr_type(arg, locals, *call_line, None);
1269 }
1270 return Some(Type::Error);
1271 }
1272
1273 if !self.current_script_is_test && self.registry.is_test_script("proc", name) {
1274 self.error(
1275 *call_line,
1276 msg::fmt(msg::TEST_PROC_FROM_PRODUCTION, &[name]),
1277 );
1278 }
1279
1280 let (p_types, r_types) = if let Some(ref sym) = script_sym {
1281 if let SymbolKind::Script {
1282 param_types,
1283 return_types,
1284 ..
1285 } = &sym.kind
1286 {
1287 (param_types.clone(), return_types.clone())
1288 } else {
1289 (vec![], vec![])
1290 }
1291 } else {
1292 (vec![], vec![])
1293 };
1294
1295 let hints = proc_hints(self.registry, name, args, locals);
1296 let arg_types: Vec<Option<Type>> = args
1297 .iter()
1298 .enumerate()
1299 .map(|(i, a)| {
1300 let arg_hint = hints.get(i).copied().flatten();
1301 self.infer_expr_type(a, locals, *call_line, arg_hint)
1302 })
1303 .collect();
1304
1305 if script_sym.is_some() {
1306 self.check_call_arguments(
1307 name,
1308 &p_types,
1309 &arg_types,
1310 args,
1311 *call_line,
1312 CallKind::Proc,
1313 );
1314 }
1315 r_types.first().copied()
1316 }
1317
1318 Expr::JumpCall {
1319 name,
1320 args,
1321 call_line,
1322 ..
1323 } => {
1324 if self.current_script_is_proc {
1325 self.error(*call_line, msg::fmt(msg::JUMP_IN_PROC, &[name]));
1326 }
1327 let script_sym = self
1328 .registry
1329 .lookup_script_by_trigger("label", name)
1330 .cloned();
1331
1332 if self.registry.label_script_id(name).is_none() {
1333 self.error(
1334 *call_line,
1335 msg::fmt(msg::JUMP_REFERENCE_UNRESOLVED, &[name]),
1336 );
1337 for arg in args {
1338 let _ = self.infer_expr_type(arg, locals, *call_line, None);
1339 }
1340 return Some(Type::Error);
1341 }
1342
1343 if !self.current_script_is_test && self.registry.is_test_script("label", name) {
1344 self.error(
1345 *call_line,
1346 msg::fmt(msg::TEST_LABEL_FROM_PRODUCTION, &[name]),
1347 );
1348 }
1349
1350 let p_types = if let Some(ref sym) = script_sym {
1351 if let SymbolKind::Script { param_types, .. } = &sym.kind {
1352 param_types.clone()
1353 } else {
1354 vec![]
1355 }
1356 } else {
1357 vec![]
1358 };
1359
1360 let arg_types: Vec<Option<Type>> = args
1361 .iter()
1362 .enumerate()
1363 .map(|(i, a)| {
1364 let arg_hint = p_types.get(i).copied();
1365 self.infer_expr_type(a, locals, *call_line, arg_hint)
1366 })
1367 .collect();
1368
1369 if script_sym.is_some() {
1370 self.check_call_arguments(
1371 name,
1372 &p_types,
1373 &arg_types,
1374 args,
1375 *call_line,
1376 CallKind::Jump,
1377 );
1378 }
1379 None
1380 }
1381
1382 Expr::JoinedString { parts } => {
1383 for part in parts {
1384 if let StringPart::Expr(e) = part {
1385 let _ = self.infer_expr_type(e, locals, line, Some(Type::String));
1386 }
1387 }
1388 Some(Type::String)
1389 }
1390
1391 Expr::Tuple(values) => {
1392 for value in values {
1393 self.infer_expr_type(value, locals, line, None);
1394 }
1395 None
1396 }
1397 Expr::MultiAssign(targets, _) => {
1398 for target in targets {
1400 if let Expr::ArrayAccess { name, .. } = target {
1401 self.error(line, msg::fmt(msg::ASSIGN_MULTI_ARRAY, &[name]));
1402 }
1403 }
1404 None
1405 }
1406 }
1407 }
1408
1409 fn stack_arguments(&self, name: &str, kind: CallKind) -> bool {
1412 let trigger = match kind {
1413 CallKind::Command => {
1414 return self
1415 .registry
1416 .stack_commands
1417 .contains(name.trim_start_matches('.'));
1418 }
1419 CallKind::Proc if name == "return" => return self.stack_returns,
1420 CallKind::Proc
1421 if self
1422 .registry
1423 .lookup_script_by_trigger("proc", name)
1424 .is_some() =>
1425 {
1426 "proc"
1427 }
1428 CallKind::Proc => "clientscript",
1429 CallKind::Jump => "label",
1430 };
1431 self.registry
1432 .stack_scripts
1433 .contains(&format!("{trigger}:{name}"))
1434 }
1435
1436 fn expand_call_types(&self, args: &[Expr], types: &[Option<Type>]) -> Vec<Option<Type>> {
1437 args.iter()
1438 .zip(types)
1439 .flat_map(|(expr, ty)| {
1440 let symbol = match expr {
1441 Expr::Identifier(name) if self.registry.lookup_command(name.trim_start_matches('.')).is_some() => {
1442 let returns = command_returns(self.registry,name,&[]);
1443 return if returns.len() > 1 && returns.first() == ty.as_ref()
1444 && !ty.is_some_and(|ty| self.registry.lookup_reference(name,ty).is_some()) {
1445 returns.into_iter().map(Some).collect()
1446 } else { vec![*ty] };
1447 }
1448 Expr::ProcCall { name, .. } => self
1449 .registry
1450 .lookup_script_by_trigger("proc", name)
1451 .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name)),
1452 Expr::CommandCall { name, args, .. } => {
1453 let name = name.trim_start_matches('.');
1454 if !self.registry.stack_commands.contains(name)
1455 && matches!(self.registry.lookup_command(name).map(|symbol| &symbol.kind),
1456 Some(SymbolKind::Command { return_types, .. })
1457 if return_types.is_empty()) {
1458 return vec![None];
1459 }
1460 return command_returns(self.registry, name, args)
1461 .into_iter()
1462 .map(Some)
1463 .collect();
1464 }
1465 _ => None,
1466 };
1467 match symbol.map(|symbol| &symbol.kind) {
1468 Some(
1469 SymbolKind::Script { return_types, .. }
1470 | SymbolKind::Command { return_types, .. },
1471 ) => return_types.iter().copied().map(Some).collect(),
1472 _ => vec![*ty],
1473 }
1474 })
1475 .collect()
1476 }
1477
1478 fn check_call_arguments(
1479 &mut self,
1480 name: &str,
1481 expected_types: &[Type],
1482 actual_types: &[Option<Type>],
1483 args: &[Expr],
1484 line: usize,
1485 kind: CallKind,
1486 ) {
1487 if self.stack_arguments(name, kind) {
1488 let actual_types = self.expand_call_types(args, actual_types);
1489 for base in [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long] {
1490 let expected: Vec<_> = expected_types
1491 .iter()
1492 .filter(|ty| ty.base_type() == base)
1493 .collect();
1494 let actual: Vec<_> = actual_types
1495 .iter()
1496 .flatten()
1497 .filter(|ty| ty.base_type() == base)
1498 .collect();
1499 if expected.len() != actual.len() {
1500 self.error(
1501 line,
1502 format!(
1503 "{name} expects {} {base:?} values, got {}",
1504 expected.len(),
1505 actual.len()
1506 ),
1507 );
1508 }
1509 for (actual, expected) in actual.into_iter().zip(expected) {
1510 if !self.types_compatible(*actual, *expected) {
1511 self.emit_type_mismatch(line, *actual, *expected);
1512 }
1513 }
1514 }
1515 return;
1516 }
1517 if expected_types.is_empty() {
1519 if kind == CallKind::Command {
1520 return;
1521 }
1522 let is_single_null = args.len() == 1 && matches!(&args[0], Expr::NullLiteral);
1524 if !actual_types.is_empty() && !is_single_null {
1525 let actual_desc = actual_types
1526 .iter()
1527 .map(|t| t.map_or("unknown".to_string(), |t| t.name().to_string()))
1528 .collect::<Vec<_>>()
1529 .join(", ");
1530 let template = match kind {
1531 CallKind::Proc => msg::PROC_NOARGS_EXPECTED,
1532 CallKind::Jump => msg::JUMP_NOARGS_EXPECTED,
1533 CallKind::Command => msg::COMMAND_NOARGS_EXPECTED,
1534 };
1535 self.error(line, msg::fmt(template, &[name, &actual_desc]));
1536 }
1537 return;
1538 }
1539
1540 let has_call_arg = args
1544 .iter()
1545 .any(|a| matches!(a, Expr::ProcCall { .. } | Expr::CommandCall { .. }));
1546
1547 if expected_types.len() != actual_types.len() {
1548 if has_call_arg {
1549 return;
1550 }
1551 if kind == CallKind::Command && !self.current_script_is_test {
1558 return;
1559 }
1560 self.error(
1561 line,
1562 msg::fmt(
1563 msg::GENERIC_TYPE_MISMATCH,
1564 &[
1565 &format!("{} arg(s)", actual_types.len()),
1566 &format!("{} arg(s)", expected_types.len()),
1567 ],
1568 ),
1569 );
1570 return;
1571 }
1572
1573 for (i, (expected, actual)) in expected_types.iter().zip(actual_types.iter()).enumerate() {
1574 if let Some(actual_ty) = actual
1575 && !self.types_compatible(*actual_ty, *expected)
1576 {
1577 self.error(
1578 line,
1579 msg::fmt(
1580 msg::GENERIC_TYPE_MISMATCH,
1581 &[actual_ty.name(), expected.name()],
1582 ),
1583 );
1584 let _ = i;
1585 }
1586 }
1587 }
1588
1589 fn is_constant_expression(&self, expr: &Expr) -> bool {
1592 match expr {
1593 Expr::IntLiteral(_)
1594 | Expr::LongLiteral(_)
1595 | Expr::StringLiteral(_)
1596 | Expr::BoolLiteral(_)
1597 | Expr::NullLiteral
1598 | Expr::CharLiteral(_)
1599 | Expr::CoordLiteral(_) => true,
1600 Expr::ConstantVar(..) => true,
1601 Expr::Identifier(name) => {
1602 self.registry.lookup_constant(name).is_some()
1603 || self.registry.lookup_entity_id(name).is_some()
1604 || self.registry.type_chars.contains_key(name)
1605 || name.contains(':') && {
1607 let parts: Vec<&str> = name.splitn(2, ':').collect();
1608 parts.len() == 2
1609 && self
1610 .registry
1611 .lookup_component(parts[0], parts[1])
1612 .is_some()
1613 }
1614 }
1615 Expr::BinaryOp {
1618 op: BinOp::Add,
1619 lhs,
1620 rhs,
1621 } => {
1622 if let (Expr::Identifier(l), Expr::Identifier(r)) = (lhs.as_ref(), rhs.as_ref()) {
1623 let combined = format!("{}+{}", l, r);
1624 self.registry.lookup_entity_id(&combined).is_some()
1625 } else {
1626 false
1627 }
1628 }
1629 _ => false,
1630 }
1631 }
1632
1633 fn expression_has_side_effects(&self, expr: &Expr) -> bool {
1636 match expr {
1637 Expr::CommandCall { .. } | Expr::ProcCall { .. } | Expr::JumpCall { .. } => true,
1638 Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
1639 self.expression_has_side_effects(lhs) || self.expression_has_side_effects(rhs)
1640 }
1641 Expr::Calc(inner) => self.expression_has_side_effects(inner),
1642 Expr::JoinedString { parts } => parts.iter().any(|p| {
1643 if let StringPart::Expr(e) = p {
1644 self.expression_has_side_effects(e)
1645 } else {
1646 false
1647 }
1648 }),
1649 _ => false,
1650 }
1651 }
1652
1653 fn types_compatible(&self, actual: Type, expected: Type) -> bool {
1657 if expected == Type::Any {
1659 return true;
1660 }
1661 if expected == Type::Error || actual == Type::Error {
1663 return true;
1664 }
1665 if actual == expected {
1667 return true;
1668 }
1669 if (expected == Type::Obj && actual == Type::NamedObj)
1671 || (expected == Type::NamedObj && actual == Type::Obj)
1672 {
1673 return true;
1674 }
1675 if actual == Type::Any {
1677 return true;
1678 }
1679 if actual == Type::Int && expected.base_type() == BaseVarType::Integer {
1685 return true;
1686 }
1687 if matches!(actual, Type::Boolean | Type::Obj) && expected == Type::Int {
1691 return true;
1692 }
1693 if !self.current_script_is_test
1703 && actual.base_type() == BaseVarType::Integer
1704 && expected.base_type() == BaseVarType::Integer
1705 {
1706 return true;
1707 }
1708 false
1709 }
1710
1711 fn warn_if_bare_command_value(&mut self, expr: &Expr, line: usize) -> bool {
1719 if let Expr::Identifier(name) = expr {
1720 let requires_args = self
1721 .registry
1722 .command_param_types
1723 .get(name)
1724 .is_some_and(|p| !p.is_empty());
1725 if requires_args && self.registry.lookup_command(name).is_some() {
1728 self.warning(
1729 line,
1730 msg::fmt(msg::COMMAND_BARE_REQUIRES_ARGS, &[name, name]),
1731 );
1732 return true;
1733 }
1734 }
1735 false
1736 }
1737
1738 fn emit_type_mismatch(&mut self, line: usize, actual: Type, expected: Type) {
1741 self.error(
1742 line,
1743 msg::fmt(
1744 msg::GENERIC_TYPE_MISMATCH,
1745 &[actual.name(), expected.name()],
1746 ),
1747 );
1748 }
1749
1750 fn error(&mut self, line: usize, message: String) {
1751 self.diagnostics.error(
1752 self.file_path.clone(),
1753 line,
1754 0,
1755 message,
1756 Phase::TypeChecking,
1757 );
1758 }
1759
1760 fn warning(&mut self, line: usize, message: String) {
1761 self.diagnostics.warning(
1762 self.file_path.clone(),
1763 line,
1764 0,
1765 message,
1766 Phase::TypeChecking,
1767 );
1768 }
1769
1770 fn warning_with_help(&mut self, line: usize, message: String, help: crate::diagnostics::Help) {
1773 use crate::diagnostics::{Diagnostic, Severity};
1774 self.diagnostics.add(Diagnostic {
1775 file: self.file_path.clone(),
1776 line,
1777 column: 0,
1778 message,
1779 severity: Severity::Warning,
1780 phase: Phase::TypeChecking,
1781 help: vec![help],
1782 });
1783 }
1784
1785 fn emit_unresolved_entity_warning(&mut self, line: usize, name: &str, expected: Type) {
1788 use crate::diagnostics::{Applicability, Help};
1789
1790 let message = msg::fmt(msg::UNRESOLVED_ENTITY_REF, &[name, expected.name()]);
1791
1792 let near = self.near_entity_names(name, expected, 2, 3);
1793 let help_message = if near.is_empty() {
1794 format!(
1795 "Check the `{}` pack/registry for the canonical name, or remove \
1796 the reference if it's stale.",
1797 expected.name()
1798 )
1799 } else {
1800 let suggestions = near
1801 .iter()
1802 .map(|n| format!("`{}`", n))
1803 .collect::<Vec<_>>()
1804 .join(", ");
1805 format!("Did you mean one of: {}?", suggestions)
1806 };
1807
1808 self.warning_with_help(
1809 line,
1810 message,
1811 Help {
1812 message: help_message,
1813 suggestions: Vec::new(),
1814 applicability: Applicability::MaybeIncorrect,
1815 },
1816 );
1817 }
1818
1819 fn emit_prefer_bare_ident_warning(&mut self, line: usize, name: &str, expected: Type) {
1821 use crate::diagnostics::{Applicability, Help};
1822
1823 let message = msg::fmt(msg::PREFER_BARE_IDENT, &[name, expected.name()]);
1824 self.warning_with_help(
1825 line,
1826 message,
1827 Help {
1828 message: format!(
1829 "Replace `\"{}\"` with the bare identifier `{}` — same \
1830 resolution, one fewer layer of indirection.",
1831 name, name
1832 ),
1833 suggestions: Vec::new(),
1834 applicability: Applicability::MachineApplicable,
1835 },
1836 );
1837 }
1838
1839 fn near_entity_names(
1848 &self,
1849 name: &str,
1850 expected: Type,
1851 max_edits: usize,
1852 limit: usize,
1853 ) -> Vec<String> {
1854 use std::collections::HashSet;
1855 let target = name.to_lowercase();
1856 let target_len = target.len();
1857 let mut seen: HashSet<String> = HashSet::new();
1858 let mut scored: Vec<(usize, String)> = Vec::new();
1859
1860 let consider =
1861 |cand: &str, scored: &mut Vec<(usize, String)>, seen: &mut HashSet<String>| {
1862 if cand.len().abs_diff(target_len) > max_edits {
1863 return;
1864 }
1865 let key = cand.to_lowercase();
1866 if !seen.insert(key.clone()) {
1867 return;
1868 }
1869 let d = levenshtein_bounded(&target, &key, max_edits);
1870 if d == 0 || d > max_edits {
1871 return;
1872 }
1873 scored.push((d, cand.to_string()));
1874 };
1875
1876 for (cand, entry) in self.registry.entity_ids.iter() {
1877 if entry.variants.iter().any(|(t, _)| *t == expected) {
1878 consider(cand, &mut scored, &mut seen);
1879 }
1880 }
1881 for (cand, entry) in self.registry.entity_ids.iter() {
1882 if entry.primary.is_some() {
1883 consider(cand, &mut scored, &mut seen);
1884 }
1885 }
1886
1887 scored.sort_by_key(|(d, _)| *d);
1888 scored.into_iter().take(limit).map(|(_, n)| n).collect()
1889 }
1890}
1891
1892fn levenshtein_bounded(a: &str, b: &str, max: usize) -> usize {
1896 let a: Vec<char> = a.chars().collect();
1897 let b: Vec<char> = b.chars().collect();
1898 let (n, m) = (a.len(), b.len());
1899 if n.abs_diff(m) > max {
1900 return max + 1;
1901 }
1902 if n == 0 {
1903 return m;
1904 }
1905 if m == 0 {
1906 return n;
1907 }
1908 let mut prev: Vec<usize> = (0..=m).collect();
1909 let mut curr = vec![0usize; m + 1];
1910 for i in 1..=n {
1911 curr[0] = i;
1912 let mut row_min = curr[0];
1913 for j in 1..=m {
1914 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
1915 curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
1916 row_min = row_min.min(curr[j]);
1917 }
1918 if row_min > max {
1919 return max + 1;
1920 }
1921 std::mem::swap(&mut prev, &mut curr);
1922 }
1923 prev[m]
1924}
1925
1926fn is_valid_bare_ident(name: &str) -> bool {
1931 let mut chars = name.chars();
1932 match chars.next() {
1933 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1934 _ => return false,
1935 }
1936 name.chars()
1937 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '+')
1938}
1939
1940#[derive(Debug, Clone, Copy, PartialEq)]
1941enum CallKind {
1942 Command,
1943 Proc,
1944 Jump,
1945}