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