Skip to main content

runec/clientscript/decompile/
source.rs

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