1use crate::bytecode::*;
2use crate::parser::*;
3use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
4use crate::types::{BaseVarType, Type};
5
6pub struct Compiler<'a> {
8 pub registry: &'a SymbolRegistry,
11 current_return_types: Vec<Type>,
13 current_stmt_line: usize,
15}
16
17impl<'a> Compiler<'a> {
18 pub fn new(registry: &'a SymbolRegistry) -> Self {
19 Compiler {
20 registry,
21 current_return_types: Vec::new(),
22 current_stmt_line: 0,
23 }
24 }
25
26 pub fn compile_script(&mut self, script: &ScriptDeclaration) -> CompiledScript {
28 let id = self
29 .registry
30 .script_id_for_trigger(&script.trigger, &script.name)
31 .or_else(|| self.registry.script_id(&script.name))
32 .unwrap_or(-1);
33 let full_name = format!("[{},{}]", script.trigger, script.name);
34 let mut compiled = CompiledScript::new(full_name, id);
35 compiled.trigger = script.trigger.clone();
36 compiled.lookup_key =
37 Self::compute_lookup_key(&script.trigger, &script.name, self.registry);
38 compiled.param_types = script.params.iter().map(|p| p.param_type).collect();
39 let mut locals = SymbolTable::new();
40
41 for param in &script.params {
43 let slot = compiled
44 .local_table
45 .push_param(param.name.clone(), param.param_type);
46 locals.define(
47 param.name.clone(),
48 SymbolKind::ScriptParam {
49 param_type: param.param_type,
50 slot,
51 },
52 );
53 }
54
55 self.current_return_types = script.return_types.clone();
57 for stmt in &script.body {
58 self.compile_statement(stmt, &mut compiled, &mut locals);
59 }
60
61 for ret_type in &script.return_types {
63 match ret_type.base_type() {
64 BaseVarType::Integer => {
65 compiled.push(Instruction::push_int(ret_type.default_return_value()))
66 }
67 BaseVarType::String => compiled.push(Instruction::push_string(String::new())),
68 BaseVarType::Long => compiled.push(Instruction::push_long(0)),
69 }
70 }
71 compiled.push(Instruction::simple(Opcode::Return));
72
73 compiled.int_local_count = compiled.local_table.get_local_count(BaseVarType::Integer);
75 compiled.string_local_count = compiled.local_table.get_local_count(BaseVarType::String);
76 compiled.long_local_count = compiled.local_table.get_local_count(BaseVarType::Long);
77 compiled.int_arg_count = compiled.local_table.get_param_count(BaseVarType::Integer);
78 compiled.string_arg_count = compiled.local_table.get_param_count(BaseVarType::String);
79 compiled.long_arg_count = compiled.local_table.get_param_count(BaseVarType::Long);
80
81 compiled
82 }
83
84 fn emit_line(line: usize, out: &mut CompiledScript) {
85 out.push(Instruction::new(
86 Opcode::LineNumber,
87 Operand::Int(line as i32),
88 ));
89 }
90
91 fn emit_comparison_value(
92 branch_opcode: Opcode,
93 fallthrough_value: i32,
94 branch_value: i32,
95 out: &mut CompiledScript,
96 ) {
97 let branch_pos = out.len();
98 out.push(Instruction::new(branch_opcode, Operand::JumpTarget(0)));
99 out.push(Instruction::push_int(fallthrough_value));
100 let jump_pos = out.len();
101 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
102 let branch_target = out.len();
103 out.push(Instruction::push_int(branch_value));
104 let end_pos = out.len();
105 out.patch_jump(branch_pos, branch_target);
106 out.patch_jump(jump_pos, end_pos);
107 }
108
109 fn compile_statement(
110 &mut self,
111 stmt: &Statement,
112 out: &mut CompiledScript,
113 locals: &mut SymbolTable,
114 ) {
115 match stmt {
117 Statement::VarDeclaration { line, .. }
118 | Statement::ArrayDeclaration { line, .. }
119 | Statement::Assignment { line, .. }
120 | Statement::If { line, .. }
121 | Statement::While { line, .. }
122 | Statement::Switch { line, .. }
123 | Statement::Return { line, .. }
124 | Statement::Expression { line, .. }
125 | Statement::OrphanCase { line, .. } => {
126 self.current_stmt_line = *line;
127 }
128 Statement::Empty => {}
129 }
130 match stmt {
131 Statement::VarDeclaration {
132 var_type,
133 name,
134 value,
135 line,
136 } => {
137 let slot = out.local_table.push_local(name.clone(), *var_type, false);
139 locals.define(
141 name.clone(),
142 SymbolKind::LocalVar {
143 var_type: *var_type,
144 slot,
145 is_array: false,
146 },
147 );
148
149 if let Some(init) = value {
150 Self::emit_line(*line, out);
154 self.compile_expr_hinted(init, out, locals, Some(*var_type));
157 Self::emit_line(*line, out);
161 } else {
162 match var_type.base_type() {
164 BaseVarType::Integer => {
165 out.push(Instruction::push_int(var_type.default_int_value()))
166 }
167 BaseVarType::String => out.push(Instruction::push_string(String::new())),
168 BaseVarType::Long => out.push(Instruction::push_long(0)),
169 }
170 Self::emit_line(*line, out);
171 }
172
173 let pop_opcode = match var_type.base_type() {
175 BaseVarType::Integer => Opcode::PopIntLocal,
176 BaseVarType::String => Opcode::PopStringLocal,
177 BaseVarType::Long => Opcode::PopLongLocal,
178 };
179 out.push(Instruction::new(pop_opcode, Operand::Int(slot)));
180 }
181
182 Statement::ArrayDeclaration {
183 element_type,
184 name,
185 size,
186 line,
187 } => {
188 Self::emit_line(*line, out);
189 let slot = out
190 .local_table
191 .push_local(name.clone(), *element_type, true);
192 locals.define(
193 name.clone(),
194 SymbolKind::LocalVar {
195 var_type: *element_type,
196 slot,
197 is_array: true,
198 },
199 );
200
201 self.compile_expr(size, out, locals);
203 out.push(Instruction::pop_int_local(slot));
204
205 let type_char = match element_type.base_type() {
207 BaseVarType::Integer => b'i',
208 BaseVarType::String => b's',
209 BaseVarType::Long => b'l',
210 };
211 out.push(Instruction::new(
212 Opcode::DefineArray,
213 Operand::ArrayDef(slot, type_char),
214 ));
215
216 let _ = line;
217 }
218
219 Statement::Assignment {
220 target,
221 value,
222 line,
223 } => {
224 Self::emit_line(*line, out);
225 let target_type_hint = self.infer_target_type(target, locals);
227 self.compile_expr_hinted(value, out, locals, target_type_hint);
228 self.compile_store(target, out, locals);
229 }
230
231 Statement::If {
232 condition,
233 body,
234 else_if,
235 else_body,
236 else_line,
237 line,
238 } => {
239 Self::emit_line(*line, out);
240 self.compile_if(condition, body, else_if, else_body, *else_line, out, locals);
241 }
242
243 Statement::While {
244 condition,
245 body,
246 line,
247 } => {
248 Self::emit_line(*line, out);
249 let loop_start = out.len();
250
251 let (true_positions, false_positions) =
253 self.compile_condition(condition, out, locals);
254
255 let body_start = out.len();
257 for pos in &true_positions {
258 out.patch_jump(*pos, body_start);
259 }
260
261 for s in body {
263 self.compile_statement(s, out, locals);
264 }
265
266 out.push(Instruction::new(
268 Opcode::Branch,
269 Operand::JumpTarget(loop_start),
270 ));
271
272 let exit_pos = out.len();
274 for pos in &false_positions {
275 out.patch_jump(*pos, exit_pos);
276 }
277 }
278
279 Statement::Switch {
280 switch_type,
281 expr,
282 cases,
283 default,
284 default_index,
285 line,
286 } => {
287 Self::emit_line(*line, out);
288 self.compile_switch(
289 switch_type,
290 expr,
291 cases,
292 default,
293 *default_index,
294 out,
295 locals,
296 );
297 }
298
299 Statement::Return { values, line } => {
300 Self::emit_line(*line, out);
301 let return_types = self.current_return_types.clone();
302 for (i, val) in values.iter().enumerate() {
303 let hint = return_types.get(i).copied();
304 self.compile_expr_hinted(val, out, locals, hint);
305 }
306 out.push(Instruction::simple(Opcode::Return));
307 }
308
309 Statement::Expression { expr, line } => {
310 let cmd_args_offset = if let Expr::CommandCall { name, args, .. } = expr {
313 let n = self.count_pre_stmt_string_args(name, args);
314 if n > 0 {
315 let first_is_const = matches!(&args[0], Expr::ConstantVar(..));
320 if first_is_const && *line > 1 {
321 Self::emit_line(*line - 1, out);
322 }
323 let lookup = name.strip_prefix('.').unwrap_or(name);
324 let ptypes: Vec<Type> = self
325 .registry
326 .command_param_types
327 .get(lookup)
328 .cloned()
329 .unwrap_or_default();
330 for (j, arg) in args[..n].iter().enumerate() {
331 let hint = ptypes.get(j).copied();
332 self.compile_expr_hinted(arg, out, locals, hint);
333 }
334 }
335 n
336 } else {
337 0
338 };
339 Self::emit_line(*line, out);
340 if cmd_args_offset > 0 {
341 if let Expr::CommandCall {
342 name,
343 args,
344 arg_lines,
345 call_line: _,
346 } = expr
347 {
348 self.compile_command_call_args_from(
349 name,
350 args,
351 arg_lines,
352 cmd_args_offset,
353 out,
354 locals,
355 );
356 }
357 } else {
358 self.compile_expr(expr, out, locals);
359 }
360 let return_types: Option<Vec<crate::types::Type>> = match expr {
363 Expr::ProcCall { name, .. } => {
364 self.registry.scripts.get(name.as_str()).and_then(|sym| {
365 if let SymbolKind::Script { return_types, .. } = &sym.kind {
366 Some(return_types.clone())
367 } else {
368 None
369 }
370 })
371 }
372 Expr::JumpCall { name, .. } => {
373 self.registry.scripts.get(name.as_str()).and_then(|sym| {
374 if let SymbolKind::Script { return_types, .. } = &sym.kind {
375 Some(return_types.clone())
376 } else {
377 None
378 }
379 })
380 }
381 Expr::CommandCall { name, .. } => {
382 let lookup_name = name.strip_prefix('.').unwrap_or(name);
384 self.registry.commands.get(lookup_name).and_then(|sym| {
385 if let SymbolKind::Command { return_types, .. } = &sym.kind {
386 if return_types.is_empty() {
387 None
388 } else {
389 Some(return_types.clone())
390 }
391 } else {
392 None
393 }
394 })
395 }
396 _ => None,
397 };
398 if let Some(ret_types) = return_types {
399 for ret_type in &ret_types {
400 match ret_type.base_type() {
401 BaseVarType::Integer => {
402 out.push(Instruction::simple(Opcode::PopIntDiscard))
403 }
404 BaseVarType::String => {
405 out.push(Instruction::simple(Opcode::PopStringDiscard))
406 }
407 BaseVarType::Long => {
408 out.push(Instruction::simple(Opcode::PopLongDiscard))
409 }
410 }
411 }
412 }
413 }
414 Statement::OrphanCase { .. } => {}
415 Statement::Empty => {}
416 }
417 }
418
419 #[allow(clippy::too_many_arguments, clippy::only_used_in_recursion)]
420 fn compile_if(
421 &mut self,
422 condition: &Expr,
423 body: &[Statement],
424 else_if: &[(Expr, Vec<Statement>, usize)],
425 else_body: &Option<Vec<Statement>>,
426 else_line: usize,
427 out: &mut CompiledScript,
428 locals: &mut SymbolTable,
429 ) {
430 let mut end_jumps = Vec::new();
431
432 let (true_positions, false_positions) = self.compile_condition(condition, out, locals);
434
435 let body_start = out.len();
437 for pos in &true_positions {
438 out.patch_jump(*pos, body_start);
439 }
440
441 for s in body {
443 self.compile_statement(s, out, locals);
444 }
445
446 let end_jump_pos = out.len();
448 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
449 end_jumps.push(end_jump_pos);
450
451 let else_start = out.len();
453 for pos in &false_positions {
454 out.patch_jump(*pos, else_start);
455 }
456
457 if !else_if.is_empty() {
458 let (first_cond, first_body, first_line) = &else_if[0];
461 let remaining = &else_if[1..];
462 Self::emit_line(*first_line, out);
464 self.compile_if(
465 first_cond, first_body, remaining, else_body, else_line, out, locals,
466 );
467
468 let wrapper_jump = out.len();
470 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
471 end_jumps.push(wrapper_jump);
472 } else if let Some(else_stmts) = else_body {
473 for s in else_stmts {
475 self.compile_statement(s, out, locals);
476 }
477 let end_jump_pos = out.len();
479 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
480 end_jumps.push(end_jump_pos);
481 }
482
483 let end_pos = out.len();
485 for pos in end_jumps {
486 out.patch_jump(pos, end_pos);
487 }
488 }
489
490 fn count_pre_stmt_string_args(&self, name: &str, args: &[Expr]) -> usize {
495 let lookup_name = name.strip_prefix('.').unwrap_or(name);
497 let param_types: Vec<Type> = self
498 .registry
499 .command_param_types
500 .get(lookup_name)
501 .cloned()
502 .unwrap_or_default();
503
504 let mut count = 0;
505 for (i, arg) in args.iter().enumerate() {
506 let is_string_param = param_types
507 .get(i)
508 .map(|t| t.base_type() == crate::types::BaseVarType::String)
509 .unwrap_or(false);
510
511 match arg {
512 Expr::ConstantVar(cname, _) => {
513 if let Some(sym) = self.registry.lookup_constant(cname)
514 && let SymbolKind::Constant {
515 string_value: Some(_),
516 ..
517 } = &sym.kind
518 {
519 count += 1;
520 continue;
521 }
522 break;
523 }
524 Expr::NullLiteral if is_string_param => {
525 count += 1;
526 continue;
527 }
528 _ => break,
529 }
530 }
531 count
532 }
533
534 fn try_emit_test_command_id_arg(
543 &self,
544 lookup_name: &str,
545 arg: &Expr,
546 hint: Option<Type>,
547 out: &mut CompiledScript,
548 ) -> bool {
549 if !matches!(lookup_name, "test_op" | "wait_for") || hint != Some(Type::Int) {
550 return false;
551 }
552 let Expr::Identifier(ident) = arg else {
553 return false;
554 };
555 if ident.contains(':') {
556 return false;
557 }
558 if let Some(trigger_byte) = crate::trigger_table::byte(ident) {
559 out.push(Instruction::push_int(trigger_byte as i32));
560 return true;
561 }
562 if let Some(sym) = self
563 .registry
564 .lookup_command(ident.strip_prefix('.').unwrap_or(ident))
565 && let SymbolKind::Command { opcode, .. } = &sym.kind
566 {
567 let opcode = *opcode;
568 out.push(Instruction::push_int(opcode));
569 return true;
570 }
571 false
572 }
573
574 fn compile_command_call_args_from(
576 &mut self,
577 name: &str,
578 args: &[Expr],
579 arg_lines: &[usize],
580 args_start: usize,
581 out: &mut CompiledScript,
582 locals: &mut SymbolTable,
583 ) {
584 let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
585 (stripped, 1u8)
586 } else {
587 (name, 0u8)
588 };
589 let param_types: Vec<Type> = self
590 .registry
591 .command_param_types
592 .get(lookup_name)
593 .cloned()
594 .unwrap_or_default();
595 let script_trigger = Self::command_script_trigger(lookup_name);
596 let variadic_info = Self::command_variadic_info(lookup_name);
597
598 for (i, arg) in args.iter().enumerate() {
599 if i < args_start {
600 continue;
601 }
602 if let Some(&al) = arg_lines.get(i)
603 && al > 0
604 {
605 Self::emit_line(al, out);
606 }
607 if i == 0
608 && let Some(trigger) = script_trigger
609 && let Expr::Identifier(script_name) = arg
610 {
611 let script_id = self
612 .registry
613 .script_id_for_trigger(trigger, script_name)
614 .or_else(|| self.registry.proc_script_id(script_name))
615 .or_else(|| self.registry.script_id(script_name))
616 .unwrap_or(-1);
617 out.push(Instruction::push_int(script_id));
618 continue;
619 }
620 let hint = param_types.get(i).copied();
621 if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
622 continue;
623 }
624 self.compile_expr_hinted(arg, out, locals, hint);
625 }
626
627 if let Some(fixed_arg_count) = variadic_info {
628 let variadic_args = if args.len() > fixed_arg_count {
629 &args[fixed_arg_count..]
630 } else {
631 &[]
632 };
633 let type_desc: String = variadic_args
634 .iter()
635 .map(|arg| self.infer_type_char(arg, locals))
636 .collect();
637 out.push(Instruction::push_string(type_desc));
638 }
639
640 let cmd_sym = self
641 .registry
642 .lookup_command(lookup_name)
643 .or_else(|| {
644 lookup_name.strip_suffix('*').and_then(|base| {
645 let vararg_name = format!("{}vararg", base);
646 self.registry.lookup_command(&vararg_name)
647 })
648 })
649 .cloned();
650 if let Some(sym) = cmd_sym {
651 if let SymbolKind::Command { opcode, .. } = &sym.kind {
652 let encoded = opcode | ((cmd_index as i32) << 16);
653 out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
654 }
655 } else {
656 out.push(Instruction::new(
657 Opcode::Command,
658 Operand::Str(name.to_string()),
659 ));
660 }
661 }
662
663 fn compile_condition(
668 &mut self,
669 condition: &Expr,
670 out: &mut CompiledScript,
671 locals: &mut SymbolTable,
672 ) -> (Vec<usize>, Vec<usize>) {
673 match condition {
674 Expr::BinaryOp { op, lhs, rhs } => {
675 let lhs_type_hint = self.infer_type(lhs, locals);
677 self.compile_expr(lhs, out, locals);
678 self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
679
680 let opcode = match op {
682 BinOp::Eq => Opcode::BranchEquals,
683 BinOp::NotEq => Opcode::BranchNot,
684 BinOp::Lt => Opcode::BranchLessThan,
685 BinOp::Gt => Opcode::BranchGreaterThan,
686 BinOp::LtEq => Opcode::BranchLessThanOrEquals,
687 BinOp::GtEq => Opcode::BranchGreaterThanOrEquals,
688 _ => Opcode::BranchNot,
689 };
690 let true_pos = out.len();
691 out.push(Instruction::new(opcode, Operand::JumpTarget(0)));
692
693 let false_pos = out.len();
695 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
696
697 (vec![true_pos], vec![false_pos])
698 }
699
700 Expr::LogicalOp {
701 op,
702 lhs,
703 rhs,
704 rhs_line,
705 } => {
706 match op {
707 LogicOp::And => {
708 let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
710
711 let rhs_start = out.len();
713 for pos in &lhs_true {
714 out.patch_jump(*pos, rhs_start);
715 }
716
717 Self::emit_line(*rhs_line, out);
720 let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
721
722 let mut false_branches = lhs_false;
725 false_branches.extend(rhs_false);
726 (rhs_true, false_branches)
727 }
728 LogicOp::Or => {
729 let (lhs_true, lhs_false) = self.compile_condition(lhs, out, locals);
731
732 let rhs_start = out.len();
734 for pos in &lhs_false {
735 out.patch_jump(*pos, rhs_start);
736 }
737
738 Self::emit_line(*rhs_line, out);
740 let (rhs_true, rhs_false) = self.compile_condition(rhs, out, locals);
741
742 let mut true_branches = lhs_true;
744 true_branches.extend(rhs_true);
745 (true_branches, rhs_false)
746 }
747 }
748 }
749
750 _ => {
752 self.compile_expr(condition, out, locals);
753 out.push(Instruction::push_int(0));
754
755 let true_pos = out.len();
756 out.push(Instruction::new(Opcode::BranchNot, Operand::JumpTarget(0)));
757
758 let false_pos = out.len();
759 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
760
761 (vec![true_pos], vec![false_pos])
762 }
763 }
764 }
765
766 #[allow(clippy::too_many_arguments)]
767 fn compile_switch(
768 &mut self,
769 switch_type: &str,
770 expr: &Expr,
771 cases: &[SwitchCase],
772 default: &Option<Vec<Statement>>,
773 default_index: usize,
774 out: &mut CompiledScript,
775 locals: &mut SymbolTable,
776 ) {
777 self.compile_expr(expr, out, locals);
778 let case_type_hint =
780 Type::from_name(switch_type.strip_prefix("switch_").unwrap_or(switch_type));
781
782 let switch_idx = out.len();
784 out.push(Instruction::new(
785 Opcode::Switch,
786 Operand::SwitchTable(Vec::new()),
787 ));
788
789 let mut end_jumps = Vec::new();
812 let default_first = default_index == 0 && default.is_some();
814
815 let default_branch_pos = if default_first {
816 if let Some(default_stmts) = default {
818 for s in default_stmts {
819 self.compile_statement(s, out, locals);
820 }
821 let jump_pos = out.len();
822 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
823 end_jumps.push(jump_pos);
824 }
825 None
826 } else {
827 let pos = out.len();
829 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
830 Some(pos)
831 };
832
833 let mut case_positions: Vec<(Vec<i32>, usize)> = Vec::new();
835 let mut default_body_pos = 0usize;
836
837 for (i, case) in cases.iter().enumerate() {
838 if !default_first && i == default_index {
840 default_body_pos = out.len();
841 if let Some(default_stmts) = default {
842 for s in default_stmts {
843 self.compile_statement(s, out, locals);
844 }
845 let jump_pos = out.len();
846 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
847 end_jumps.push(jump_pos);
848 }
849 }
850
851 let body_start = out.len();
852 let mut values = Vec::new();
853 for val in &case.values {
854 if let Expr::IntLiteral(n) = val {
855 values.push(*n);
856 } else if let Expr::ConstantVar(cname, _) = val {
857 if let Some(sym) = self.registry.constants.get(cname)
859 && let SymbolKind::Constant {
860 int_value: Some(value),
861 ..
862 } = &sym.kind
863 {
864 values.push(*value);
865 }
866 } else if let Expr::Identifier(ident) = val {
867 let mut resolved = false;
869 if let Some((iface_name, comp_name)) = ident.split_once(':')
870 && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
871 {
872 values.push(packed);
873 resolved = true;
874 }
875 if !resolved
877 && let Some(hint) = case_type_hint
878 && let Some(id) = self.registry.lookup_entity_id_typed(ident, hint)
879 {
880 values.push(id);
881 resolved = true;
882 }
883 if !resolved {
884 if let Some(sym) = self.registry.entity_ids.get(ident.as_str()) {
885 if let SymbolKind::Constant {
886 int_value: Some(value),
887 ..
888 } = &sym.kind
889 {
890 values.push(*value);
891 }
892 } else if let Some(sym) = self.registry.constants.get(ident.as_str())
893 && let SymbolKind::Constant {
894 int_value: Some(value),
895 ..
896 } = &sym.kind
897 {
898 values.push(*value);
899 }
900 }
901 } else if let Expr::BinaryOp {
902 op: BinOp::Add,
903 lhs,
904 rhs,
905 } = val
906 {
907 if let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
909 (lhs.as_ref(), rhs.as_ref())
910 {
911 let combined = format!("{}+{}", lhs_name, rhs_name);
912 if let Some(hint) = case_type_hint {
913 if let Some(id) = self.registry.lookup_entity_id_typed(&combined, hint)
914 {
915 values.push(id);
916 }
917 } else if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
918 && let SymbolKind::Constant {
919 int_value: Some(id),
920 ..
921 } = &sym.kind
922 {
923 values.push(*id);
924 }
925 }
926 } else if let Expr::CoordLiteral(v) = val {
927 values.push(*v);
928 }
929 }
930 case_positions.push((values, body_start));
931
932 for s in &case.body {
933 self.compile_statement(s, out, locals);
934 }
935
936 let jump_pos = out.len();
938 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
939 end_jumps.push(jump_pos);
940 }
941
942 if !default_first && default_index >= cases.len() {
944 default_body_pos = out.len();
945 if let Some(default_stmts) = default {
946 for s in default_stmts {
947 self.compile_statement(s, out, locals);
948 }
949 let jump_pos = out.len();
950 out.push(Instruction::new(Opcode::Branch, Operand::JumpTarget(0)));
951 end_jumps.push(jump_pos);
952 }
953 }
954
955 let end_pos = out.len();
956
957 if let Some(dbp) = default_branch_pos {
959 let default_target = if default.is_some() {
960 default_body_pos
961 } else {
962 end_pos
963 };
964 out.patch_jump(dbp, default_target);
965 }
966
967 let mut table = Vec::new();
969 for (values, pos) in &case_positions {
970 for &v in values {
971 table.push((v, *pos));
972 }
973 }
974
975 out.instructions[switch_idx].operand = Operand::SwitchTable(table);
977
978 for pos in end_jumps {
980 out.patch_jump(pos, end_pos);
981 }
982 }
983
984 fn compile_expr(&mut self, expr: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
985 self.compile_expr_hinted(expr, out, locals, None);
986 }
987
988 fn compile_expr_hinted(
989 &mut self,
990 expr: &Expr,
991 out: &mut CompiledScript,
992 locals: &mut SymbolTable,
993 type_hint: Option<Type>,
994 ) {
995 match expr {
996 Expr::IntLiteral(n) => {
997 out.push(Instruction::push_int(*n));
998 }
999
1000 Expr::LongLiteral(n) => {
1001 out.push(Instruction::push_long(*n));
1002 }
1003
1004 Expr::StringLiteral(s) => {
1005 if let Some(h) = type_hint
1006 && h.base_type() == BaseVarType::Integer
1007 && h != Type::Int
1008 && h != Type::Boolean
1009 {
1010 if let Some(id) = self.registry.lookup_entity_id_typed(s, h) {
1011 out.push(Instruction::push_int(id));
1012 return;
1013 }
1014 if let Some(sym) = self.registry.lookup_entity_id(s)
1015 && let SymbolKind::Constant {
1016 int_value: Some(id),
1017 ..
1018 } = &sym.kind
1019 {
1020 out.push(Instruction::push_int(*id));
1021 return;
1022 }
1023 }
1024 out.push(Instruction::push_string(s.clone()));
1025 }
1026
1027 Expr::BoolLiteral(b) => {
1028 out.push(Instruction::push_int(if *b { 1 } else { 0 }));
1029 }
1030
1031 Expr::NullLiteral => {
1032 if matches!(type_hint, Some(Type::String)) {
1035 out.push(Instruction::push_string("null".to_string()));
1036 } else {
1037 out.push(Instruction::push_int(-1));
1038 }
1039 }
1040
1041 Expr::CharLiteral(c) => {
1042 out.push(Instruction::push_int(*c as i32));
1043 }
1044
1045 Expr::CoordLiteral(c) => {
1046 out.push(Instruction::push_int(*c));
1047 }
1048
1049 Expr::LocalVar(name, _var_line) => {
1050 if let Some(sym) = locals.lookup(name) {
1051 let (slot, base) = match &sym.kind {
1052 SymbolKind::LocalVar { var_type, slot, .. } => {
1053 (*slot, var_type.base_type())
1054 }
1055 SymbolKind::ScriptParam { param_type, slot } => {
1056 (*slot, param_type.base_type())
1057 }
1058 _ => (0, BaseVarType::Integer),
1059 };
1060 let opcode = match base {
1061 BaseVarType::Integer => Opcode::PushIntLocal,
1062 BaseVarType::String => Opcode::PushStringLocal,
1063 BaseVarType::Long => Opcode::PushLongLocal,
1064 };
1065 out.push(Instruction::new(opcode, Operand::Int(slot)));
1066 } else {
1067 out.push(Instruction::push_int(0));
1069 }
1070 }
1071
1072 Expr::GameVar(name, _var_line) => {
1073 let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1076 (stripped, true)
1077 } else {
1078 (name.as_str(), false)
1079 };
1080 if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1081 && let SymbolKind::GameVar {
1082 var_id, category, ..
1083 } = &sym.kind
1084 {
1085 let opcode = match category.as_str() {
1086 "varp" => Opcode::PushVarp,
1087 "varn" => Opcode::PushVarn,
1088 "vars" => Opcode::PushVars,
1089 "varbit" => Opcode::PushVarbit,
1090 _ => Opcode::PushVarp,
1091 };
1092 let encoded_id = if secondary {
1093 (1 << 16) | *var_id
1094 } else {
1095 *var_id
1096 };
1097 out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1098 }
1099 }
1100
1101 Expr::ConstantVar(name, const_line) => {
1102 if let Some(sym) = self.registry.lookup_constant(name).cloned()
1103 && let SymbolKind::Constant {
1104 int_value,
1105 string_value,
1106 ..
1107 } = &sym.kind
1108 {
1109 if let Some(v) = int_value {
1110 out.push(Instruction::push_int(*v));
1111 } else if let Some(s) = string_value {
1112 if *const_line > 0 {
1119 Self::emit_line(*const_line - 1, out);
1120 }
1121 out.push(Instruction::push_string(s.clone()));
1122 }
1123 }
1124 }
1125
1126 Expr::Identifier(name) => {
1127 if let Some((iface_name, comp_name)) = name.split_once(':')
1129 && let Some(packed) = self.registry.lookup_component(iface_name, comp_name)
1130 {
1131 out.push(Instruction::push_int(packed));
1132 return;
1133 }
1134
1135 if let Some(hint) = type_hint {
1147 let trigger_opt: Option<&'static str> = match hint {
1148 Type::Proc => Some("proc"),
1149 Type::Label => Some("label"),
1150 Type::Queue => Some("queue"),
1151 Type::SoftTimer => Some("softtimer"),
1152 Type::Timer => Some("timer"),
1153 Type::Walktrigger => Some("walktrigger"),
1154 _ => None,
1155 };
1156 if let Some(trigger) = trigger_opt {
1157 let script_id = self
1158 .registry
1159 .script_id_for_trigger(trigger, name)
1160 .or_else(|| self.registry.proc_script_id(name))
1161 .or_else(|| self.registry.script_id(name))
1162 .unwrap_or(-1);
1163 out.push(Instruction::push_int(script_id));
1164 return;
1165 }
1166 if let Some(id) = self.registry.lookup_entity_id_typed(name, hint) {
1167 out.push(Instruction::push_int(id));
1168 return;
1169 }
1170 }
1171 if let Some(sym) = self.registry.lookup_entity_id(name).cloned()
1172 && let SymbolKind::Constant {
1173 const_type,
1174 int_value,
1175 string_value,
1176 } = &sym.kind
1177 {
1178 let skip_for_type_char = *const_type == Type::Param
1182 && type_hint != Some(Type::Param)
1183 && self.registry.type_chars.contains_key(name);
1184 if !skip_for_type_char {
1185 if let Some(v) = int_value {
1186 out.push(Instruction::push_int(*v));
1187 } else if let Some(s) = string_value {
1188 out.push(Instruction::push_string(s.clone()));
1189 }
1190 return;
1192 }
1193 }
1194 if let Some(sym) = self.registry.lookup_constant(name).cloned() {
1206 if let SymbolKind::Constant {
1207 int_value,
1208 string_value,
1209 ..
1210 } = &sym.kind
1211 {
1212 if let Some(v) = int_value {
1213 out.push(Instruction::push_int(*v));
1214 } else if let Some(s) = string_value {
1215 out.push(Instruction::push_string(s.clone()));
1216 }
1217 }
1218 } else {
1219 let (lookup, idx) = if let Some(stripped) = name.strip_prefix('.') {
1220 (stripped, 1u8)
1221 } else {
1222 (name.as_str(), 0u8)
1223 };
1224 let resolved = if let Some(sym) = self.registry.lookup_command(lookup).cloned()
1225 {
1226 if let SymbolKind::Command { opcode, .. } = &sym.kind {
1227 let encoded = opcode | ((idx as i32) << 16);
1228 out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1229 }
1230 true
1231 } else {
1232 false
1233 };
1234 if !resolved {
1235 if let Some(sym) = self.registry.lookup_game_var(name).cloned()
1236 && let SymbolKind::GameVar {
1237 var_id, category, ..
1238 } = &sym.kind
1239 {
1240 let push_op = match category.as_str() {
1241 "varp" => Opcode::PushVarp,
1242 "varn" => Opcode::PushVarn,
1243 "vars" => Opcode::PushVars,
1244 "varbit" => Opcode::PushVarbit,
1245 _ => Opcode::PushVarp,
1246 };
1247 out.push(Instruction::new(push_op, Operand::Int(*var_id)));
1248 } else if let Some(&type_char) = self.registry.type_chars.get(name) {
1249 out.push(Instruction::push_int(type_char));
1250 } else if let Some(script_id) = self
1251 .registry
1252 .proc_script_id(name)
1253 .or_else(|| self.registry.script_id(name))
1254 {
1255 out.push(Instruction::push_int(script_id));
1256 } else {
1257 out.push(Instruction::push_int(-1));
1258 }
1259 }
1260 }
1261 }
1262
1263 Expr::ArrayAccess { name, index } => {
1264 self.compile_expr(index, out, locals);
1266
1267 if let Some(sym) = locals.lookup(name) {
1269 let slot = match &sym.kind {
1270 SymbolKind::LocalVar { slot, .. } => *slot,
1271 _ => 0,
1272 };
1273 out.push(Instruction::new(Opcode::PushArrayInt, Operand::Int(slot)));
1274 }
1275 }
1276
1277 Expr::BinaryOp { op, lhs, rhs } => {
1278 if matches!(op, BinOp::Add)
1282 && let (Expr::Identifier(lhs_name), Expr::Identifier(rhs_name)) =
1283 (lhs.as_ref(), rhs.as_ref())
1284 {
1285 let combined = format!("{}+{}", lhs_name, rhs_name);
1286 if let Some(sym) = self.registry.lookup_entity_id(&combined).cloned()
1287 && let SymbolKind::Constant {
1288 int_value: Some(id),
1289 ..
1290 } = &sym.kind
1291 {
1292 out.push(Instruction::push_int(*id));
1293 return;
1294 }
1295 }
1296
1297 let lhs_type_hint = match op {
1301 BinOp::Eq
1302 | BinOp::NotEq
1303 | BinOp::Lt
1304 | BinOp::Gt
1305 | BinOp::LtEq
1306 | BinOp::GtEq => self.infer_type(lhs, locals),
1307 _ => None,
1308 };
1309 self.compile_expr(lhs, out, locals);
1310 self.compile_expr_hinted(rhs, out, locals, lhs_type_hint);
1311
1312 let opcode = match op {
1315 BinOp::Add => Opcode::Add,
1316 BinOp::Sub => Opcode::Sub,
1317 BinOp::Mul => Opcode::Multiply,
1318 BinOp::Div => Opcode::Divide,
1319 BinOp::Mod => Opcode::Modulo,
1320 BinOp::BitAnd => Opcode::And,
1321 BinOp::BitOr => Opcode::Or,
1322 BinOp::Eq => {
1323 Self::emit_comparison_value(Opcode::BranchEquals, 0, 1, out);
1324 return;
1325 }
1326 BinOp::NotEq => {
1327 Self::emit_comparison_value(Opcode::BranchEquals, 1, 0, out);
1328 return;
1329 }
1330 BinOp::Lt => {
1331 Self::emit_comparison_value(Opcode::BranchLessThan, 0, 1, out);
1332 return;
1333 }
1334 BinOp::Gt => {
1335 Self::emit_comparison_value(Opcode::BranchGreaterThan, 0, 1, out);
1336 return;
1337 }
1338 BinOp::LtEq => {
1339 Self::emit_comparison_value(Opcode::BranchLessThanOrEquals, 0, 1, out);
1340 return;
1341 }
1342 BinOp::GtEq => {
1343 Self::emit_comparison_value(Opcode::BranchGreaterThanOrEquals, 0, 1, out);
1344 return;
1345 }
1346 };
1347 out.push(Instruction::simple(opcode));
1348 }
1349
1350 Expr::LogicalOp { op, lhs, rhs, .. } => {
1351 self.compile_expr(lhs, out, locals);
1352 self.compile_expr(rhs, out, locals);
1353 match op {
1354 LogicOp::And => out.push(Instruction::simple(Opcode::And)),
1355 LogicOp::Or => out.push(Instruction::simple(Opcode::Or)),
1356 }
1357 }
1358
1359 Expr::Calc(inner) => {
1360 self.compile_expr(inner, out, locals);
1361 }
1362
1363 Expr::CommandCall {
1364 name,
1365 args,
1366 arg_lines,
1367 call_line,
1368 } => {
1369 let (lookup_name, cmd_index) = if let Some(stripped) = name.strip_prefix('.') {
1371 (stripped, 1u8)
1372 } else {
1373 (name.as_str(), 0u8)
1374 };
1375
1376 let param_types: Vec<Type> = self
1378 .registry
1379 .command_param_types
1380 .get(lookup_name)
1381 .cloned()
1382 .unwrap_or_default();
1383
1384 let script_trigger = Self::command_script_trigger(lookup_name);
1387 let variadic_info = Self::command_variadic_info(lookup_name);
1388
1389 for (i, arg) in args.iter().enumerate() {
1391 if let Some(&al) = arg_lines.get(i)
1393 && al > 0
1394 {
1395 Self::emit_line(al, out);
1396 }
1397 if i == 0
1398 && let Some(trigger) = script_trigger
1399 {
1400 if let Expr::Identifier(script_name) = arg {
1402 let script_id = self
1403 .registry
1404 .script_id_for_trigger(trigger, script_name)
1405 .or_else(|| self.registry.proc_script_id(script_name))
1406 .or_else(|| self.registry.script_id(script_name))
1407 .unwrap_or(-1);
1408 out.push(Instruction::push_int(script_id));
1409 continue;
1410 }
1411 }
1412 if (lookup_name == "enum"
1415 || lookup_name == "enum2"
1416 || lookup_name == "db_getfield"
1417 || lookup_name == "db_find"
1418 || lookup_name == "db_find_refine"
1419 || lookup_name == "db_findbyindex"
1420 || lookup_name == "db_find_with_count"
1421 || lookup_name == "param")
1422 && (i == 0 || i == 1)
1423 && let Expr::Identifier(n) = arg
1424 && let Some(&tc) = self.registry.type_chars.get(n.as_str())
1425 {
1426 out.push(Instruction::push_int(tc));
1427 continue;
1428 }
1429 let hint = param_types.get(i).copied();
1430 if self.try_emit_test_command_id_arg(lookup_name, arg, hint, out) {
1431 continue;
1432 }
1433 self.compile_expr_hinted(arg, out, locals, hint);
1434 }
1435
1436 if let Some(fixed_arg_count) = variadic_info {
1438 let variadic_args = if args.len() > fixed_arg_count {
1439 &args[fixed_arg_count..]
1440 } else {
1441 &[]
1442 };
1443 let type_desc: String = variadic_args
1444 .iter()
1445 .map(|arg| self.infer_type_char(arg, locals))
1446 .collect();
1447 out.push(Instruction::push_string(type_desc));
1448 }
1449
1450 if lookup_name == "db_find" || lookup_name == "db_find_refine" {
1453 let base_type_ordinal = if let Some(Expr::Identifier(col_name)) = args.first() {
1454 self.registry
1455 .dbcolumn_types
1456 .get(col_name.as_str())
1457 .map(|t| match t.base_type() {
1458 crate::types::BaseVarType::Integer => 0,
1459 crate::types::BaseVarType::Long => 1,
1460 crate::types::BaseVarType::String => 2,
1461 })
1462 .unwrap_or(0)
1463 } else {
1464 0
1465 };
1466 out.push(Instruction::push_int(base_type_ordinal));
1467 }
1468
1469 if *call_line > 0 {
1472 Self::emit_line(*call_line, out);
1473 }
1474
1475 let cmd_sym = self
1479 .registry
1480 .lookup_command(lookup_name)
1481 .or_else(|| {
1482 lookup_name.strip_suffix('*').and_then(|base| {
1483 let vararg_name = format!("{}vararg", base);
1484 self.registry.lookup_command(&vararg_name)
1485 })
1486 })
1487 .cloned();
1488 if let Some(sym) = cmd_sym {
1489 if let SymbolKind::Command { opcode, .. } = &sym.kind {
1490 let encoded = (*opcode) | ((cmd_index as i32) << 16);
1491 out.push(Instruction::new(Opcode::Command, Operand::Int(encoded)));
1492 }
1493 } else {
1494 out.push(Instruction::new(
1495 Opcode::Command,
1496 Operand::Str(name.clone()),
1497 ));
1498 }
1499
1500 }
1503
1504 Expr::ProcCall {
1505 name,
1506 args,
1507 arg_lines,
1508 call_line,
1509 } => {
1510 let param_types: Vec<Type> = self
1512 .registry
1513 .lookup_script(name)
1514 .and_then(|sym| {
1515 if let SymbolKind::Script { param_types, .. } = &sym.kind {
1516 Some(param_types.clone())
1517 } else {
1518 None
1519 }
1520 })
1521 .unwrap_or_default();
1522 for (i, arg) in args.iter().enumerate() {
1523 if let Some(&al) = arg_lines.get(i)
1524 && al > 0
1525 {
1526 Self::emit_line(al, out);
1527 }
1528 let hint = param_types.get(i).copied();
1529 self.compile_expr_hinted(arg, out, locals, hint);
1530 }
1531
1532 if *call_line > 0 {
1534 Self::emit_line(*call_line, out);
1535 }
1536
1537 let script_id = self.registry.proc_script_id(name).unwrap_or(-1);
1545 out.push(Instruction::gosub_with_params(script_id));
1546 }
1547
1548 Expr::JumpCall {
1549 name,
1550 args,
1551 arg_lines,
1552 call_line,
1553 } => {
1554 let param_types: Vec<Type> = self
1556 .registry
1557 .lookup_script(name)
1558 .and_then(|sym| {
1559 if let SymbolKind::Script { param_types, .. } = &sym.kind {
1560 Some(param_types.clone())
1561 } else {
1562 None
1563 }
1564 })
1565 .unwrap_or_default();
1566 for (i, arg) in args.iter().enumerate() {
1567 if let Some(&al) = arg_lines.get(i)
1568 && al > 0
1569 {
1570 Self::emit_line(al, out);
1571 }
1572 let hint = param_types.get(i).copied();
1573 self.compile_expr_hinted(arg, out, locals, hint);
1574 }
1575 if *call_line > 0 {
1577 Self::emit_line(*call_line, out);
1578 }
1579
1580 let script_id = self
1581 .registry
1582 .label_script_id(name)
1583 .or_else(|| self.registry.script_id(name))
1584 .unwrap_or(-1);
1585 out.push(Instruction::new(
1586 Opcode::JumpWithParams,
1587 Operand::Int(script_id),
1588 ));
1589 }
1590
1591 Expr::JoinedString { parts } => {
1592 let mut count = 0u32;
1593 for part in parts {
1594 match part {
1595 StringPart::Literal(s) => {
1596 out.push(Instruction::push_string(s.clone()));
1597 count += 1;
1598 }
1599 StringPart::Expr(e) => {
1600 self.compile_expr(e, out, locals);
1601 count += 1;
1602 }
1603 }
1604 }
1605 out.push(Instruction::join_string(count));
1606 }
1607
1608 Expr::MultiAssign(..) => {
1609 }
1611 }
1612 }
1613
1614 fn compile_store(&mut self, target: &Expr, out: &mut CompiledScript, locals: &mut SymbolTable) {
1615 match target {
1616 Expr::LocalVar(name, _var_line) => {
1617 if let Some(sym) = locals.lookup(name) {
1618 let (slot, base) = match &sym.kind {
1619 SymbolKind::LocalVar { var_type, slot, .. } => {
1620 (*slot, var_type.base_type())
1621 }
1622 SymbolKind::ScriptParam { param_type, slot } => {
1623 (*slot, param_type.base_type())
1624 }
1625 _ => (0, BaseVarType::Integer),
1626 };
1627 let opcode = match base {
1628 BaseVarType::Integer => Opcode::PopIntLocal,
1629 BaseVarType::String => Opcode::PopStringLocal,
1630 BaseVarType::Long => Opcode::PopLongLocal,
1631 };
1632 out.push(Instruction::new(opcode, Operand::Int(slot)));
1633 }
1634 }
1635
1636 Expr::GameVar(name, _var_line) => {
1637 let (lookup_name, secondary) = if let Some(stripped) = name.strip_prefix('.') {
1640 (stripped, true)
1641 } else {
1642 (name.as_str(), false)
1643 };
1644 if let Some(sym) = self.registry.lookup_game_var(lookup_name).cloned()
1645 && let SymbolKind::GameVar {
1646 var_id, category, ..
1647 } = &sym.kind
1648 {
1649 let opcode = match category.as_str() {
1650 "varp" => Opcode::PopVarp,
1651 "varn" => Opcode::PopVarn,
1652 "vars" => Opcode::PopVars,
1653 "varbit" => Opcode::PopVarbit,
1654 _ => Opcode::PopVarp,
1655 };
1656 let encoded_id = if secondary {
1657 (1 << 16) | *var_id
1658 } else {
1659 *var_id
1660 };
1661 out.push(Instruction::new(opcode, Operand::Int(encoded_id)));
1662 }
1663 }
1664
1665 Expr::ArrayAccess { name, index } => {
1666 self.compile_expr(index, out, locals);
1668 if let Some(sym) = locals.lookup(name) {
1669 let slot = match &sym.kind {
1670 SymbolKind::LocalVar { slot, .. } => *slot,
1671 _ => 0,
1672 };
1673 out.push(Instruction::new(Opcode::PopArrayInt, Operand::Int(slot)));
1674 }
1675 }
1676
1677 Expr::MultiAssign(targets, target_lines) => {
1678 for (i, target) in targets.iter().enumerate().rev() {
1680 if let Some(&tl) = target_lines.get(i)
1682 && tl > 0
1683 {
1684 Self::emit_line(tl, out);
1685 }
1686 self.compile_store(target, out, locals);
1687 }
1688 }
1689
1690 _ => {
1691 }
1693 }
1694 }
1695
1696 fn command_script_trigger(cmd_name: &str) -> Option<&'static str> {
1698 match cmd_name {
1699 "queue" | "queue*" | "longqueue" | "longqueue*" | "strongqueue" | "strongqueue*"
1700 | "weakqueue" | "weakqueue*" | "clearqueue" => Some("queue"),
1701 "softtimer" | "softtimer*" => Some("softtimer"),
1702 "settimer" | "settimer*" | "cleartimer" => Some("timer"),
1703 "walktrigger" => Some("walktrigger"),
1704 _ => None,
1705 }
1706 }
1707
1708 fn command_variadic_info(cmd_name: &str) -> Option<usize> {
1711 match cmd_name {
1712 "queue*" | "strongqueue*" | "weakqueue*" => Some(2),
1714 "longqueue*" => Some(3),
1715 "settimer" | "softtimer" => Some(2),
1717 "runclientscript*" => Some(1),
1719 _ => None,
1720 }
1721 }
1722
1723 fn infer_type_char(&self, expr: &Expr, locals: &SymbolTable) -> char {
1725 match expr {
1726 Expr::StringLiteral(_) | Expr::JoinedString { .. } => 's',
1727 Expr::LongLiteral(_) => 'l',
1728 Expr::IntLiteral(_)
1729 | Expr::BoolLiteral(_)
1730 | Expr::CoordLiteral(_)
1731 | Expr::CharLiteral(_) => 'i',
1732 Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1733 if let Some(sym) = locals.lookup(name) {
1734 match &sym.kind {
1735 SymbolKind::LocalVar { var_type, .. } => self.type_to_type_char(*var_type),
1736 SymbolKind::ScriptParam { param_type, .. } => {
1737 self.type_to_type_char(*param_type)
1738 }
1739 _ => 'i',
1740 }
1741 } else {
1742 'i'
1743 }
1744 }
1745 Expr::GameVar(name, _var_line) => {
1746 if let Some(sym) = self.registry.lookup_game_var(name)
1747 && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1748 {
1749 return self.type_to_type_char(*var_type);
1750 }
1751 'i'
1752 }
1753 Expr::CommandCall { name, .. } => {
1754 let lookup = name.trim_start_matches('.');
1755 if let Some(sym) = self.registry.lookup_command(lookup)
1756 && let SymbolKind::Command { return_types, .. } = &sym.kind
1757 && let Some(rt) = return_types.first()
1758 {
1759 return self.type_to_type_char(*rt);
1760 }
1761 Self::known_command_type_char(lookup)
1763 }
1764 Expr::ProcCall { name, .. } => {
1765 if let Some(sym) = self.registry.lookup_script(name)
1766 && let SymbolKind::Script { return_types, .. } = &sym.kind
1767 && let Some(rt) = return_types.first()
1768 {
1769 return self.type_to_type_char(*rt);
1770 }
1771 'i'
1772 }
1773 Expr::Identifier(name) => {
1774 let lookup = name.trim_start_matches('.');
1776 if let Some(sym) = self.registry.lookup_command(lookup)
1777 && let SymbolKind::Command { return_types, .. } = &sym.kind
1778 && let Some(rt) = return_types.first()
1779 {
1780 return self.type_to_type_char(*rt);
1781 }
1782 Self::known_command_type_char(lookup)
1783 }
1784 Expr::ConstantVar(name, _) => {
1785 if let Some(sym) = self.registry.lookup_constant(name)
1786 && let SymbolKind::Constant { const_type, .. } = &sym.kind
1787 {
1788 return self.type_to_type_char(*const_type);
1789 }
1790 'i'
1791 }
1792 Expr::BinaryOp { .. } | Expr::Calc(_) => 'i',
1793 Expr::NullLiteral => 'i',
1794 _ => 'i',
1795 }
1796 }
1797
1798 fn infer_target_type(&self, target: &Expr, locals: &SymbolTable) -> Option<Type> {
1800 match target {
1801 Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1802 if let Some(sym) = locals.lookup(name) {
1803 match &sym.kind {
1804 SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1805 SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1806 _ => None,
1807 }
1808 } else {
1809 None
1810 }
1811 }
1812 Expr::GameVar(name, _var_line) => {
1813 let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1814 stripped
1815 } else {
1816 name.as_str()
1817 };
1818 if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1819 && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1820 {
1821 return Some(*var_type);
1822 }
1823 None
1824 }
1825 _ => None,
1826 }
1827 }
1828
1829 fn infer_type(&self, expr: &Expr, locals: &SymbolTable) -> Option<Type> {
1831 match expr {
1832 Expr::LocalVar(name, _) | Expr::ArrayAccess { name, .. } => {
1833 if let Some(sym) = locals.lookup(name) {
1834 match &sym.kind {
1835 SymbolKind::LocalVar { var_type, .. } => Some(*var_type),
1836 SymbolKind::ScriptParam { param_type, .. } => Some(*param_type),
1837 _ => None,
1838 }
1839 } else {
1840 None
1841 }
1842 }
1843 Expr::GameVar(name, _var_line) => {
1844 let lookup_name = if let Some(stripped) = name.strip_prefix('.') {
1845 stripped
1846 } else {
1847 name.as_str()
1848 };
1849 if let Some(sym) = self.registry.lookup_game_var(lookup_name)
1850 && let SymbolKind::GameVar { var_type, .. } = &sym.kind
1851 {
1852 return Some(*var_type);
1853 }
1854 None
1855 }
1856 Expr::CommandCall { name, .. } => {
1857 let lookup = name.trim_start_matches('.');
1858 if let Some(sym) = self.registry.lookup_command(lookup)
1859 && let SymbolKind::Command { return_types, .. } = &sym.kind
1860 {
1861 return return_types.first().copied();
1862 }
1863 None
1864 }
1865 Expr::Identifier(name) => {
1866 let lookup = name.trim_start_matches('.');
1868 if let Some(sym) = self.registry.lookup_command(lookup)
1869 && let SymbolKind::Command { return_types, .. } = &sym.kind
1870 {
1871 return return_types.first().copied();
1872 }
1873 None
1874 }
1875 _ => None,
1876 }
1877 }
1878
1879 fn type_to_type_char(&self, t: Type) -> char {
1880 match t.base_type() {
1881 BaseVarType::String => 's',
1882 BaseVarType::Long => 'l',
1883 BaseVarType::Integer => {
1884 for (name, &tc) in &self.registry.type_chars {
1887 if let Some(from_type) = Type::from_name(name)
1888 && from_type == t
1889 {
1890 return (tc as u8) as char;
1891 }
1892 }
1893 'i'
1894 }
1895 }
1896 }
1897
1898 fn known_command_type_char(name: &str) -> char {
1899 match name {
1901 "uid" => 'p', "npc_uid" => 'u', "displayname" | "name" | "npc_name" | "oc_name" | "oc_cert" => 's',
1904 _ => 'i',
1905 }
1906 }
1907
1908 pub fn validate_trigger_subject(
1917 trigger: &str,
1918 entity_name: &str,
1919 registry: &SymbolRegistry,
1920 ) -> Option<String> {
1921 if entity_name.is_empty() || entity_name == "_" {
1922 return None;
1923 }
1924 if entity_name.starts_with('_') {
1926 return None;
1927 }
1928 if !crate::trigger_table::validates_subject(trigger) {
1931 return None;
1932 }
1933 let key = Self::compute_lookup_key(trigger, entity_name, registry);
1934 if key == -1 {
1935 let hint = if entity_name.contains(':') {
1936 let (iface, comp) = entity_name.split_once(':').unwrap();
1937 format!(
1938 "interface:component subject — check interface.pack for either an if3 entry \
1939 `<iface_id>:<comp_id>=<comp_name>` (with iface_id matching `{iface}`) \
1940 or an if1 entry `<flat_id>={iface}:{comp}`"
1941 )
1942 } else {
1943 "Likely a typo or missing pack entry (check interface.pack / npc.pack / obj.pack / loc.pack)".to_string()
1944 };
1945 return Some(format!(
1946 "[{trigger},{entity_name}] — subject `{entity_name}` did not resolve to an entity. \
1947 {hint}. Script will compile but never dispatch."
1948 ));
1949 }
1950 None
1951 }
1952
1953 pub fn compute_lookup_key(trigger: &str, entity_name: &str, registry: &SymbolRegistry) -> i32 {
1957 let trigger_byte = match crate::trigger_table::byte(trigger) {
1961 Some(b) => b as i64,
1962 None => return -1,
1963 };
1964
1965 if entity_name == "_" {
1967 return trigger_byte as i32;
1968 }
1969
1970 if matches!(trigger, "mapzone" | "mapzoneexit") {
1972 let parts: Vec<&str> = entity_name.splitn(4, '_').collect();
1973 if parts.len() >= 3
1974 && let (Ok(bx), Ok(by)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>())
1975 {
1976 let entity_id: i64 = ((bx & 3) << 20) | (by << 6);
1977 return (entity_id * 1024 + 512 + trigger_byte) as i32;
1978 }
1979 return -1;
1980 }
1981
1982 if matches!(trigger, "zone" | "zoneexit") {
1984 let parts: Vec<&str> = entity_name.splitn(6, '_').collect();
1985 if parts.len() >= 5
1986 && let (Ok(bx), Ok(by), Ok(lx), Ok(lz)) = (
1987 parts[1].parse::<i64>(),
1988 parts[2].parse::<i64>(),
1989 parts[3].parse::<i64>(),
1990 parts[4].parse::<i64>(),
1991 )
1992 {
1993 let entity_id: i64 = ((bx & 3) << 20) | (by << 6) | (lx << 14) | lz;
1994 return (entity_id * 1024 + 512 + trigger_byte) as i32;
1995 }
1996 return -1;
1997 }
1998
1999 if let Some(cat_name) = entity_name.strip_prefix('_') {
2006 if let Some(sym) = registry.lookup_entity_id_typed(cat_name, Type::Category) {
2007 return (sym as i64 * 1024 + 256 + trigger_byte) as i32;
2008 }
2009 return -1;
2010 }
2011
2012 if let Some((iface_name, comp_name)) = entity_name.split_once(':') {
2017 if let Some(packed) = registry.lookup_component(iface_name, comp_name) {
2018 return (packed as i64 * 1024 + 512 + trigger_byte) as i32;
2019 }
2020 return -1;
2021 }
2022
2023 if let Some(entity_type) = crate::trigger_table::subject_type(trigger)
2027 && let Some(entity_id) = registry.lookup_entity_id_typed(entity_name, entity_type)
2028 {
2029 return (entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2030 }
2031
2032 if let Some(sym) = registry.lookup_entity_id(entity_name)
2034 && let crate::symbol::SymbolKind::Constant {
2035 int_value: Some(entity_id),
2036 ..
2037 } = &sym.kind
2038 {
2039 return (*entity_id as i64 * 1024 + 512 + trigger_byte) as i32;
2040 }
2041 -1
2042 }
2043}
2044
2045#[cfg(test)]
2046mod tests {
2047 use super::*;
2048 use crate::types::Type;
2049
2050 fn seed_registry() -> SymbolRegistry {
2054 let mut r = SymbolRegistry::new();
2055 r.register_entity_id("options".into(), Type::Interface, 261);
2058 r.register_entity_id("com14".into(), Type::Component, 14);
2059 r.components
2060 .insert("options:com14".into(), (261 << 16) | 14);
2061 r.register_entity_id("man".into(), Type::Npc, 1);
2063 r.register_entity_id("bronze_axe".into(), Type::Obj, 1351);
2064 r
2065 }
2066
2067 #[test]
2068 fn if_button_resolves_interface_component_form() {
2069 let r = seed_registry();
2070 let key = Compiler::compute_lookup_key("if_button", "options:com_14", &r);
2071 let expected = ((261i64 << 16 | 14) * 1024 + 512 + 147) as i32;
2072 assert_eq!(key, expected);
2073 let com_hash = (261i64 << 16 | 14) as i32;
2077 let engine_key = (com_hash as i64 * 1024 + 512 + 147) as i32;
2078 assert_eq!(key, engine_key);
2079 }
2080
2081 #[test]
2082 fn validate_warns_on_unresolved_if_button_subject() {
2083 let r = seed_registry();
2084 let warning =
2086 Compiler::validate_trigger_subject("if_button", "options:com_does_not_exist", &r);
2087 assert!(
2088 warning.is_some(),
2089 "expected a warning for unresolved subject"
2090 );
2091 assert!(warning.unwrap().contains("did not resolve"));
2092 }
2093
2094 #[test]
2095 fn validate_silent_on_resolvable_subject() {
2096 let r = seed_registry();
2097 assert!(Compiler::validate_trigger_subject("if_button", "options:com_14", &r).is_none());
2098 assert!(Compiler::validate_trigger_subject("opnpc1", "man", &r).is_none());
2099 assert!(Compiler::validate_trigger_subject("opheld1", "bronze_axe", &r).is_none());
2100 }
2101
2102 #[test]
2103 fn validate_silent_on_wildcards_and_categories() {
2104 let r = seed_registry();
2105 assert!(Compiler::validate_trigger_subject("opheld1", "_", &r).is_none());
2107 assert!(Compiler::validate_trigger_subject("opheldu", "_alcoholic_drinks", &r).is_none());
2109 }
2110
2111 #[test]
2112 fn validate_silent_on_name_keyed_triggers() {
2113 let r = seed_registry();
2114 assert!(Compiler::validate_trigger_subject("queue", "my_queue", &r).is_none());
2116 assert!(Compiler::validate_trigger_subject("timer", "my_timer", &r).is_none());
2117 assert!(Compiler::validate_trigger_subject("proc", "my_proc", &r).is_none());
2118 }
2119
2120 #[test]
2121 fn validate_silent_on_coord_triggers() {
2122 let r = seed_registry();
2123 assert!(Compiler::validate_trigger_subject("zone", "0_50_50_10_10", &r).is_none());
2125 }
2126
2127 #[test]
2128 fn validate_warns_on_unknown_npc_subject() {
2129 let r = seed_registry();
2130 let warning = Compiler::validate_trigger_subject("opnpc1", "not_a_real_npc", &r);
2131 assert!(warning.is_some());
2132 }
2133
2134 #[test]
2135 fn bare_command_sharing_a_trigger_name_compiles_to_the_command() {
2136 let mut r = seed_registry();
2142 r.register_command("if_close".into(), 2033, vec![], vec![]);
2143 let mut c = Compiler::new(&r);
2144 let mut out = CompiledScript::new("t".into(), 0);
2145 let mut locals = SymbolTable::new();
2146 c.compile_expr_hinted(
2147 &Expr::Identifier("if_close".into()),
2148 &mut out,
2149 &mut locals,
2150 None,
2151 );
2152 assert!(
2153 out.instructions
2154 .iter()
2155 .any(|i| i.opcode == Opcode::Command && matches!(i.operand, Operand::Int(2033))),
2156 "bare `if_close` should emit Command(2033), got {:?}",
2157 out.instructions
2158 );
2159 assert!(
2160 !out.instructions
2161 .iter()
2162 .any(|i| matches!(i.operand, Operand::Int(148))),
2163 "bare `if_close` must NOT emit the trigger byte 148: {:?}",
2164 out.instructions
2165 );
2166 }
2167
2168 #[test]
2169 fn test_commands_resolve_names_to_ids_but_only_for_themselves() {
2170 let mut r = seed_registry();
2173 r.register_command("mes".into(), 2064, vec![Type::String], vec![]);
2174 r.register_command("if_close".into(), 2033, vec![], vec![]);
2175 let c = Compiler::new(&r);
2176
2177 let mut out = CompiledScript::new("t".into(), 0);
2179 assert!(c.try_emit_test_command_id_arg(
2180 "test_op",
2181 &Expr::Identifier("oploc1".into()),
2182 Some(Type::Int),
2183 &mut out
2184 ));
2185 let last = out.instructions.last().expect("an instruction");
2186 assert!(
2187 matches!(last.operand, Operand::Int(66)),
2188 "got {:?}",
2189 last.operand
2190 );
2191
2192 let mut out = CompiledScript::new("t".into(), 0);
2194 assert!(c.try_emit_test_command_id_arg(
2195 "wait_for",
2196 &Expr::Identifier("mes".into()),
2197 Some(Type::Int),
2198 &mut out
2199 ));
2200 let last = out.instructions.last().expect("an instruction");
2201 assert!(
2202 matches!(last.operand, Operand::Int(2064)),
2203 "got {:?}",
2204 last.operand
2205 );
2206
2207 let mut out = CompiledScript::new("t".into(), 0);
2210 assert!(!c.try_emit_test_command_id_arg(
2211 "mes",
2212 &Expr::Identifier("if_close".into()),
2213 Some(Type::Int),
2214 &mut out
2215 ));
2216 assert!(out.instructions.is_empty());
2217
2218 let mut out = CompiledScript::new("t".into(), 0);
2220 assert!(!c.try_emit_test_command_id_arg(
2221 "test_op",
2222 &Expr::Identifier("oploc1".into()),
2223 Some(Type::Loc),
2224 &mut out
2225 ));
2226 }
2227}