1use super::Names;
2use super::inference;
3use super::structure;
4use crate::bytecode::Opcode;
5use crate::clientscript::decode::Script;
6use crate::clientscript::decode::is_branch;
7use crate::clientscript::hooks::{self, HookValue};
8use crate::clientscript::{self, Command, CommandKind};
9use crate::parser::Expr;
10use crate::symbol::{SymbolKind, SymbolRegistry};
11use crate::types::{BaseVarType, Type};
12use anyhow::{Context, Result, bail, ensure};
13use std::collections::{BTreeSet, HashMap, VecDeque};
14use std::fmt::Write;
15use std::path::Path;
16
17#[derive(Clone, Default)]
18pub struct Signature {
19 pub params: [usize; 3],
20 pub returns: [usize; 3],
21 pub param_types: Vec<Type>,
22 pub return_types: Vec<Type>,
23 pub locals: HashMap<String, Type>,
24 pub order: Option<Vec<BaseVarType>>,
26 pub return_order: Vec<BaseVarType>,
28}
29
30fn types(counts: [usize; 3], inferred: &[Type]) -> Vec<Type> {
31 if !inferred.is_empty() {
32 return inferred.to_vec();
33 }
34 [Type::Int, Type::String, Type::Long]
35 .into_iter()
36 .zip(counts)
37 .flat_map(|(ty, count)| vec![ty; count])
38 .collect()
39}
40
41fn parameter_types(signature: &Signature) -> Vec<Type> {
42 let types = types(signature.params, &signature.param_types);
43 let Some(order) = &signature.order else {
44 return types;
45 };
46 let mut pending: [VecDeque<Type>; 3] = Default::default();
47 for ty in types {
48 pending[stack(ty.base_type())].push_back(ty);
49 }
50 order
51 .iter()
52 .map(|&kind| pending[stack(kind)].pop_front().unwrap())
53 .collect()
54}
55
56fn stack(kind: BaseVarType) -> usize {
57 match kind {
58 BaseVarType::Integer => 0,
59 BaseVarType::String => 1,
60 BaseVarType::Long => 2,
61 }
62}
63
64pub fn infer_signatures(
65 scripts: &HashMap<u32, Script>,
66 component_hooks: &[Vec<HookValue>],
67 names: &dyn Names,
68 params: &HashMap<i32, bool>,
69 commands: &[Command],
70 registry: &mut SymbolRegistry,
71) -> Result<HashMap<u32, Signature>> {
72 let mut signatures = signatures(scripts);
73 let ids = scripts
74 .keys()
75 .map(|&id| (script_key(names, id), id as i32))
76 .collect();
77 let mut files = Vec::new();
78 let mut sorted: Vec<_> = scripts.keys().copied().collect();
79 sorted.sort_unstable();
80 for id in sorted {
81 let text = decompile_source(
82 &scripts[&id],
83 id,
84 names,
85 &signatures,
86 params,
87 commands,
88 registry,
89 false,
90 )
91 .with_context(|| format!("Inferring clientscript {id}"))?;
92 let file = clientscript::parse(&text, Path::new("inference.cs2"))
93 .with_context(|| format!("Parsing inferred clientscript {id}"))?;
94 clientscript::register(&file, &ids, registry)?;
95 files.push((id, file));
96 }
97 let (mut inferred, vars) = inference::infer(&files, component_hooks, registry);
98 for (name, ty) in vars {
99 if let Some(SymbolKind::GameVar { var_type, .. }) = registry
100 .game_vars
101 .get_mut(&name)
102 .map(|symbol| &mut symbol.kind)
103 {
104 *var_type = ty;
105 }
106 }
107 for (id, mut file) in files {
108 let info = inferred.remove(&id).unwrap();
109 let signature = signatures.get_mut(&id).unwrap();
110 signature.param_types = info.params;
111 signature.return_types = info.returns;
112 signature.locals = info.locals;
113 signature.order = info.order.filter(|order| {
114 let count = |kind: BaseVarType| order.iter().filter(|ty| **ty == kind).count();
115 count(BaseVarType::Integer) == signature.params[0]
116 && count(BaseVarType::String) == signature.params[1]
117 && count(BaseVarType::Long) == signature.params[2]
118 });
119 for base in ["int", "string", "long"] {
120 if let Some(ty) = signature.locals.remove(base) {
121 signature.locals.insert(format!("{base}0"), ty);
122 }
123 }
124 for (param, &ty) in file.scripts[0]
125 .params
126 .iter_mut()
127 .zip(&signature.param_types)
128 {
129 param.param_type = ty;
130 }
131 file.scripts[0].return_types = signature.return_types.clone();
132 clientscript::register(&file, &ids, registry)?;
133 registry.register_script(
134 file.scripts[0].name.clone(),
135 file.scripts[0].trigger.clone(),
136 parameter_types(signature),
137 signature.return_types.clone(),
138 );
139 }
140 Ok(signatures)
141}
142
143pub fn component_hook_text(
145 values: &[HookValue],
146 transmits: Option<(&str, &[i32])>,
147 signatures: &HashMap<u32, Signature>,
148 names: &dyn Names,
149 registry: &SymbolRegistry,
150) -> Result<String> {
151 let Some(HookValue::Int(script)) = values.first() else {
152 bail!("A hook must start with its script");
153 };
154 let script = u32::try_from(*script).context("Hook with a negative script")?;
155 let mut text = script_name(names, script);
156 if values.len() > 1 {
157 let mut ints = signatures
158 .get(&script)
159 .map_or(&[][..], |signature| signature.param_types.as_slice())
160 .iter()
161 .filter(|ty| ty.base_type() == BaseVarType::Integer);
162 let args = values[1..]
163 .iter()
164 .map(|value| {
165 Ok(match value {
166 HookValue::Int(value) => structure::expressions(&[inference::hook_literal(
167 *value,
168 ints.next().copied(),
169 names,
170 registry,
171 )])?,
172 HookValue::String(value) => structure::hook_string(value),
173 })
174 })
175 .collect::<Result<Vec<_>>>()?;
176 write!(text, "({})", args.join(", "))?;
177 }
178 if let Some((kind, list)) = transmits {
179 let list: Vec<_> = list
180 .iter()
181 .map(|&id| hooks::transmit_name(registry, kind, id).unwrap_or_else(|| id.to_string()))
182 .collect();
183 write!(text, "{{{}}}", list.join(", "))?;
184 }
185 Ok(text)
186}
187
188pub fn script_name(names: &dyn Names, id: u32) -> String {
189 let name = names.name("clientscript", id);
190 let name = name
191 .strip_prefix('[')
192 .and_then(|s| s.strip_suffix(']'))
193 .and_then(|s| s.split_once(','))
194 .map_or(name.as_str(), |(_, name)| name);
195 name.chars()
196 .map(|ch| {
197 if ch.is_ascii_alphanumeric() || ch == '_' {
198 ch
199 } else {
200 '_'
201 }
202 })
203 .collect()
204}
205
206pub fn script_key(names: &dyn Names, id: u32) -> String {
207 clientscript::script_key(&names.name("clientscript", id))
208}
209
210pub fn signatures(scripts: &HashMap<u32, Script>) -> HashMap<u32, Signature> {
211 scripts
212 .iter()
213 .map(|(&id, script)| {
214 let mut returns = [0; 3];
215 let mut return_order = Vec::new();
216 for &opcode in script.operations.iter().rev().skip(1) {
217 let kind = match opcode {
218 Opcode::PushConstantInt | Opcode::PushIntLocal => 0,
219 Opcode::PushConstantString | Opcode::PushStringLocal => 1,
220 Opcode::PushConstantLong | Opcode::PushLongLocal => 2,
221 _ => break,
222 };
223 returns[kind] += 1;
224 return_order.insert(
225 0,
226 [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long][kind],
227 );
228 }
229 (
230 id,
231 Signature {
232 params: [
233 script.int_param_count as usize,
234 script.string_param_count as usize,
235 script.long_param_count as usize,
236 ],
237 returns,
238 return_order,
239 ..Signature::default()
240 },
241 )
242 })
243 .collect()
244}
245
246#[derive(Clone)]
247struct Value {
248 text: String,
249 kind: usize,
250 start: usize,
251 end: usize,
252 int: Option<i32>,
253 string: Option<String>,
254}
255
256impl Value {
257 fn stack(kind: usize, pc: usize) -> Self {
258 Self {
259 text: format!("__pop_{}()", ["int", "string", "long"][kind]),
260 kind,
261 start: pc,
262 end: pc,
263 int: None,
264 string: None,
265 }
266 }
267}
268
269struct Decompiler<'a> {
270 names: &'a dyn Names,
271 registry: &'a SymbolRegistry,
272 signatures: &'a HashMap<u32, Signature>,
273 param_types: &'a HashMap<i32, bool>,
274 commands: HashMap<u16, &'a Command>,
275 returns: [usize; 3],
276 return_types: Vec<Type>,
277 stack: [Vec<Value>; 3],
278 body: String,
279 canonical: bool,
280}
281
282pub fn decompile(
283 script: &Script,
284 id: u32,
285 names: &dyn Names,
286 signatures: &HashMap<u32, Signature>,
287 param_types: &HashMap<i32, bool>,
288 commands: &[Command],
289 registry: &SymbolRegistry,
290) -> Result<String> {
291 decompile_source(
292 script,
293 id,
294 names,
295 signatures,
296 param_types,
297 commands,
298 registry,
299 true,
300 )
301}
302
303#[allow(clippy::too_many_arguments)]
304fn decompile_source(
305 script: &Script,
306 id: u32,
307 names: &dyn Names,
308 signatures: &HashMap<u32, Signature>,
309 param_types: &HashMap<i32, bool>,
310 commands: &[Command],
311 registry: &SymbolRegistry,
312 canonical: bool,
313) -> Result<String> {
314 let sig = signatures
315 .get(&id)
316 .with_context(|| format!("Missing signature for script {id}"))?;
317 if !sig.param_types.is_empty() && sig.param_types.len() != sig.params.iter().sum::<usize>() {
318 bail!("Parameter types do not match stack counts for script {id}");
319 }
320 let mut dc = Decompiler {
321 names,
322 registry,
323 signatures,
324 param_types,
325 commands: commands
326 .iter()
327 .map(|command| (command.opcode, command))
328 .collect(),
329 returns: sig.returns,
330 return_types: if sig.return_types.is_empty() {
331 sig.return_order
332 .iter()
333 .map(|kind| match kind {
334 BaseVarType::Integer => Type::Int,
335 BaseVarType::String => Type::String,
336 BaseVarType::Long => Type::Long,
337 })
338 .collect()
339 } else {
340 sig.return_types.clone()
341 },
342 stack: Default::default(),
343 body: String::new(),
344 canonical,
345 };
346 let mut labels = BTreeSet::new();
347 for (pc, &opcode) in script.operations.iter().enumerate() {
348 if is_branch(opcode) {
349 labels.insert((pc as i64 + 1 + script.int_operands[pc] as i64) as usize);
350 }
351 if opcode == Opcode::Switch {
352 for (_, offset) in &script.switches[script.int_operands[pc] as usize] {
353 labels.insert((pc as i64 + 1 + *offset as i64) as usize);
354 }
355 }
356 }
357 for (pc, &opcode) in script.operations.iter().enumerate() {
358 if labels.contains(&pc) {
359 dc.flush();
360 dc.stack.iter_mut().for_each(Vec::clear);
361 writeln!(dc.body, "__label(L{pc});")?;
362 }
363 dc.instruction(script, pc, opcode)?;
364 }
365 dc.flush();
366 if labels.contains(&script.operations.len()) {
367 writeln!(dc.body, "__label(L{});", script.operations.len())?;
368 }
369 ensure!(
370 script.name.is_empty(),
371 "Named bytecode requires an explicit source name"
372 );
373 let mut out = format!("{}(", script_key(names, id));
374 let base_names = ["int", "string", "long"];
375 let mut params = Vec::new();
376 let mut slots = [0; 3];
377 for ty in parameter_types(sig) {
378 let kind = stack(ty.base_type());
379 let slot = slots[kind];
380 slots[kind] += 1;
381 let ty = match ty {
383 Type::IntArray => "int",
384 ty => ty.name(),
385 };
386 params.push(format!("{ty} ${}{slot}", base_names[kind]));
387 }
388 let returns: Vec<_> = if sig.return_types.is_empty() {
389 sig.return_order
390 .iter()
391 .map(|kind| match kind {
392 BaseVarType::Integer => "int",
393 BaseVarType::String => "string",
394 BaseVarType::Long => "long",
395 })
396 .collect()
397 } else {
398 sig.return_types.iter().map(Type::name).collect()
399 };
400 out.push_str(¶ms.join(", "));
401 out.push(')');
402 if !returns.is_empty() {
403 write!(out, "({})", returns.join(", "))?;
404 }
405 out.push('\n');
406 for (kind, count) in [
407 script.local_int_count,
408 script.local_string_count,
409 script.local_long_count,
410 ]
411 .into_iter()
412 .enumerate()
413 {
414 for i in sig.params[kind]..count as usize {
415 let name = format!("{}{i}", base_names[kind]);
416 let ty = sig
417 .locals
418 .get(&name)
419 .map_or(base_names[kind], |ty| ty.name());
420 writeln!(out, "def_{ty} ${name};")?;
421 }
422 }
423 out.push_str(&dc.body);
424 let mut returns = HashMap::new();
425 for (pc, (&opcode, &operand)) in script
426 .operations
427 .iter()
428 .zip(&script.int_operands)
429 .enumerate()
430 {
431 if opcode == Opcode::GosubWithParams {
432 if let Some(signature) = signatures.get(&(operand as u32)) {
433 returns.insert(
434 format!("~{}", script_name(names, operand as u32)),
435 signature.returns.iter().sum(),
436 );
437 }
438 } else if let Some(command) = dc.commands.get(&script.opcodes[pc]) {
439 returns.insert(command.name.clone(), command.returns.len());
440 }
441 }
442 structure::generate(
444 &out,
445 &sig.locals,
446 sig.return_types.is_empty() && !sig.return_order.is_empty(),
447 &returns,
448 names,
449 registry,
450 canonical,
451 )
452 .with_context(|| format!("Structuring clientscript {id}"))
453}
454
455fn quote(text: &str) -> String {
456 format!("r\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
457}
458
459fn counts(types: &[Type]) -> [usize; 3] {
460 let mut counts = [0; 3];
461 for ty in types {
462 counts[match ty.base_type() {
463 BaseVarType::Integer => 0,
464 BaseVarType::String => 1,
465 BaseVarType::Long => 2,
466 }] += 1;
467 }
468 counts
469}
470
471impl Decompiler<'_> {
472 fn ordered_arguments(
473 &mut self,
474 mut args: Vec<Value>,
475 types: &[Type],
476 component_first: bool,
477 pc: usize,
478 ) -> Vec<Value> {
479 if !self.canonical {
480 return args;
481 }
482 let mut pending: [VecDeque<usize>; 3] = Default::default();
483 for (index, value) in args.iter().enumerate() {
484 pending[value.kind].push_back(index);
485 }
486 let order = types
487 .iter()
488 .enumerate()
489 .map(|(slot, ty)| {
490 let values = &mut pending[stack(ty.base_type())];
491 if component_first && slot == 0 {
492 values.pop_back().unwrap()
493 } else {
494 values.pop_front().unwrap()
495 }
496 })
497 .collect::<Vec<_>>();
498 let emitted = if component_first {
499 order[1..]
500 .iter()
501 .chain(&order[..1])
502 .copied()
503 .collect::<Vec<_>>()
504 } else {
505 order.clone()
506 };
507 let mut positions = vec![0; args.len()];
508 for (position, &index) in emitted.iter().enumerate() {
509 positions[index] = position;
510 }
511 let mut next = usize::MAX;
512 let prefix = args
513 .iter()
514 .enumerate()
515 .rev()
516 .find_map(|(index, value)| {
517 if value.start == value.end {
518 return None;
519 }
520 if positions[index] >= next {
521 Some(index + 1)
522 } else {
523 next = positions[index];
524 None
525 }
526 })
527 .unwrap_or(0);
528 if prefix > 0 {
529 self.flush();
530 for value in &args[..prefix] {
531 if value.start != value.end {
532 writeln!(self.body, "__push({});", value.text).unwrap();
533 }
534 }
535 for value in &mut args[..prefix] {
536 *value = Value::stack(value.kind, pc);
537 }
538 }
539 order.into_iter().map(|index| args[index].clone()).collect()
540 }
541
542 fn arguments(&self, args: &mut [Value], types: &[Type], hook: bool) {
543 let mut by_kind: [Vec<Type>; 3] = Default::default();
544 for &ty in types {
545 by_kind[match ty.base_type() {
546 BaseVarType::Integer => 0,
547 BaseVarType::String => 1,
548 BaseVarType::Long => 2,
549 }]
550 .push(ty);
551 }
552 let mut slots = [0; 3];
553 for value in args {
554 if let Some(&ty) = by_kind[value.kind].get(slots[value.kind]) {
555 self.typed(value, ty, hook);
556 }
557 slots[value.kind] += 1;
558 }
559 }
560 fn typed(&self, value: &mut Value, ty: Type, hook: bool) {
561 let Some(id) = value.int else {
562 return;
563 };
564 if hook && let Some(name) = inference::event_name(id, self.registry) {
565 value.text = name.to_owned();
566 return;
567 }
568 if ty == Type::ClientScript && id >= 0 && !self.signatures.contains_key(&(id as u32)) {
569 return;
570 }
571 if let Some(literal) = inference::named_literal(id, ty, self.names, self.registry) {
572 value.text = match literal {
573 Expr::BoolLiteral(value) => value.to_string(),
574 Expr::NullLiteral => "null".to_owned(),
575 Expr::Identifier(name) => name,
576 Expr::StringLiteral(name) => quote(&name),
577 _ => unreachable!(),
578 };
579 }
580 }
581
582 fn flush(&mut self) {
583 let mut values: Vec<_> = self
584 .stack
585 .iter()
586 .flatten()
587 .filter(|v| v.start != v.end)
588 .cloned()
589 .collect();
590 values.sort_by_key(|v| v.start);
591 for value in values {
592 writeln!(self.body, "__push({});", value.text).unwrap();
593 }
594 for stack in &mut self.stack {
595 for value in stack {
596 *value = Value::stack(value.kind, value.end);
597 }
598 }
599 }
600
601 fn args(&mut self, counts: [usize; 3], pc: usize) -> Vec<Value> {
602 let mut values = Vec::new();
603 for (kind, count) in counts.into_iter().enumerate() {
604 let mut args = Vec::new();
605 for _ in 0..count {
606 args.push(
607 self.stack[kind]
608 .pop()
609 .unwrap_or_else(|| Value::stack(kind, pc)),
610 );
611 }
612 args.reverse();
613 values.extend(args);
614 }
615 values.sort_by_key(|v| v.start);
616 let start = values
617 .iter()
618 .filter(|v| v.start != v.end)
619 .map(|v| v.start)
620 .min()
621 .unwrap_or(pc);
622 if self
623 .stack
624 .iter()
625 .flatten()
626 .any(|v| v.start != v.end && v.start >= start)
627 {
628 let mut pending: Vec<_> = values
629 .iter()
630 .chain(self.stack.iter().flatten())
631 .filter(|v| v.start != v.end)
632 .cloned()
633 .collect();
634 pending.sort_by_key(|v| v.start);
635 for value in pending {
636 writeln!(self.body, "__push({});", value.text).unwrap();
637 }
638 for stack in &mut self.stack {
639 for value in stack {
640 *value = Value::stack(value.kind, pc);
641 }
642 }
643 for value in &mut values {
644 *value = Value::stack(value.kind, pc);
645 }
646 }
647 values
648 }
649
650 fn expression(&mut self, text: String, args: &[Value], returns: [usize; 3], pc: usize) {
651 let start = args
652 .iter()
653 .filter(|v| v.start != v.end)
654 .map(|v| v.start)
655 .min()
656 .unwrap_or(pc);
657 if returns.iter().sum::<usize>() == 1 {
658 let kind = returns.iter().position(|&n| n == 1).unwrap();
659 self.stack[kind].push(Value {
660 text,
661 kind,
662 start,
663 end: pc + 1,
664 int: None,
665 string: None,
666 });
667 } else {
668 self.flush();
669 if returns == [0; 3] {
670 writeln!(self.body, "{text};").unwrap();
671 } else {
672 writeln!(self.body, "__push({text});").unwrap();
673 }
674 for (kind, count) in returns.into_iter().enumerate() {
675 for _ in 0..count {
676 self.stack[kind].push(Value::stack(kind, pc + 1));
677 }
678 }
679 }
680 }
681
682 fn instruction(&mut self, script: &Script, pc: usize, opcode: Opcode) -> Result<()> {
683 let operand = script.int_operands[pc];
684 let local = |kind: usize| format!("${}{}", ["int", "string", "long"][kind], operand);
685 let variable = |domain: &str| format!("%{}", self.names.name(domain, operand as u32));
686 let text = match opcode {
687 Opcode::PushConstantInt => Some((operand.to_string(), 0)),
688 Opcode::PushConstantString => {
689 Some((quote(script.string_operands[pc].as_deref().unwrap()), 1))
690 }
691 Opcode::PushConstantLong => {
692 Some((format!("{}L", script.long_operands[pc].unwrap()), 2))
693 }
694 Opcode::PushVarp => Some((variable("varp"), 0)),
695 Opcode::PushVarbit => Some((variable("varpbit"), 0)),
696 Opcode::PushVarcInt => Some((variable("varc"), 0)),
697 Opcode::PushVarcString => Some((variable("varcstr"), 1)),
698 Opcode::PushClanSettingInt => Some((variable("varclansetting"), 0)),
699 Opcode::PushClanSettingVarbit => Some((variable("varclansetting"), 0)),
700 Opcode::PushClanSettingLong => Some((variable("varclansetting"), 2)),
701 Opcode::PushClanSettingString => Some((variable("varclansetting"), 1)),
702 Opcode::PushIntLocal => Some((local(0), 0)),
703 Opcode::PushStringLocal => Some((local(1), 1)),
704 Opcode::PushLongLocal => Some((local(2), 2)),
705 _ => None,
706 };
707 if let Some((text, kind)) = text {
708 self.stack[kind].push(Value {
709 text,
710 kind,
711 start: pc,
712 end: pc + 1,
713 int: (opcode == Opcode::PushConstantInt).then_some(operand),
714 string: script.string_operands[pc].clone(),
715 });
716 return Ok(());
717 }
718 match opcode {
719 Opcode::PopVarp
720 | Opcode::PopVarbit
721 | Opcode::PopVarcInt
722 | Opcode::PopVarcString
723 | Opcode::PopIntLocal
724 | Opcode::PopStringLocal
725 | Opcode::PopLongLocal => {
726 let (target, kind) = match opcode {
727 Opcode::PopVarp => (variable("varp"), 0),
728 Opcode::PopVarbit => (variable("varpbit"), 0),
729 Opcode::PopVarcInt => (variable("varc"), 0),
730 Opcode::PopVarcString => (variable("varcstr"), 1),
731 Opcode::PopIntLocal => (local(0), 0),
732 Opcode::PopStringLocal => (local(1), 1),
733 _ => (local(2), 2),
734 };
735 let mut count = [0; 3];
736 count[kind] = 1;
737 let args = self.args(count, pc);
738 self.expression(format!("{target} = {}", args[0].text), &args, [0; 3], pc);
739 }
740 Opcode::Branch => {
741 self.flush();
742 writeln!(self.body, "__jump(L{});", pc as i64 + 1 + operand as i64)?;
743 self.stack.iter_mut().for_each(Vec::clear);
744 }
745 op if is_branch(op) => {
746 let count = if matches!(op, Opcode::BranchIfTrue | Opcode::BranchIfFalse) {
747 [1, 0, 0]
748 } else if matches!(
749 op,
750 Opcode::LongBranchNot
751 | Opcode::LongBranchEquals
752 | Opcode::LongBranchLessThan
753 | Opcode::LongBranchGreaterThan
754 | Opcode::LongBranchLessThanOrEquals
755 | Opcode::LongBranchGreaterThanOrEquals
756 ) {
757 [0, 0, 2]
758 } else {
759 [2, 0, 0]
760 };
761 let args = self.args(count, pc);
762 let target = pc as i64 + 1 + operand as i64;
763 let values = args
764 .iter()
765 .map(|v| v.text.as_str())
766 .collect::<Vec<_>>()
767 .join(", ");
768 let name = match op {
769 Opcode::BranchNot => "BranchNot",
770 Opcode::BranchEquals => "BranchEquals",
771 Opcode::BranchLessThan => "BranchLessThan",
772 Opcode::BranchGreaterThan => "BranchGreaterThan",
773 Opcode::BranchLessThanOrEquals => "BranchLessThanOrEquals",
774 Opcode::BranchGreaterThanOrEquals => "BranchGreaterThanOrEquals",
775 Opcode::LongBranchNot => "LongBranchNot",
776 Opcode::LongBranchEquals => "LongBranchEquals",
777 Opcode::LongBranchLessThan => "LongBranchLessThan",
778 Opcode::LongBranchGreaterThan => "LongBranchGreaterThan",
779 Opcode::LongBranchLessThanOrEquals => "LongBranchLessThanOrEquals",
780 Opcode::LongBranchGreaterThanOrEquals => "LongBranchGreaterThanOrEquals",
781 Opcode::BranchIfTrue => "BranchIfTrue",
782 Opcode::BranchIfFalse => "BranchIfFalse",
783 _ => unreachable!(),
784 };
785 self.expression(
786 format!("__branch({name}, L{target}, {values})"),
787 &args,
788 [0; 3],
789 pc,
790 );
791 }
792 Opcode::Switch => {
793 let args = self.args([1, 0, 0], pc);
794 let mut text = format!("__switch({}", args[0].text);
795 for (key, offset) in &script.switches[operand as usize] {
796 write!(text, ", {key}, L{}", pc as i64 + 1 + *offset as i64)?;
797 }
798 text.push(')');
799 self.expression(text, &args, [0; 3], pc);
800 }
801 Opcode::Return => {
802 let args = self.args(self.returns, pc);
803 let types = self.return_types.clone();
804 let args = self.ordered_arguments(args, &types, false, pc);
805 self.expression(
806 format!(
807 "return({})",
808 args.iter()
809 .map(|v| v.text.as_str())
810 .collect::<Vec<_>>()
811 .join(", ")
812 ),
813 &args,
814 [0; 3],
815 pc,
816 );
817 self.stack.iter_mut().for_each(Vec::clear);
818 }
819 Opcode::JoinString => {
820 let args = self.args([0, operand as usize, 0], pc);
821 self.expression(
822 format!(
823 "__join({})",
824 args.iter()
825 .map(|v| v.text.as_str())
826 .collect::<Vec<_>>()
827 .join(", ")
828 ),
829 &args,
830 [0, 1, 0],
831 pc,
832 );
833 }
834 Opcode::GosubWithParams => {
835 let signature = self
836 .signatures
837 .get(&(operand as u32))
838 .context("Missing called clientscript")?;
839 let mut args = self.args(signature.params, pc);
840 let parameters = parameter_types(signature);
841 self.arguments(&mut args, ¶meters, false);
842 let args = self.ordered_arguments(args, ¶meters, false, pc);
843 self.expression(
844 format!(
845 "~{}({})",
846 script_name(self.names, operand as u32),
847 args.iter()
848 .map(|v| v.text.as_str())
849 .collect::<Vec<_>>()
850 .join(", ")
851 ),
852 &args,
853 signature.returns,
854 pc,
855 );
856 }
857 Opcode::PopIntDiscard | Opcode::PopStringDiscard | Opcode::PopLongDiscard => {
858 self.flush();
859 let kind = match opcode {
860 Opcode::PopStringDiscard => 1,
861 Opcode::PopLongDiscard => 2,
862 _ => 0,
863 };
864 self.stack[kind].pop();
865 writeln!(self.body, "__opcode({opcode:?}, {operand});")?;
866 }
867 Opcode::DefineArray | Opcode::PushArrayInt | Opcode::PopArrayInt => {
868 let args = self.args(
869 [if opcode == Opcode::PopArrayInt { 2 } else { 1 }, 0, 0],
870 pc,
871 );
872 let text = match opcode {
873 Opcode::DefineArray => format!(
874 "__define_array({}, {}, {})",
875 operand >> 16,
876 operand & 65535,
877 args[0].text
878 ),
879 Opcode::PushArrayInt => format!("__get_array({operand}, {})", args[0].text),
880 _ => format!("__set_array({operand}, {}, {})", args[0].text, args[1].text),
881 };
882 self.expression(
883 text,
884 &args,
885 [usize::from(opcode == Opcode::PushArrayInt), 0, 0],
886 pc,
887 );
888 }
889 _ => {
890 let command = self
891 .commands
892 .get(&script.opcodes[pc])
893 .copied()
894 .with_context(|| format!("Unknown operation {opcode:?}"))?;
895 let mut types = command.params.clone();
896 let mut returns = counts(&command.returns);
897 let mut name = command.name.to_owned();
898 let component_first = self.registry.component_first_command(&name);
899 if component_first {
900 let component = types.remove(0);
901 types.push(component);
902 }
903 if matches!(command.kind, CommandKind::Hook | CommandKind::HookComponent) {
904 let explicit = command.kind == CommandKind::HookComponent;
905 let signature = self.stack[1]
906 .last()
907 .and_then(|v| v.string.as_deref())
908 .context("Nonconstant hook signature")?;
909 let triggers = if signature.ends_with('Y') {
910 let index = self.stack[0]
911 .len()
912 .checked_sub(1 + usize::from(explicit))
913 .context("Missing hook count")?;
914 self.stack[0][index].int.context("Nonconstant hook count")? as usize
915 } else {
916 0
917 };
918 types = clientscript::hook_types(signature, triggers, explicit);
919 }
920 if command.kind == CommandKind::Enum {
921 let n = self.stack[0].len();
922 let string = n >= 3 && self.stack[0][n - 3].int == Some(115);
923 returns = if string { [0, 1, 0] } else { [1, 0, 0] };
924 } else if command.kind == CommandKind::Param {
925 let id = self.stack[0]
926 .last()
927 .and_then(|v| v.int)
928 .context("Nonconstant param")?;
929 if self.param_types.get(&id) == Some(&true) {
930 returns = [0, 1, 0];
931 }
932 }
933 if operand == 1 {
934 name.insert(0, '.');
935 }
936 let mut args = self.args(counts(&types), pc);
937 self.arguments(
938 &mut args,
939 &types,
940 matches!(command.kind, CommandKind::Hook | CommandKind::HookComponent),
941 );
942 if component_first {
943 let component = types.pop().unwrap();
944 types.insert(0, component);
945 }
946 let mut args = self.ordered_arguments(args, &types, component_first, pc);
947 let type_args = match command.kind {
948 CommandKind::Enum => 2,
949 CommandKind::EnumOutput => 1,
950 _ => 0,
951 };
952 if type_args > 0 {
953 for arg in args.iter_mut().take(type_args) {
955 if let Some(ty) = arg
956 .int
957 .and_then(|value| char::from_u32(value as u32))
958 .and_then(Type::from_char)
959 {
960 arg.text = ty.name().to_owned();
961 }
962 }
963 }
964 self.expression(
965 format!(
966 "{name}({})",
967 args.iter()
968 .map(|v| v.text.as_str())
969 .collect::<Vec<_>>()
970 .join(", ")
971 ),
972 &args,
973 returns,
974 pc,
975 );
976 }
977 }
978 Ok(())
979 }
980}