1use crate::arguments::{
2 command_hints, command_parameters, command_returns, positional_hints, proc_hints, stack_hints,
3};
4use crate::clientscript::{hooks, triggers};
5use crate::compiler::Compiler;
6use crate::diagnostic_messages as msg;
7use crate::diagnostics::{DiagnosticsCollector, Phase};
8use crate::parser::*;
9use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
10use crate::types::{BaseVarType, Type};
11use std::collections::HashSet;
12use std::path::{Path, PathBuf};
13use std::slice::from_ref;
14
15const TEST_COMMAND_PREFIXES: &[&str] = &[
16 "assert_",
17 "test_",
18 "setup_",
19 "mock_",
20 "verify_",
21 "wait_for_",
22];
23
24const LITERAL_TYPES: &[Type] = &[
25 Type::Int,
26 Type::Boolean,
27 Type::Coord,
28 Type::String,
29 Type::Char,
30 Type::Long,
31];
32
33fn is_literal_type(t: Type) -> bool {
34 LITERAL_TYPES.contains(&t)
35}
36
37pub struct TypeChecker<'a> {
38 stack_returns: bool,
39 pub diagnostics: DiagnosticsCollector,
40 pub registry: &'a SymbolRegistry,
41 file_path: PathBuf,
42 current_script_is_test: bool,
43 current_script_is_proc: bool,
44}
45
46impl<'a> TypeChecker<'a> {
47 pub fn new(registry: &'a SymbolRegistry) -> Self {
48 TypeChecker {
49 stack_returns: false,
50 diagnostics: DiagnosticsCollector::new(),
51 registry,
52 file_path: PathBuf::new(),
53 current_script_is_test: false,
54 current_script_is_proc: false,
55 }
56 }
57
58 pub fn check_file(&mut self, file: &ScriptFile, file_path: &Path) {
59 self.check_file_with_test_boundary(file, file_path, None);
60 }
61
62 pub fn check_file_with_test_boundary(
63 &mut self,
64 file: &ScriptFile,
65 file_path: &Path,
66 testscript_line: Option<usize>,
67 ) {
68 self.file_path = file_path.to_path_buf();
69 for script in &file.scripts {
70 self.current_script_is_test = match testscript_line {
71 Some(ts_line) => script.line >= ts_line,
72 None => false,
73 };
74 self.check_script(script);
75 }
76 }
77
78 fn is_test_command(name: &str) -> bool {
79 TEST_COMMAND_PREFIXES
80 .iter()
81 .any(|prefix| name.starts_with(prefix))
82 }
83
84 fn check_script(&mut self, script: &ScriptDeclaration) {
85 self.current_script_is_proc = script.trigger == "proc";
86 if let Some(message) =
87 self.registry
88 .visibility
89 .declaration(&self.file_path, &script.trigger, &script.name)
90 {
91 self.error(script.line, message);
92 }
93 self.stack_returns = self
94 .registry
95 .stack_scripts
96 .contains(&format!("{}:{}", script.trigger, script.name));
97 let mut locals = SymbolTable::new();
98
99 let mut seen_params = std::collections::HashSet::new();
101 for param in &script.params {
102 if !seen_params.insert(param.name.clone()) {
103 self.error(
104 script.line,
105 msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[¶m.name]),
106 );
107 }
108 if !Self::type_allows_parameter(param.param_type) {
110 self.error(
111 script.line,
112 msg::fmt(
113 msg::LOCAL_PARAMETER_INVALID_TYPE,
114 &[param.param_type.name()],
115 ),
116 );
117 }
118 locals.define_param(param.name.clone(), param.param_type);
119 }
120
121 self.check_trigger_constraints(script);
123 if !script.name.starts_with('_')
124 && let Some(ty) = self
125 .registry
126 .trigger(&script.trigger)
127 .and_then(|trigger| trigger.subject_type)
128 && let Some(message) = self.registry.visibility.reference(
129 &self.file_path,
130 &script
131 .name
132 .parse::<i32>()
133 .map(Expr::IntLiteral)
134 .unwrap_or_else(|_| Expr::Identifier(script.name.clone())),
135 Some(if script.name.contains(':') {
136 Type::Component
137 } else {
138 ty
139 }),
140 self.registry,
141 )
142 {
143 self.error(script.line, message);
144 }
145
146 for stmt in &script.body {
147 self.check_statement(stmt, &mut locals, Some(&script.return_types));
148 }
149 }
150
151 fn check_trigger_constraints(&mut self, script: &ScriptDeclaration) {
156 let trigger = script.trigger.as_str();
157
158 if self.stack_returns
159 && let Some(info) = triggers::lookup(trigger)
160 {
161 if info.params.is_some() && !script.return_types.is_empty() {
162 self.error(
163 script.line,
164 msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[trigger]),
165 );
166 }
167 if let Some((subject, ty)) = info.subject(&script.name) {
168 if self.registry.lookup_reference(subject, ty).is_none() {
169 self.error(
170 script.line,
171 format!("Unknown {} trigger subject '{subject}'", ty.name()),
172 );
173 } else if let Some(message) = self.registry.visibility.reference(
174 &self.file_path,
175 &Expr::Identifier(subject.to_owned()),
176 Some(ty),
177 self.registry,
178 ) {
179 self.error(script.line, message);
180 }
181 }
182 }
183
184 match trigger {
188 "walktrigger" | "login" | "logout" if !script.params.is_empty() => {
189 self.error(
190 script.line,
191 msg::fmt(msg::SCRIPT_TRIGGER_NO_PARAMETERS, &[trigger]),
192 );
193 }
194 _ => {}
195 }
196
197 if let Some(expected_params) = self.trigger_expected_params(trigger) {
199 let actual: Vec<&str> = script.params.iter().map(|p| p.param_type.name()).collect();
200 let expected: Vec<&str> = expected_params.iter().map(|t| t.name()).collect();
201 if actual != expected {
202 self.error(
203 script.line,
204 msg::fmt(
205 msg::SCRIPT_TRIGGER_EXPECTED_PARAMETERS,
206 &[trigger, &expected.join(", ")],
207 ),
208 );
209 }
210 }
211
212 match trigger {
215 "debugproc" | "label" | "queue" | "softtimer" | "timer" | "walktrigger" | "login"
216 | "controller_queue" | "npc_queue"
217 if !script.return_types.is_empty() =>
218 {
219 self.error(
220 script.line,
221 msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[trigger]),
222 );
223 }
224 _ => {}
225 }
226
227 if let Some(expected_returns) = self.trigger_expected_returns(trigger)
229 && script.return_types != expected_returns
230 && !expected_returns.is_empty()
231 {
232 let expected: Vec<&str> = expected_returns.iter().map(|t| t.name()).collect();
233 self.error(
234 script.line,
235 msg::fmt(
236 msg::SCRIPT_TRIGGER_EXPECTED_RETURNS,
237 &[trigger, &expected.join(", ")],
238 ),
239 );
240 }
241
242 let subject = &script.name;
244 match trigger {
245 "debugproc" | "command" => {}
247
248 "opnpc1" | "opnpc2" | "opnpc3" | "opnpc4" | "opnpc5" | "opobj1" | "opobj2"
250 | "opobj3" | "opobj4" | "opobj5" | "oploc1" | "oploc2" | "oploc3" | "oploc4"
251 | "oploc5" | "opplayer1" | "opplayer2" | "opplayer3" | "opplayer4" | "opplayer5"
252 | "opnpct" | "opobjt" | "oploct" | "opplayert" | "opnpcu" | "opobju" | "oplocu"
253 | "opplayeru" | "ai_opnpc1" | "ai_opnpc2" | "ai_opnpc3" | "ai_opnpc4" | "ai_opnpc5"
254 | "ai_oploc1" | "ai_oploc2" | "ai_oploc3" | "ai_oploc4" | "ai_oploc5" | "ai_opobj1"
255 | "ai_opobj2" | "ai_opobj3" | "ai_opobj4" | "ai_opobj5" | "ai_opplayer1"
256 | "ai_opplayer2" | "ai_opplayer3" | "ai_opplayer4" | "ai_opplayer5" => {
257 if subject == "_" {
258 } else if subject.starts_with('_') {
260 } else if subject.contains(' ') {
262 self.error(
263 script.line,
264 msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
265 );
266 }
267 }
268
269 "login" | "logout" | "mapenter" | "mapleave" | "map_enter" | "worldinit"
271 | "worldshutdown"
272 if subject != "_" && !subject.is_empty() =>
273 {
274 self.error(
275 script.line,
276 msg::fmt(msg::SCRIPT_SUBJECT_ONLY_GLOBAL, &[trigger]),
277 );
278 }
279
280 "proc" | "label" | "queue" | "softtimer" | "timer" | "controller_queue"
282 | "npc_queue" => {
283 if subject.contains(' ') {
284 self.error(
285 script.line,
286 msg::fmt(msg::SCRIPT_SUBJECT_NO_SPACES, &[trigger]),
287 );
288 }
289 if subject == "_" {
290 self.error(
291 script.line,
292 msg::fmt(msg::SCRIPT_SUBJECT_NO_GLOBAL, &[trigger]),
293 );
294 }
295 if subject.starts_with('_') && subject.len() > 1 {
296 self.error(
297 script.line,
298 msg::fmt(msg::SCRIPT_SUBJECT_NO_CATEGORY, &[trigger]),
299 );
300 }
301 }
302
303 _ => {}
304 }
305
306 if script.name.ends_with('*') && trigger != "command" {
308 self.error(script.line, msg::SCRIPT_COMMAND_ONLY.to_string());
309 }
310 }
311
312 fn trigger_expected_params(&self, trigger: &str) -> Option<&'static [Type]> {
313 if self.stack_returns {
314 triggers::lookup(trigger).and_then(|trigger| trigger.params)
315 } else {
316 None
317 }
318 }
319
320 fn trigger_expected_returns(&self, _trigger: &str) -> Option<Vec<Type>> {
321 None
322 }
323
324 fn type_allows_declaration(t: Type) -> bool {
325 !matches!(t, Type::Void | Type::Error | Type::Any)
326 }
327
328 fn type_allows_array(t: Type) -> bool {
329 Self::type_allows_declaration(t) && t.base_type() == BaseVarType::Integer
330 }
331
332 fn type_allows_parameter(t: Type) -> bool {
333 !matches!(t, Type::Void | Type::Error)
334 }
335
336 fn check_block(
337 &mut self,
338 stmts: &[Statement],
339 parent: &SymbolTable,
340 return_types: Option<&[Type]>,
341 ) {
342 let mut child = parent.new_child();
343 for s in stmts {
344 self.check_statement(s, &mut child, return_types);
345 }
346 }
347
348 fn check_statement(
349 &mut self,
350 stmt: &Statement,
351 locals: &mut SymbolTable,
352 return_types: Option<&[Type]>,
353 ) {
354 match stmt {
355 Statement::VarDeclaration {
356 var_type,
357 name,
358 value,
359 line,
360 } => {
361 if locals.lookup(name).is_some() {
363 self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
364 }
365 if !Self::type_allows_declaration(*var_type) {
367 self.error(
368 *line,
369 msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[var_type.name()]),
370 );
371 }
372
373 if self.stack_returns {
375 locals.define_local(name.clone(), *var_type, false);
376 }
377 if let Some(init_expr) = value {
378 self.warn_if_bare_command_value(init_expr, *line);
379 let expr_type = self.infer_expr_type(init_expr, locals, *line, Some(*var_type));
380 if let Some(et) = expr_type
381 && !self.types_compatible(et, *var_type)
382 {
383 self.emit_type_mismatch(*line, et, *var_type);
384 }
385 self.warn_if_int_for_boolean(init_expr, *var_type, *line);
386 }
387 locals.define_local(name.clone(), *var_type, false);
388 }
389
390 Statement::ArrayDeclaration {
391 element_type,
392 name,
393 size,
394 line,
395 } => {
396 if locals.lookup(name).is_some_and(|symbol| {
398 !matches!(symbol.kind, SymbolKind::LocalVar { is_array: true, .. })
399 }) {
400 self.error(*line, msg::fmt(msg::SCRIPT_LOCAL_REDECLARATION, &[name]));
401 }
402 if !Self::type_allows_declaration(*element_type) {
404 self.error(
405 *line,
406 msg::fmt(msg::LOCAL_DECLARATION_INVALID_TYPE, &[element_type.name()]),
407 );
408 }
409 if !Self::type_allows_array(*element_type) {
410 self.error(
411 *line,
412 msg::fmt(msg::LOCAL_ARRAY_INVALID_TYPE, &[element_type.name()]),
413 );
414 }
415
416 let size_type = self.infer_expr_type(size, locals, *line, Some(Type::Int));
417 if let Some(st) = size_type
418 && !self.types_compatible(st, Type::Int)
419 {
420 self.emit_type_mismatch(*line, st, Type::Int);
421 }
422 locals.define_local(name.clone(), *element_type, true);
423 }
424
425 Statement::Assignment {
426 target,
427 value,
428 line,
429 } => {
430 self.warn_if_bare_command_value(value, *line);
431 if matches!(target, Expr::MultiAssign(..)) || matches!(value, Expr::Tuple(_)) {
432 let targets = match target {
433 Expr::MultiAssign(targets, _) => targets.as_slice(),
434 _ => from_ref(target),
435 };
436 let values = match value {
437 Expr::Tuple(values) => values.as_slice(),
438 _ => from_ref(value),
439 };
440 let expected: Vec<_> = targets
441 .iter()
442 .filter_map(|target| self.infer_expr_type(target, locals, *line, None))
443 .collect();
444 let hints = stack_hints(self.registry, &expected, values, locals);
445 let actual: Vec<_> = values
446 .iter()
447 .zip(hints)
448 .map(|(value, hint)| self.infer_expr_type(value, locals, *line, hint))
449 .collect();
450 let actual = self.expand_call_types(values, &actual);
451 if actual
452 .iter()
453 .any(|ty| ty.is_none() || *ty == Some(Type::Any))
454 {
455 return;
456 }
457 for base in [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long] {
458 let expected: Vec<_> = expected
459 .iter()
460 .copied()
461 .filter(|ty| ty.base_type() == base)
462 .collect();
463 let actual: Vec<_> = actual
464 .iter()
465 .filter_map(|ty| *ty)
466 .filter(|ty| ty.base_type() == base)
467 .collect();
468 if expected.len() != actual.len() {
469 self.error(
470 *line,
471 "Assignment value count does not match its targets".into(),
472 );
473 }
474 for (actual, expected) in actual.into_iter().zip(expected) {
475 if !self.types_compatible(actual, expected) {
476 self.emit_type_mismatch(*line, actual, expected);
477 }
478 }
479 }
480 return;
481 }
482 let target_type = self.infer_expr_type(target, locals, *line, None);
483 let value_type = self.infer_expr_type(value, locals, *line, target_type);
484 if let (Some(tt), Some(vt)) = (target_type, value_type)
485 && !self.types_compatible(vt, tt)
486 {
487 self.emit_type_mismatch(*line, vt, tt);
488 }
489 if let Some(tt) = target_type {
490 self.warn_if_int_for_boolean(value, tt, *line);
491 }
492 }
493
494 Statement::If {
495 condition,
496 body,
497 else_if,
498 else_body,
499 line,
500 ..
501 } => {
502 self.check_condition(condition, locals, *line);
503 self.check_block(body, locals, return_types);
504 for (cond, stmts, ei_line) in else_if {
505 self.check_condition(cond, locals, *ei_line);
506 self.check_block(stmts, locals, return_types);
507 }
508 if let Some(else_stmts) = else_body {
509 self.check_block(else_stmts, locals, return_types);
510 }
511 }
512
513 Statement::While {
514 condition,
515 body,
516 line,
517 } => {
518 self.check_condition(condition, locals, *line);
519 self.check_block(body, locals, return_types);
520 }
521
522 Statement::Switch {
523 switch_type,
524 expr,
525 cases,
526 default,
527 line,
528 ..
529 } => {
530 let type_name = switch_type.strip_prefix("switch_").unwrap_or(switch_type);
531 let resolved_type = Type::from_name(type_name);
532 if resolved_type.is_none() {
533 self.error(*line, msg::fmt(msg::GENERIC_INVALID_TYPE, &[type_name]));
534 }
535 let switch_ty = resolved_type.unwrap_or(Type::Error);
536
537 if switch_ty != Type::Error && !switch_ty.allow_switch() {
539 self.error(
540 *line,
541 msg::fmt(msg::SWITCH_INVALID_TYPE, &[switch_ty.name()]),
542 );
543 }
544
545 let expr_type = self.infer_expr_type(expr, locals, *line, Some(switch_ty));
546 let valid_expr = switch_ty != Type::Error
547 && switch_ty.allow_switch()
548 && expr_type.is_some_and(|actual| {
549 actual != Type::Error && self.types_compatible(actual, switch_ty)
550 });
551 if let Some(et) = expr_type
552 && switch_ty != Type::Error
553 && !self.types_compatible(et, switch_ty)
554 {
555 self.emit_type_mismatch(*line, et, switch_ty);
556 }
557
558 for case in cases {
562 self.check_switch_case(case, Some(switch_ty), locals, return_types, *line);
563 }
564 if let Some(default_stmts) = default {
565 self.check_block(default_stmts, locals, return_types);
566 } else if valid_expr {
567 let domain = if self.registry.switch_values(switch_ty).is_some() {
568 switch_ty
569 } else if switch_ty == Type::Int {
570 expr_type.unwrap_or(switch_ty)
571 } else {
572 switch_ty
573 };
574 self.check_exhaustive_switch(domain, switch_ty, cases, *line);
575 }
576 }
577
578 Statement::Return { values, line } => {
579 let script_returns = match return_types {
580 Some(rt) => rt,
581 None => {
582 self.error(*line, msg::RETURN_ORPHAN.to_string());
583 return;
584 }
585 };
586 if self.stack_returns {
587 let hints = positional_hints(self.registry, script_returns, values, locals);
588 let actual: Vec<_> = values
589 .iter()
590 .zip(hints)
591 .map(|(value, hint)| self.infer_expr_type(value, locals, *line, hint))
592 .collect();
593 self.check_call_arguments(
594 "return",
595 script_returns,
596 &actual,
597 values,
598 *line,
599 CallKind::Proc,
600 );
601 return;
602 }
603 let is_single_proc_call = values.len() == 1
604 && matches!(&values[0], Expr::ProcCall { .. } | Expr::CommandCall { .. });
605 if values.len() != script_returns.len() && !is_single_proc_call {
606 self.error(
607 *line,
608 msg::fmt(
609 msg::GENERIC_TYPE_MISMATCH,
610 &[
611 &format!("{} value(s)", values.len()),
612 &format!("{} value(s)", script_returns.len()),
613 ],
614 ),
615 );
616 }
617 for (i, val) in values.iter().enumerate() {
618 let hint = script_returns.get(i).copied();
619 let val_type = self.infer_expr_type(val, locals, *line, hint);
620 if let Some(vt) = val_type
621 && let Some(expected) = hint
622 && !self.types_compatible(vt, expected)
623 {
624 self.emit_type_mismatch(*line, vt, expected);
625 }
626 if let Some(expected) = hint {
627 self.warn_if_int_for_boolean(val, expected, *line);
628 }
629 }
630 }
631
632 Statement::Expression { expr, line } => {
633 let bare_cmd = self.warn_if_bare_command_value(expr, *line);
636 let expr_type = self.infer_expr_type(expr, locals, *line, None);
637 if !bare_cmd
638 && let Some(et) = expr_type
639 && et != Type::Error
640 && !self.expression_has_side_effects(expr)
641 {
642 self.warning(*line, msg::EXPRESSION_STATEMENT_NO_SIDE_EFFECT.to_string());
643 }
644 }
645 Statement::OrphanCase { case, line } => {
646 self.check_switch_case(case, None, locals, return_types, *line);
647 }
648 Statement::Empty => {}
649 }
650 }
651
652 fn check_condition(&mut self, expr: &Expr, locals: &SymbolTable, line: usize) {
653 match expr {
654 Expr::BinaryOp { op, lhs, rhs } => {
655 match op {
658 BinOp::Eq
659 | BinOp::NotEq
660 | BinOp::Lt
661 | BinOp::Gt
662 | BinOp::LtEq
663 | BinOp::GtEq
664 if (self.is_condition_expr(lhs) || self.is_condition_expr(rhs)) =>
665 {
666 self.error(line, msg::CONDITION_NOT_VALID.to_string());
667 return;
668 }
669 _ => {}
670 }
671
672 let lt = self.infer_expr_type(lhs, locals, line, None);
673 let rhs_hint = lt;
674 let rt = self.infer_expr_type(rhs, locals, line, rhs_hint);
675
676 match op {
677 BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
678 if let Some(ref lt) = lt
679 && lt.base_type() == BaseVarType::String
680 && *lt != Type::Error
681 && *lt != Type::Any
682 {
683 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
684 }
685 if let Some(ref rt) = rt
686 && rt.base_type() == BaseVarType::String
687 && *rt != Type::Error
688 && *rt != Type::Any
689 {
690 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
691 }
692 }
693 BinOp::Eq | BinOp::NotEq => {
694 if let (Some(lt), Some(rt)) = (<, &rt)
695 && *lt == Type::String
696 && *rt == Type::String
697 {
698 let op_str = if *op == BinOp::Eq { "=" } else { "!" };
699 self.error(
700 line,
701 msg::fmt(msg::BINOP_INVALID_TYPES, &[op_str, lt.name(), rt.name()]),
702 );
703 }
704 if let Some(lt) = lt {
705 self.warn_if_int_for_boolean(rhs, lt, line);
706 }
707 if let Some(rt) = rt {
708 self.warn_if_int_for_boolean(lhs, rt, line);
709 }
710 }
711 _ => {}
712 }
713 }
714 Expr::LogicalOp { lhs, rhs, .. } => {
715 self.check_condition(lhs, locals, line);
716 self.check_condition(rhs, locals, line);
717 }
718 _ => {
719 if let Some(ty) = self.infer_expr_type(expr, locals, line, None)
720 && ty.base_type() != BaseVarType::Integer
721 {
722 self.error(
723 line,
724 format!("Condition requires a boolean or integer, got {}", ty.name()),
725 );
726 }
727 }
728 }
729 }
730
731 fn is_condition_expr(&self, expr: &Expr) -> bool {
732 match expr {
733 Expr::BinaryOp { op, .. } => matches!(
734 op,
735 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq
736 ),
737 Expr::LogicalOp { .. } => true,
738 _ => false,
739 }
740 }
741
742 fn check_exhaustive_switch(
743 &mut self,
744 ty: Type,
745 case_type: Type,
746 cases: &[SwitchCase],
747 line: usize,
748 ) {
749 let Some(domain) = self.registry.switch_values(ty) else {
750 return;
751 };
752 let mut covered = HashSet::new();
753 for value in cases.iter().flat_map(|case| &case.values) {
754 let value = match value {
755 Expr::IntLiteral(value) | Expr::CoordLiteral(value) => Some(*value),
756 Expr::BoolLiteral(value) => Some(i32::from(*value)),
757 Expr::NullLiteral => Some(-1),
758 Expr::ConstantVar(name, _) => {
759 self.registry
760 .lookup_constant(name)
761 .and_then(|symbol| match symbol.kind {
762 SymbolKind::Constant { int_value, .. } => int_value,
763 _ => None,
764 })
765 }
766 Expr::StringLiteral(name) => self.registry.lookup_reference(name, case_type),
769 Expr::Identifier(name) => name
770 .split_once(':')
771 .and_then(|(interface, component)| {
772 self.registry.lookup_component(interface, component)
773 })
774 .or_else(|| self.registry.lookup_reference(name, case_type))
775 .or_else(|| {
776 self.registry
777 .entity_ids
778 .get(name)
779 .and_then(|entry| entry.primary)
780 .map(|entity| entity.id)
781 })
782 .or_else(|| {
783 self.registry
784 .lookup_constant(name)
785 .and_then(|symbol| match symbol.kind {
786 SymbolKind::Constant { int_value, .. } => int_value,
787 _ => None,
788 })
789 }),
790 Expr::BinaryOp {
791 op: BinOp::Add,
792 lhs,
793 rhs,
794 } => match (lhs.as_ref(), rhs.as_ref()) {
795 (Expr::Identifier(left), Expr::Identifier(right)) => self
796 .registry
797 .lookup_entity_id_typed(&format!("{left}+{right}"), case_type),
798 _ => None,
799 },
800 _ => None,
801 };
802 let Some(value) = value else {
803 return;
804 };
805 covered.insert(value);
806 }
807 let missing = domain
808 .iter()
809 .filter(|(value, _)| !covered.contains(*value))
810 .map(|(_, name)| name.as_str())
811 .collect::<Vec<_>>();
812 if !missing.is_empty() {
813 let listed = missing
814 .iter()
815 .take(12)
816 .copied()
817 .collect::<Vec<_>>()
818 .join(", ");
819 let more = if missing.len() > 12 {
820 format!(" and {} more", missing.len() - 12)
821 } else {
822 String::new()
823 };
824 self.warning(line, format!("Non-exhaustive switch on {}: missing {listed}{more}; add the cases or a default branch.", ty.name()));
825 }
826 }
827
828 fn check_switch_case(
832 &mut self,
833 case: &SwitchCase,
834 parent_switch_type: Option<Type>,
835 locals: &SymbolTable,
836 return_types: Option<&[Type]>,
837 line: usize,
838 ) {
839 let switch_ty = match parent_switch_type {
840 Some(t) => t,
841 None => {
842 self.error(line, msg::CASE_WITHOUT_SWITCH.to_string());
843 return;
844 }
845 };
846
847 for val in &case.values {
848 if !self.is_constant_expression(val) {
849 self.warning(line, msg::SWITCH_CASE_NOT_CONSTANT.to_string());
850 }
851 let val_type = self.infer_expr_type(val, locals, line, Some(switch_ty));
852 if let Some(vt) = val_type
853 && switch_ty != Type::Error
854 && !self.types_compatible(vt, switch_ty)
855 {
856 self.emit_type_mismatch(line, vt, switch_ty);
857 }
858 }
859 self.check_block(&case.body, locals, return_types);
860 }
861
862 fn infer_expr_type(
867 &mut self,
868 expr: &Expr,
869 locals: &SymbolTable,
870 line: usize,
871 hint: Option<Type>,
872 ) -> Option<Type> {
873 if let Some(message) =
874 self.registry
875 .visibility
876 .reference(&self.file_path, expr, hint, self.registry)
877 {
878 self.error(line, message);
879 return Some(Type::Error);
880 }
881 match expr {
882 Expr::IntLiteral(_) => {
883 if let Some(h) = hint {
886 if !is_literal_type(h) && h != Type::Error && h != Type::Any {
887 return Some(h);
888 }
889 if h == Type::Boolean {
890 return Some(Type::Boolean);
891 }
892 }
893 Some(Type::Int)
894 }
895 Expr::LongLiteral(_) => Some(Type::Long),
896 Expr::StringLiteral(s) => {
897 if let Some(h) = hint
901 && !is_literal_type(h)
902 && h != Type::Error
903 && h != Type::Any
904 {
905 let typed_ok = self.registry.lookup_reference(s, h).is_some();
917 let untyped_ok = self.registry.lookup_entity_id(s).is_some();
918 let script_ok = self.registry.proc_script_id(s).is_some()
919 || self.registry.script_id(s).is_some();
920 if !typed_ok && !untyped_ok && !script_ok {
921 self.emit_unresolved_entity_warning(line, s, h);
922 } else if is_valid_bare_ident(s) {
923 self.emit_prefer_bare_ident_warning(line, s, h);
927 }
928 return Some(h);
929 }
930 Some(Type::String)
931 }
932 Expr::BoolLiteral(_) => Some(Type::Boolean),
933 Expr::NullLiteral => {
934 if let Some(h) = hint
936 && h != Type::Error
937 {
938 return Some(h);
939 }
940 Some(Type::Int)
941 }
942 Expr::CharLiteral(_) => Some(Type::Char),
943 Expr::CoordLiteral(_) => Some(Type::Coord),
944
945 Expr::LocalVar(name, src_line) => {
946 if let Some(sym) = locals.lookup(name) {
947 match &sym.kind {
948 SymbolKind::LocalVar {
949 var_type, is_array, ..
950 } => {
951 if *is_array {
953 self.error(
954 *src_line,
955 msg::fmt(msg::LOCAL_ARRAY_REFERENCE_NOINDEX, &[name]),
956 );
957 return Some(Type::Error);
958 }
959 Some(*var_type)
960 }
961 SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
962 _ => None,
963 }
964 } else {
965 self.error(
966 *src_line,
967 msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]),
968 );
969 Some(Type::Error)
970 }
971 }
972
973 Expr::ArrayAccess { name, index } => {
974 if let Some(sym) = locals.lookup(name) {
975 match &sym.kind {
976 SymbolKind::LocalVar {
977 var_type, is_array, ..
978 } => {
979 if !is_array {
980 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
982 }
983 let idx_type =
984 self.infer_expr_type(index, locals, line, Some(Type::Int));
985 if let Some(it) = idx_type
986 && !self.types_compatible(it, Type::Int)
987 {
988 self.emit_type_mismatch(line, it, Type::Int);
989 }
990 Some(*var_type)
991 }
992 SymbolKind::ScriptParam { param_type, .. } => {
993 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_NOT_ARRAY, &[name]));
994 Some(*param_type)
995 }
996 _ => None,
997 }
998 } else {
999 self.error(line, msg::fmt(msg::LOCAL_REFERENCE_UNRESOLVED, &[name]));
1000 Some(Type::Error)
1001 }
1002 }
1003
1004 Expr::GameVar(name, src_line) => {
1005 if let Some(sym) = self.registry.lookup_game_var(name) {
1006 match &sym.kind {
1007 SymbolKind::GameVar { var_type, .. } => Some(*var_type),
1008 _ => None,
1009 }
1010 } else {
1011 self.error(*src_line, msg::fmt(msg::GAME_REFERENCE_UNRESOLVED, &[name]));
1012 Some(Type::Error)
1013 }
1014 }
1015
1016 Expr::ConstantVar(name, src_line) => {
1017 if let Some(sym) = self.registry.lookup_constant(name) {
1018 match &sym.kind {
1019 SymbolKind::Constant { const_type, .. } => Some(*const_type),
1020 _ => None,
1021 }
1022 } else {
1023 self.error(
1024 *src_line,
1025 msg::fmt(msg::CONSTANT_REFERENCE_UNRESOLVED, &[name]),
1026 );
1027 Some(Type::Error)
1028 }
1029 }
1030
1031 Expr::Identifier(name) => {
1032 if let Some(h) = hint
1035 && h != Type::Error
1036 && h != Type::Any
1037 && self.registry.lookup_reference(name, h).is_some()
1038 {
1039 return Some(h);
1040 }
1041
1042 if hint == Some(Type::Int) && self.registry.type_chars.contains_key(name) {
1047 return Some(Type::Int);
1048 }
1049
1050 let entity = self.registry.lookup_entity_id(name).filter(|entity| {
1054 !self.registry.command_fills(name, hint)
1055 && !(entity.const_type == Type::Param
1056 && hint != Some(Type::Param)
1057 && self.registry.type_chars.contains_key(name))
1058 });
1059 if let Some(sym) = self.registry.lookup_constant(name) {
1060 match &sym.kind {
1061 SymbolKind::Constant { const_type, .. } => Some(*const_type),
1062 other => {
1063 let kind_name = other.kind_name();
1064 self.error(
1065 line,
1066 msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[kind_name]),
1067 );
1068 Some(Type::Error)
1069 }
1070 }
1071 } else if let Some(e) = entity {
1072 Some(e.const_type)
1073 } else if let Some(sym) = self.registry.lookup_command(name).cloned() {
1074 if let SymbolKind::Command { return_types, .. } = &sym.kind {
1075 return return_types.first().copied();
1076 }
1077 self.error(
1078 line,
1079 msg::fmt(msg::UNSUPPORTED_SYMBOLTYPE_TO_TYPE, &[sym.kind.kind_name()]),
1080 );
1081 Some(Type::Error)
1082 } else if self.registry.type_chars.contains_key(name) {
1083 Some(Type::Int)
1084 } else if name.contains(':') {
1085 let parts: Vec<&str> = name.splitn(2, ':').collect();
1087 if parts.len() == 2
1088 && self.registry.lookup_component(parts[0], parts[1]).is_some()
1089 {
1090 Some(Type::Component)
1091 } else if let Some(h) = hint {
1092 if h != Type::Error {
1093 Some(h)
1094 } else {
1095 Some(Type::Error)
1096 }
1097 } else {
1098 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
1099 Some(Type::Error)
1100 }
1101 } else {
1102 if let Some(h) = hint {
1107 if h == Type::String {
1108 return Some(Type::String);
1109 }
1110 if h != Type::Error {
1111 let resolved = self.registry.lookup_entity_id_typed(name, h).is_some()
1129 || self.registry.lookup_entity_id(name).is_some()
1130 || self
1131 .registry
1132 .trigger(name)
1133 .is_some_and(|trigger| trigger.byte.is_some())
1134 || (h == Type::Int && self.registry.command_opcode(name).is_some())
1135 || self.registry.proc_script_id(name).is_some()
1136 || self.registry.script_id(name).is_some();
1137 if !resolved {
1138 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
1139 return Some(Type::Error);
1140 }
1141 return Some(h);
1142 }
1143 }
1144 self.error(line, msg::fmt(msg::GENERIC_UNRESOLVED_SYMBOL, &[name]));
1145 Some(Type::Error)
1146 }
1147 }
1148
1149 Expr::BinaryOp { op, lhs, rhs } => match op {
1150 BinOp::Add
1151 | BinOp::Sub
1152 | BinOp::Mul
1153 | BinOp::Div
1154 | BinOp::Mod
1155 | BinOp::BitAnd
1156 | BinOp::BitOr => {
1157 if matches!(op, BinOp::Add)
1164 && let (Expr::Identifier(lname), Expr::Identifier(rname)) =
1165 (lhs.as_ref(), rhs.as_ref())
1166 {
1167 let combined = format!("{}+{}", lname, rname);
1168 if let Some(h) = hint {
1169 if self.registry.lookup_entity_id_typed(&combined, h).is_some()
1170 || self.registry.lookup_entity_id(&combined).is_some()
1171 {
1172 return Some(h);
1173 }
1174 } else if let Some(e) = self.registry.lookup_entity_id(&combined) {
1175 return Some(e.const_type);
1176 }
1177 }
1178
1179 let expected = hint.unwrap_or(Type::Int);
1180 let lt = self.infer_expr_type(lhs, locals, line, Some(expected));
1181 let rt = self.infer_expr_type(rhs, locals, line, Some(expected));
1182 if let Some(ref lt) = lt
1183 && lt.base_type() == BaseVarType::String
1184 && *lt != Type::Error
1185 && *lt != Type::Any
1186 {
1187 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[lt.name()]));
1188 }
1189 if let Some(ref rt) = rt
1190 && rt.base_type() == BaseVarType::String
1191 && *rt != Type::Error
1192 && *rt != Type::Any
1193 {
1194 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[rt.name()]));
1195 }
1196 if matches!(lt, Some(Type::Long)) || matches!(rt, Some(Type::Long)) {
1197 Some(Type::Long)
1198 } else {
1199 Some(hint.unwrap_or(Type::Int))
1200 }
1201 }
1202 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::Gt | BinOp::LtEq | BinOp::GtEq => {
1203 let lt = self.infer_expr_type(lhs, locals, line, None);
1204 let _ = self.infer_expr_type(rhs, locals, line, lt);
1205 Some(Type::Boolean)
1206 }
1207 },
1208
1209 Expr::LogicalOp { lhs, rhs, .. } => {
1210 let _ = self.infer_expr_type(lhs, locals, line, None);
1211 let _ = self.infer_expr_type(rhs, locals, line, None);
1212 Some(Type::Boolean)
1213 }
1214
1215 Expr::Calc(inner) => {
1216 let expected = hint.unwrap_or(Type::Int);
1217 let inner_type = self.infer_expr_type(inner, locals, line, Some(expected));
1218 if let Some(ref it) = inner_type
1219 && it.base_type() == BaseVarType::String
1220 && *it != Type::Error
1221 && *it != Type::Any
1222 {
1223 self.error(line, msg::fmt(msg::ARITHMETIC_INVALID_TYPE, &[it.name()]));
1224 }
1225 inner_type
1226 }
1227
1228 Expr::CommandCall {
1229 name,
1230 args,
1231 call_line,
1232 ..
1233 } => {
1234 let call = match hooks::server_call(self.registry, name, args, locals, *call_line) {
1235 Ok(call) => call,
1236 Err(error) => {
1237 self.error(*call_line, error);
1238 return Some(Type::Error);
1239 }
1240 };
1241 let (name, args, call_line) = match &call {
1242 Some(Expr::CommandCall {
1243 name,
1244 args,
1245 call_line,
1246 ..
1247 }) => (name, args, call_line),
1248 _ => (name, args, call_line),
1249 };
1250 let lookup_name = name.strip_prefix('.').unwrap_or(name);
1251 if lookup_name.starts_with("__") {
1252 let (values, result): (Vec<&Expr>, Option<Type>) = match lookup_name {
1253 "__label" | "__jump" | "__opcode" => (vec![], None),
1254 "__branch" => (args.iter().skip(2).collect(), None),
1255 "__switch" => (args.first().into_iter().collect(), None),
1256 "__push" => (args.iter().collect(), None),
1257 "__pop_int" => (vec![], Some(Type::Int)),
1258 "__pop_string" => (vec![], Some(Type::String)),
1259 "__pop_long" => (vec![], Some(Type::Long)),
1260 "__join" => (args.iter().collect(), Some(Type::String)),
1261 "__get_array" => (args.iter().collect(), Some(Type::Int)),
1262 "__set_array" | "__define_array" => (args.iter().collect(), None),
1263 _ => {
1264 self.error(*call_line, format!("Unknown intrinsic {name}"));
1265 (vec![], None)
1266 }
1267 };
1268 for value in values {
1269 self.infer_expr_type(value, locals, *call_line, None);
1270 }
1271 return result;
1272 }
1273
1274 if !self.current_script_is_test
1275 && Self::is_test_command(lookup_name)
1276 && !self.registry.stack_commands.contains(lookup_name)
1277 {
1278 self.error(
1279 *call_line,
1280 msg::fmt(msg::TEST_COMMAND_FROM_PRODUCTION, &[lookup_name]),
1281 );
1282 }
1283
1284 let lowered =
1285 match hooks::lower(self.registry, lookup_name, args, locals, *call_line) {
1286 Ok(args) => args,
1287 Err(error) => {
1288 self.error(*call_line, error);
1289 return Some(Type::Error);
1290 }
1291 };
1292 let args = lowered.as_deref().unwrap_or(args);
1293 let hints = command_hints(self.registry, lookup_name, args, locals);
1294
1295 let arg_types: Vec<Option<Type>> = args
1296 .iter()
1297 .enumerate()
1298 .map(|(i, a)| {
1299 let arg_hint = hints.get(i).copied().flatten();
1300 self.infer_expr_type(a, locals, *call_line, arg_hint)
1301 })
1302 .collect();
1303
1304 let is_variadic = lookup_name.ends_with('*');
1305 let cmd_sym = self
1306 .registry
1307 .lookup_command(lookup_name)
1308 .cloned()
1309 .or_else(|| {
1310 lookup_name.strip_suffix('*').and_then(|base| {
1311 let vararg_name = format!("{}vararg", base);
1312 self.registry.lookup_command(&vararg_name).cloned()
1313 })
1314 });
1315 if let Some(sym) = cmd_sym {
1316 if let SymbolKind::Command {
1317 param_types: cmd_params,
1318 ..
1319 } = &sym.kind
1320 {
1321 if self.registry.stack_commands.contains(lookup_name) {
1322 if self.registry.hook_commands.contains_key(lookup_name)
1323 && !args.iter().any(|arg| matches!(arg, Expr::StringLiteral(_)))
1324 {
1325 self.error(
1326 *call_line,
1327 "Client hook needs a constant signature".into(),
1328 );
1329 }
1330 let params =
1331 command_parameters(self.registry, lookup_name, args, locals);
1332 self.check_call_arguments(
1333 name,
1334 ¶ms,
1335 &arg_types,
1336 args,
1337 *call_line,
1338 CallKind::Command,
1339 );
1340 } else if let Some(fixed) = Compiler::command_variadic_info(lookup_name) {
1341 self.check_variadic_arguments(
1342 name,
1343 lookup_name,
1344 fixed,
1345 cmd_params,
1346 &arg_types,
1347 args,
1348 *call_line,
1349 );
1350 } else if !is_variadic {
1351 self.check_call_arguments(
1352 name,
1353 cmd_params,
1354 &arg_types,
1355 args,
1356 *call_line,
1357 CallKind::Command,
1358 );
1359 }
1360 return command_returns(self.registry, lookup_name, args)
1361 .first()
1362 .copied();
1363 }
1364 } else {
1365 self.error(
1366 *call_line,
1367 msg::fmt(msg::COMMAND_REFERENCE_UNRESOLVED, &[name]),
1368 );
1369 return Some(Type::Error);
1370 }
1371 None
1372 }
1373
1374 Expr::ProcCall {
1375 name,
1376 args,
1377 call_line,
1378 ..
1379 } => {
1380 let script_sym = self
1382 .registry
1383 .lookup_script_by_trigger("proc", name)
1384 .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name))
1385 .cloned();
1386
1387 if self.registry.proc_script_id(name).is_none() && script_sym.is_none() {
1388 self.error(
1389 *call_line,
1390 msg::fmt(msg::PROC_REFERENCE_UNRESOLVED, &[name]),
1391 );
1392 for arg in args {
1394 let _ = self.infer_expr_type(arg, locals, *call_line, None);
1395 }
1396 return Some(Type::Error);
1397 }
1398
1399 if !self.current_script_is_test && self.registry.is_test_script("proc", name) {
1400 self.error(
1401 *call_line,
1402 msg::fmt(msg::TEST_PROC_FROM_PRODUCTION, &[name]),
1403 );
1404 }
1405
1406 let (p_types, r_types) = if let Some(ref sym) = script_sym {
1407 if let SymbolKind::Script {
1408 param_types,
1409 return_types,
1410 ..
1411 } = &sym.kind
1412 {
1413 (param_types.clone(), return_types.clone())
1414 } else {
1415 (vec![], vec![])
1416 }
1417 } else {
1418 (vec![], vec![])
1419 };
1420
1421 let hints = proc_hints(self.registry, name, args, locals);
1422 let arg_types: Vec<Option<Type>> = args
1423 .iter()
1424 .enumerate()
1425 .map(|(i, a)| {
1426 let arg_hint = hints.get(i).copied().flatten();
1427 self.infer_expr_type(a, locals, *call_line, arg_hint)
1428 })
1429 .collect();
1430
1431 if script_sym.is_some() {
1432 self.check_call_arguments(
1433 name,
1434 &p_types,
1435 &arg_types,
1436 args,
1437 *call_line,
1438 CallKind::Proc,
1439 );
1440 }
1441 r_types.first().copied()
1442 }
1443
1444 Expr::JumpCall {
1445 name,
1446 args,
1447 call_line,
1448 ..
1449 } => {
1450 if self.current_script_is_proc {
1451 self.error(*call_line, msg::fmt(msg::JUMP_IN_PROC, &[name]));
1452 }
1453 let script_sym = self
1454 .registry
1455 .lookup_script_by_trigger("label", name)
1456 .cloned();
1457
1458 if self.registry.label_script_id(name).is_none() {
1459 self.error(
1460 *call_line,
1461 msg::fmt(msg::JUMP_REFERENCE_UNRESOLVED, &[name]),
1462 );
1463 for arg in args {
1464 let _ = self.infer_expr_type(arg, locals, *call_line, None);
1465 }
1466 return Some(Type::Error);
1467 }
1468
1469 if !self.current_script_is_test && self.registry.is_test_script("label", name) {
1470 self.error(
1471 *call_line,
1472 msg::fmt(msg::TEST_LABEL_FROM_PRODUCTION, &[name]),
1473 );
1474 }
1475
1476 let p_types = if let Some(ref sym) = script_sym {
1477 if let SymbolKind::Script { param_types, .. } = &sym.kind {
1478 param_types.clone()
1479 } else {
1480 vec![]
1481 }
1482 } else {
1483 vec![]
1484 };
1485
1486 let arg_types: Vec<Option<Type>> = args
1487 .iter()
1488 .enumerate()
1489 .map(|(i, a)| {
1490 let arg_hint = p_types.get(i).copied();
1491 self.infer_expr_type(a, locals, *call_line, arg_hint)
1492 })
1493 .collect();
1494
1495 if script_sym.is_some() {
1496 self.check_call_arguments(
1497 name,
1498 &p_types,
1499 &arg_types,
1500 args,
1501 *call_line,
1502 CallKind::Jump,
1503 );
1504 }
1505 None
1506 }
1507
1508 Expr::JoinedString { parts } => {
1509 for part in parts {
1510 if let StringPart::Expr(e) = part {
1511 let _ = self.infer_expr_type(e, locals, line, Some(Type::String));
1512 }
1513 }
1514 Some(Type::String)
1515 }
1516
1517 Expr::Tuple(values) => {
1518 for value in values {
1519 self.infer_expr_type(value, locals, line, None);
1520 }
1521 None
1522 }
1523 Expr::MultiAssign(targets, _) => {
1524 for target in targets {
1526 if let Expr::ArrayAccess { name, .. } = target {
1527 self.error(line, msg::fmt(msg::ASSIGN_MULTI_ARRAY, &[name]));
1528 }
1529 }
1530 None
1531 }
1532 }
1533 }
1534
1535 fn stack_arguments(&self, name: &str, kind: CallKind) -> bool {
1538 let trigger = match kind {
1539 CallKind::Command => {
1540 return self
1541 .registry
1542 .stack_commands
1543 .contains(name.trim_start_matches('.'));
1544 }
1545 CallKind::Proc if name == "return" => return self.stack_returns,
1546 CallKind::Proc
1547 if self
1548 .registry
1549 .lookup_script_by_trigger("proc", name)
1550 .is_some() =>
1551 {
1552 "proc"
1553 }
1554 CallKind::Proc => "clientscript",
1555 CallKind::Jump => "label",
1556 };
1557 self.registry
1558 .stack_scripts
1559 .contains(&format!("{trigger}:{name}"))
1560 }
1561
1562 fn expand_call_types(&self, args: &[Expr], types: &[Option<Type>]) -> Vec<Option<Type>> {
1563 args.iter()
1564 .zip(types)
1565 .flat_map(|(expr, ty)| {
1566 let symbol = match expr {
1567 Expr::Identifier(name) if self.registry.lookup_command(name.trim_start_matches('.')).is_some() => {
1568 let returns = command_returns(self.registry,name,&[]);
1569 return if returns.len() > 1 && returns.first() == ty.as_ref()
1570 && !ty.is_some_and(|ty| self.registry.lookup_reference(name,ty).is_some()) {
1571 returns.into_iter().map(Some).collect()
1572 } else { vec![*ty] };
1573 }
1574 Expr::ProcCall { name, .. } => self
1575 .registry
1576 .lookup_script_by_trigger("proc", name)
1577 .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name)),
1578 Expr::CommandCall { name, args, .. } => {
1579 let name = name.trim_start_matches('.');
1580 if !self.registry.stack_commands.contains(name)
1581 && matches!(self.registry.lookup_command(name).map(|symbol| &symbol.kind),
1582 Some(SymbolKind::Command { return_types, .. })
1583 if return_types.is_empty()) {
1584 return vec![None];
1585 }
1586 return command_returns(self.registry, name, args)
1587 .into_iter()
1588 .map(Some)
1589 .collect();
1590 }
1591 _ => None,
1592 };
1593 match symbol.map(|symbol| &symbol.kind) {
1594 Some(
1595 SymbolKind::Script { return_types, .. }
1596 | SymbolKind::Command { return_types, .. },
1597 ) => return_types.iter().copied().map(Some).collect(),
1598 _ => vec![*ty],
1599 }
1600 })
1601 .collect()
1602 }
1603
1604 fn call_values(&self, args: &[Expr], types: &[Option<Type>]) -> Option<Vec<Option<Type>>> {
1606 let mut values = Vec::with_capacity(args.len());
1607 for (arg, ty) in args.iter().zip(types) {
1608 match arg {
1609 Expr::ProcCall { name, .. } => {
1610 let symbol = self
1611 .registry
1612 .lookup_script_by_trigger("proc", name)
1613 .or_else(|| self.registry.lookup_script_by_trigger("clientscript", name))?;
1614 let SymbolKind::Script { return_types, .. } = &symbol.kind else {
1615 return None;
1616 };
1617 values.extend(return_types.iter().copied().map(Some));
1618 }
1619 Expr::CommandCall { name, args, .. } => {
1620 let name = name.trim_start_matches('.');
1621 let returns = if name == "db_getfield" {
1622 self.column_types(args.get(1))?
1623 } else {
1624 command_returns(self.registry, name, args)
1625 };
1626 if returns.is_empty() {
1627 return None;
1628 }
1629 values.extend(returns.into_iter().map(Some));
1630 }
1631 _ => values.extend(self.expand_call_types(from_ref(arg), from_ref(ty))),
1632 }
1633 }
1634 Some(values)
1635 }
1636
1637 fn column_types(&self, column: Option<&Expr>) -> Option<Vec<Type>> {
1639 let Some(Expr::Identifier(column)) = column else {
1640 return None;
1641 };
1642 if let Some(types) = self.registry.dbcolumn_types.get(column) {
1643 return Some(types.clone());
1644 }
1645 let (column, slot) = column.rsplit_once(':')?;
1646 let types = self.registry.dbcolumn_types.get(column)?;
1647 Some(vec![*types.get(slot.parse::<usize>().ok()?)?])
1648 }
1649
1650 #[allow(clippy::too_many_arguments)]
1653 fn check_variadic_arguments(
1654 &mut self,
1655 name: &str,
1656 command: &str,
1657 fixed: usize,
1658 params: &[Type],
1659 actual_types: &[Option<Type>],
1660 args: &[Expr],
1661 line: usize,
1662 ) {
1663 let script = Compiler::command_script_trigger(command)
1664 .zip(args.first())
1665 .and_then(|(trigger, arg)| match arg {
1666 Expr::Identifier(script) => self.registry.lookup_script_by_trigger(trigger, script),
1667 _ => None,
1668 })
1669 .and_then(|symbol| match &symbol.kind {
1670 SymbolKind::Script { param_types, .. } => Some(param_types.clone()),
1671 _ => None,
1672 });
1673 match script {
1674 Some(script) if params.len() >= fixed => {
1675 let expected = params[..fixed]
1676 .iter()
1677 .copied()
1678 .chain(script)
1679 .collect::<Vec<_>>();
1680 self.check_call_arguments(
1681 name,
1682 &expected,
1683 actual_types,
1684 args,
1685 line,
1686 CallKind::Command,
1687 );
1688 }
1689 _ if args.len() < fixed => self.error(
1690 line,
1691 msg::fmt(
1692 msg::GENERIC_TYPE_MISMATCH,
1693 &[
1694 &format!("{} arg(s)", args.len()),
1695 &format!("{fixed} arg(s)"),
1696 ],
1697 ),
1698 ),
1699 _ => {}
1700 }
1701 }
1702
1703 fn check_call_arguments(
1704 &mut self,
1705 name: &str,
1706 expected_types: &[Type],
1707 actual_types: &[Option<Type>],
1708 args: &[Expr],
1709 line: usize,
1710 kind: CallKind,
1711 ) {
1712 if args.len() == expected_types.len() {
1713 for (arg, expected) in args.iter().zip(expected_types) {
1714 self.warn_if_int_for_boolean(arg, *expected, line);
1715 }
1716 }
1717 if self.stack_arguments(name, kind) {
1718 if matches!(kind, CallKind::Command)
1719 && self.registry.component_first_command(name)
1720 && let Some((arg, ty)) = args.first().zip(actual_types.first())
1721 && self.expand_call_types(from_ref(arg), from_ref(ty)).len() > 1
1722 {
1723 self.error(
1724 line,
1725 format!("{name}: pass the component as a separate first argument"),
1726 );
1727 }
1728 let actual_types = self.expand_call_types(args, actual_types);
1729 let actual = actual_types.into_iter().flatten().collect::<Vec<_>>();
1730 if actual.len() != expected_types.len() {
1731 self.error(
1732 line,
1733 format!(
1734 "{name} expects {} values, got {}",
1735 expected_types.len(),
1736 actual.len()
1737 ),
1738 );
1739 }
1740 for (index, (&actual, &expected)) in actual.iter().zip(expected_types).enumerate() {
1741 if !Self::stack_types_compatible(actual, expected) {
1742 self.error(
1743 line,
1744 format!(
1745 "{name} argument {}: expected {}, got {}",
1746 index + 1,
1747 expected.name(),
1748 actual.name()
1749 ),
1750 );
1751 }
1752 }
1753 return;
1754 }
1755 if expected_types.is_empty() {
1757 if kind == CallKind::Command {
1758 return;
1759 }
1760 let is_single_null = args.len() == 1 && matches!(&args[0], Expr::NullLiteral);
1762 if !actual_types.is_empty() && !is_single_null {
1763 let actual_desc = actual_types
1764 .iter()
1765 .map(|t| t.map_or("unknown".to_string(), |t| t.name().to_string()))
1766 .collect::<Vec<_>>()
1767 .join(", ");
1768 let template = match kind {
1769 CallKind::Proc => msg::PROC_NOARGS_EXPECTED,
1770 CallKind::Jump => msg::JUMP_NOARGS_EXPECTED,
1771 CallKind::Command => msg::COMMAND_NOARGS_EXPECTED,
1772 };
1773 self.error(line, msg::fmt(template, &[name, &actual_desc]));
1774 }
1775 return;
1776 }
1777
1778 let (actual_types, counted) = match self.call_values(args, actual_types) {
1781 Some(values) => (values, true),
1782 None => (actual_types.to_vec(), false),
1783 };
1784 if expected_types.len() != actual_types.len() {
1785 if !counted
1787 || kind == CallKind::Command
1788 && matches!(
1789 name.trim_start_matches('.'),
1790 "db_find"
1791 | "db_find_refine"
1792 | "db_find_with_count"
1793 | "db_find_refine_with_count"
1794 | "db_findbyindex"
1795 )
1796 {
1797 return;
1798 }
1799 self.error(
1800 line,
1801 msg::fmt(
1802 msg::GENERIC_TYPE_MISMATCH,
1803 &[
1804 &format!("{} arg(s)", actual_types.len()),
1805 &format!("{} arg(s)", expected_types.len()),
1806 ],
1807 ),
1808 );
1809 return;
1810 }
1811
1812 for (i, (expected, actual)) in expected_types.iter().zip(actual_types.iter()).enumerate() {
1813 if let Some(actual_ty) = actual
1814 && !self.types_compatible(*actual_ty, *expected)
1815 {
1816 self.error(
1817 line,
1818 msg::fmt(
1819 msg::GENERIC_TYPE_MISMATCH,
1820 &[actual_ty.name(), expected.name()],
1821 ),
1822 );
1823 let _ = i;
1824 }
1825 }
1826 }
1827
1828 fn is_constant_expression(&self, expr: &Expr) -> bool {
1831 match expr {
1832 Expr::IntLiteral(_)
1833 | Expr::LongLiteral(_)
1834 | Expr::StringLiteral(_)
1835 | Expr::BoolLiteral(_)
1836 | Expr::NullLiteral
1837 | Expr::CharLiteral(_)
1838 | Expr::CoordLiteral(_) => true,
1839 Expr::ConstantVar(..) => true,
1840 Expr::Identifier(name) => {
1841 self.registry.lookup_constant(name).is_some()
1842 || self.registry.lookup_entity_id(name).is_some()
1843 || self.registry.type_chars.contains_key(name)
1844 || name.contains(':') && {
1846 let parts: Vec<&str> = name.splitn(2, ':').collect();
1847 parts.len() == 2
1848 && self
1849 .registry
1850 .lookup_component(parts[0], parts[1])
1851 .is_some()
1852 }
1853 }
1854 Expr::BinaryOp {
1857 op: BinOp::Add,
1858 lhs,
1859 rhs,
1860 } => {
1861 if let (Expr::Identifier(l), Expr::Identifier(r)) = (lhs.as_ref(), rhs.as_ref()) {
1862 let combined = format!("{}+{}", l, r);
1863 self.registry.lookup_entity_id(&combined).is_some()
1864 } else {
1865 false
1866 }
1867 }
1868 _ => false,
1869 }
1870 }
1871
1872 fn expression_has_side_effects(&self, expr: &Expr) -> bool {
1875 match expr {
1876 Expr::CommandCall { .. } | Expr::ProcCall { .. } | Expr::JumpCall { .. } => true,
1877 Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
1878 self.expression_has_side_effects(lhs) || self.expression_has_side_effects(rhs)
1879 }
1880 Expr::Calc(inner) => self.expression_has_side_effects(inner),
1881 Expr::JoinedString { parts } => parts.iter().any(|p| {
1882 if let StringPart::Expr(e) = p {
1883 self.expression_has_side_effects(e)
1884 } else {
1885 false
1886 }
1887 }),
1888 _ => false,
1889 }
1890 }
1891
1892 fn stack_types_compatible(actual: Type, expected: Type) -> bool {
1896 actual == expected
1897 || matches!(actual, Type::Any | Type::Error)
1898 || matches!(expected, Type::Any | Type::Error)
1899 || (actual == Type::Int && expected.base_type() == BaseVarType::Integer)
1900 || (expected == Type::Int && actual.base_type() == BaseVarType::Integer)
1901 || matches!(
1902 (actual, expected),
1903 (Type::Obj, Type::NamedObj)
1904 | (Type::NamedObj, Type::Obj)
1905 | (Type::Boolean, Type::IntBool)
1906 | (Type::IntBool, Type::Boolean)
1907 | (Type::Long, Type::ClanForumQfc)
1908 | (Type::ClanForumQfc, Type::Long)
1909 )
1910 }
1911
1912 fn types_compatible(&self, actual: Type, expected: Type) -> bool {
1913 if expected == Type::Any {
1915 return true;
1916 }
1917 if expected == Type::Error || actual == Type::Error {
1919 return true;
1920 }
1921 if actual == expected {
1923 return true;
1924 }
1925 if (expected == Type::Obj && actual == Type::NamedObj)
1927 || (expected == Type::NamedObj && actual == Type::Obj)
1928 {
1929 return true;
1930 }
1931 if actual == Type::Any {
1933 return true;
1934 }
1935 if actual == Type::Int && expected.base_type() == BaseVarType::Integer {
1941 return true;
1942 }
1943 if matches!(actual, Type::Boolean | Type::Obj) && expected == Type::Int {
1947 return true;
1948 }
1949 if !self.current_script_is_test
1959 && actual.base_type() == BaseVarType::Integer
1960 && expected.base_type() == BaseVarType::Integer
1961 {
1962 return true;
1963 }
1964 false
1965 }
1966
1967 fn warn_if_int_for_boolean(&mut self, expr: &Expr, expected: Type, line: usize) {
1970 if expected != Type::Boolean {
1971 return;
1972 }
1973 let (shown, value) = match expr {
1974 Expr::IntLiteral(value) => (format!("`{value}` is an int"), *value),
1975 Expr::ConstantVar(name, _) => match self
1976 .registry
1977 .lookup_constant(name)
1978 .map(|symbol| &symbol.kind)
1979 {
1980 Some(SymbolKind::Constant {
1981 const_type,
1982 int_value: Some(value),
1983 ..
1984 }) if *const_type != Type::Boolean => {
1985 (format!("`^{name}` is an int constant"), *value)
1986 }
1987 _ => return,
1988 },
1989 _ => return,
1990 };
1991 let takes = match value {
1992 0 => "`false`",
1993 1 => "`true`",
1994 _ => "`true` or `false`",
1995 };
1996 self.warning(line, format!("{shown}; a boolean takes {takes}"));
1997 }
1998
1999 fn warn_if_bare_command_value(&mut self, expr: &Expr, line: usize) -> bool {
2007 if let Expr::Identifier(name) = expr {
2008 let requires_args = self
2009 .registry
2010 .command_param_types
2011 .get(name)
2012 .is_some_and(|p| !p.is_empty());
2013 if requires_args && self.registry.lookup_command(name).is_some() {
2016 self.warning(
2017 line,
2018 msg::fmt(msg::COMMAND_BARE_REQUIRES_ARGS, &[name, name]),
2019 );
2020 return true;
2021 }
2022 }
2023 false
2024 }
2025
2026 fn emit_type_mismatch(&mut self, line: usize, actual: Type, expected: Type) {
2029 self.error(
2030 line,
2031 msg::fmt(
2032 msg::GENERIC_TYPE_MISMATCH,
2033 &[actual.name(), expected.name()],
2034 ),
2035 );
2036 }
2037
2038 fn error(&mut self, line: usize, message: String) {
2039 self.diagnostics.error(
2040 self.file_path.clone(),
2041 line,
2042 0,
2043 message,
2044 Phase::TypeChecking,
2045 );
2046 }
2047
2048 fn warning(&mut self, line: usize, message: String) {
2049 self.diagnostics.warning(
2050 self.file_path.clone(),
2051 line,
2052 0,
2053 message,
2054 Phase::TypeChecking,
2055 );
2056 }
2057
2058 fn warning_with_help(&mut self, line: usize, message: String, help: crate::diagnostics::Help) {
2061 use crate::diagnostics::{Diagnostic, Severity};
2062 self.diagnostics.add(Diagnostic {
2063 file: self.file_path.clone(),
2064 line,
2065 column: 0,
2066 message,
2067 severity: Severity::Warning,
2068 phase: Phase::TypeChecking,
2069 help: vec![help],
2070 });
2071 }
2072
2073 fn emit_unresolved_entity_warning(&mut self, line: usize, name: &str, expected: Type) {
2076 use crate::diagnostics::{Applicability, Help};
2077
2078 let message = msg::fmt(msg::UNRESOLVED_ENTITY_REF, &[name, expected.name()]);
2079
2080 let near = self.near_entity_names(name, expected, 2, 3);
2081 let help_message = if near.is_empty() {
2082 format!(
2083 "Check the `{}` pack/registry for the canonical name, or remove \
2084 the reference if it's stale.",
2085 expected.name()
2086 )
2087 } else {
2088 let suggestions = near
2089 .iter()
2090 .map(|n| format!("`{}`", n))
2091 .collect::<Vec<_>>()
2092 .join(", ");
2093 format!("Did you mean one of: {}?", suggestions)
2094 };
2095
2096 self.warning_with_help(
2097 line,
2098 message,
2099 Help {
2100 message: help_message,
2101 suggestions: Vec::new(),
2102 applicability: Applicability::MaybeIncorrect,
2103 },
2104 );
2105 }
2106
2107 fn emit_prefer_bare_ident_warning(&mut self, line: usize, name: &str, expected: Type) {
2109 use crate::diagnostics::{Applicability, Help};
2110
2111 let message = msg::fmt(msg::PREFER_BARE_IDENT, &[name, expected.name()]);
2112 self.warning_with_help(
2113 line,
2114 message,
2115 Help {
2116 message: format!(
2117 "Replace `\"{}\"` with the bare identifier `{}` — same \
2118 resolution, one fewer layer of indirection.",
2119 name, name
2120 ),
2121 suggestions: Vec::new(),
2122 applicability: Applicability::MachineApplicable,
2123 },
2124 );
2125 }
2126
2127 fn near_entity_names(
2136 &self,
2137 name: &str,
2138 expected: Type,
2139 max_edits: usize,
2140 limit: usize,
2141 ) -> Vec<String> {
2142 use std::collections::HashSet;
2143 let target = name.to_lowercase();
2144 let target_len = target.len();
2145 let mut seen: HashSet<String> = HashSet::new();
2146 let mut scored: Vec<(usize, String)> = Vec::new();
2147
2148 let consider =
2149 |cand: &str, scored: &mut Vec<(usize, String)>, seen: &mut HashSet<String>| {
2150 if cand.len().abs_diff(target_len) > max_edits {
2151 return;
2152 }
2153 let key = cand.to_lowercase();
2154 if !seen.insert(key.clone()) {
2155 return;
2156 }
2157 let d = levenshtein_bounded(&target, &key, max_edits);
2158 if d == 0 || d > max_edits {
2159 return;
2160 }
2161 scored.push((d, cand.to_string()));
2162 };
2163
2164 for (cand, entry) in self.registry.entity_ids.iter() {
2165 if entry.variants.iter().any(|(t, _)| *t == expected) {
2166 consider(cand, &mut scored, &mut seen);
2167 }
2168 }
2169 for (cand, entry) in self.registry.entity_ids.iter() {
2170 if entry.primary.is_some() {
2171 consider(cand, &mut scored, &mut seen);
2172 }
2173 }
2174
2175 scored.sort_by_key(|(d, _)| *d);
2176 scored.into_iter().take(limit).map(|(_, n)| n).collect()
2177 }
2178}
2179
2180fn levenshtein_bounded(a: &str, b: &str, max: usize) -> usize {
2184 let a: Vec<char> = a.chars().collect();
2185 let b: Vec<char> = b.chars().collect();
2186 let (n, m) = (a.len(), b.len());
2187 if n.abs_diff(m) > max {
2188 return max + 1;
2189 }
2190 if n == 0 {
2191 return m;
2192 }
2193 if m == 0 {
2194 return n;
2195 }
2196 let mut prev: Vec<usize> = (0..=m).collect();
2197 let mut curr = vec![0usize; m + 1];
2198 for i in 1..=n {
2199 curr[0] = i;
2200 let mut row_min = curr[0];
2201 for j in 1..=m {
2202 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
2203 curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
2204 row_min = row_min.min(curr[j]);
2205 }
2206 if row_min > max {
2207 return max + 1;
2208 }
2209 std::mem::swap(&mut prev, &mut curr);
2210 }
2211 prev[m]
2212}
2213
2214fn is_valid_bare_ident(name: &str) -> bool {
2219 let mut chars = name.chars();
2220 match chars.next() {
2221 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
2222 _ => return false,
2223 }
2224 name.chars()
2225 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '+')
2226}
2227
2228#[derive(Debug, Clone, Copy, PartialEq)]
2229enum CallKind {
2230 Command,
2231 Proc,
2232 Jump,
2233}