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