Skip to main content

runec/
clientscript.rs

1use crate::bytecode::{CompiledScript, Opcode, Operand};
2use crate::lexer::Lexer;
3use crate::parser::{Expr, Parser, ScriptFile, Statement, StringPart};
4use crate::pointer::{PointerHolder, PointerType};
5use crate::pointer_checker::PointerChecker;
6use crate::symbol::{ReturnType, SymbolKind, SymbolRegistry, identifier_form};
7use crate::symloader::{load_constant_files, load_game_var_types, load_packs};
8use crate::typechecker::TypeChecker;
9use crate::types::BaseVarType;
10use crate::types::Type;
11use std::collections::{BTreeMap, HashMap, HashSet};
12use std::fs;
13use std::io::{Error, ErrorKind, Result};
14use std::path::{Path, PathBuf};
15
16pub mod decode;
17pub mod decompile;
18pub mod format;
19pub(crate) mod hooks;
20pub(crate) mod triggers;
21use format::{Format, Width};
22pub use hooks::{HookValue, component_hook};
23
24#[derive(Clone, Copy, PartialEq, Eq)]
25pub enum CommandKind {
26    Fixed,
27    Hook,
28    HookComponent,
29    Enum,
30    EnumOutput,
31    Param,
32}
33
34pub struct Command {
35    pub opcode: u16,
36    pub name: String,
37    pub params: Vec<Type>,
38    pub returns: Vec<Type>,
39    pub kind: CommandKind,
40    pub component_last: bool,
41}
42
43pub(crate) fn command_pointers(registry: &SymbolRegistry) -> HashMap<String, PointerHolder> {
44    let mut pointers = HashMap::new();
45    for name in registry.commands.keys() {
46        let name = name.to_lowercase();
47        if !(name.starts_with("cc_") || name == "if_find") || name == "cc_deleteall" {
48            continue;
49        }
50        for (prefix, pointer) in [
51            ("", PointerType::ActiveComponent),
52            (".", PointerType::ActiveComponent2),
53        ] {
54            let mut holder = PointerHolder::default();
55            match name.as_str() {
56                "cc_create" => holder.set.insert(pointer),
57                "cc_find" | "if_find" => {
58                    holder.set.insert(pointer);
59                    holder.conditional_set = true;
60                }
61                _ => holder.required.insert(pointer),
62            }
63            pointers.insert(format!("{prefix}{name}"), holder);
64        }
65    }
66    pointers
67}
68
69pub fn hook_types(signature: &str, triggers: usize, explicit: bool) -> Vec<Type> {
70    let mut types = vec![Type::ClientScript];
71    types.extend(
72        signature
73            .trim_end_matches('Y')
74            .chars()
75            .map(|ch| Type::from_char(ch).unwrap_or(Type::Int)),
76    );
77    if signature.ends_with('Y') {
78        types.extend(vec![Type::Int; triggers + 1]);
79    }
80    types.push(Type::String);
81    if explicit {
82        types.push(Type::Component);
83    }
84    types
85}
86
87#[derive(Clone, Debug)]
88pub struct Source {
89    pub path: PathBuf,
90    pub file: ScriptFile,
91}
92
93impl Source {
94    pub fn parse(text: &str, path: &Path) -> Result<Self> {
95        Ok(Self {
96            path: path.to_path_buf(),
97            file: parse(text, path)?,
98        })
99    }
100
101    pub fn compile(
102        &self,
103        registry: &SymbolRegistry,
104        format: &Format,
105    ) -> Result<Vec<(i32, Vec<u8>)>> {
106        compile(&self.file, &self.path, registry, format)
107    }
108}
109
110pub fn script_key(name: &str) -> String {
111    let (trigger, name) = name
112        .strip_prefix('[')
113        .and_then(|name| name.strip_suffix(']'))
114        .and_then(|name| name.split_once(','))
115        .unwrap_or(("proc", name));
116    format!("[{trigger},{}]", identifier_form(name))
117}
118
119pub fn script_ids(pack: &Path) -> Result<HashMap<String, i32>> {
120    let mut ids = HashMap::new();
121    for line in fs::read_to_string(pack.join("clientscript.pack"))?.lines() {
122        if let Some((id, name)) = line.split_once('=') {
123            let key = script_key(name);
124            if ids
125                .insert(key.clone(), id.parse::<i32>().map_err(invalid)?)
126                .is_some()
127            {
128                return Err(invalid(format!("Duplicate clientscript name {key}")));
129            }
130        }
131    }
132    Ok(ids)
133}
134
135pub fn compile_sources(
136    sources: &[Source],
137    source_dir: &Path,
138    pack: &Path,
139) -> Result<BTreeMap<u32, Vec<u8>>> {
140    compile_registered_sources(sources, pack, registry(source_dir, pack)?)
141}
142
143pub fn compile_directory(source_dir: &Path, pack: &Path) -> Result<BTreeMap<u32, Vec<u8>>> {
144    let registry = registry(source_dir, pack)?;
145    let sources = load_sources(source_dir)?;
146    compile_registered_sources(&sources, pack, registry)
147}
148
149/// Registers every script, giving the ones the pack doesn't name the next free ids.
150fn register_sources(
151    sources: &[Source],
152    pack: &Path,
153    registry: &mut SymbolRegistry,
154) -> Result<Vec<(i32, String)>> {
155    let mut ids = script_ids(pack)?;
156    let mut next = ids.values().copied().max().unwrap_or(-1) + 1;
157    for source in sources {
158        for script in &source.file.scripts {
159            if let Some(id) = script
160                .name
161                .strip_prefix("clientscript_")
162                .and_then(|id| id.parse::<i32>().ok())
163            {
164                next = next.max(
165                    id.checked_add(1)
166                        .ok_or_else(|| invalid("Clientscript ID overflow"))?,
167                );
168            }
169        }
170    }
171    let mut new_ids = Vec::new();
172    let mut declared = HashSet::new();
173    for source in sources {
174        std::sync::Arc::make_mut(&mut registry.visibility)
175            .declare_source(&source.path, &source.file);
176        for script in &source.file.scripts {
177            let key = format!("[{},{}]", script.trigger, script.name);
178            if !declared.insert(key.clone()) {
179                return Err(invalid(format!("Duplicate script {key}")));
180            }
181            if !ids.contains_key(&key)
182                && !script
183                    .name
184                    .strip_prefix("clientscript_")
185                    .is_some_and(|id| id.parse::<u32>().is_ok())
186            {
187                ids.insert(key.clone(), next);
188                new_ids.push((next, key));
189                next = next
190                    .checked_add(1)
191                    .ok_or_else(|| invalid("Clientscript ID overflow"))?;
192            }
193        }
194        register(&source.file, &ids, registry)?;
195    }
196    Ok(new_ids)
197}
198
199pub fn compile_registered_sources(
200    sources: &[Source],
201    pack: &Path,
202    mut registry: SymbolRegistry,
203) -> Result<BTreeMap<u32, Vec<u8>>> {
204    let format = Format::load(&pack.join("cs2_command.pack"))?;
205    let new_ids = register_sources(sources, pack, &mut registry)?;
206    let mut scripts = Vec::new();
207    for source in sources {
208        scripts.extend(checked_codegen(&source.file, &source.path, &registry)?);
209    }
210    PointerChecker::new_client(&scripts, &registry)
211        .run()
212        .print_all();
213    let mut compiled = BTreeMap::new();
214    for script in scripts {
215        if compiled
216            .insert(
217                u32::try_from(script.id).map_err(invalid)?,
218                encode(&script, &format)?,
219            )
220            .is_some()
221        {
222            return Err(invalid(format!("Duplicate clientscript ID {}", script.id)));
223        }
224    }
225    if !new_ids.is_empty() {
226        let path = pack.join("clientscript.pack");
227        let mut text = fs::read_to_string(&path)?;
228        if !text.is_empty() && !text.ends_with('\n') {
229            text.push('\n');
230        }
231        for (id, key) in new_ids {
232            text.push_str(&format!("{id}={key}\n"));
233        }
234        fs::write(path, text)?;
235    }
236    Ok(compiled)
237}
238
239pub fn load_sources(dir: &Path) -> Result<Vec<Source>> {
240    let mut sources = Vec::new();
241    for path in crate::sources::script_files(dir, "cs2")? {
242        if path
243            .file_name()
244            .is_some_and(|name| name != "engine.cs2" && name != "engine.gs2")
245        {
246            sources.push(Source::parse(&fs::read_to_string(&path)?, &path)?);
247        }
248    }
249    sources.sort_by(|a, b| a.path.cmp(&b.path));
250    Ok(sources)
251}
252
253pub fn load_commands(path: &Path, engine_path: &Path) -> Result<Vec<Command>> {
254    let format = Format::load(path)?;
255    let engine_text = fs::read_to_string(engine_path)?;
256    commands(&format, &engine_text, engine_path)
257}
258
259/// Parse host-supplied command signatures without reading files.
260pub fn commands(format: &Format, engine_text: &str, label: &Path) -> Result<Vec<Command>> {
261    let engine = parse(engine_text, label)?;
262    let mut signatures = HashMap::new();
263    for script in engine.scripts {
264        if script.trigger != "command" || !script.body.is_empty() {
265            return Err(invalid("engine.cs2 must contain command signatures"));
266        }
267        if signatures.insert(script.name.clone(), script).is_some() {
268            return Err(invalid("Duplicate engine.cs2 command"));
269        }
270    }
271    let mut commands = Vec::new();
272    for (&opcode, name) in &format.commands {
273        let signature = signatures
274            .remove(name)
275            .ok_or_else(|| invalid(format!("Missing engine.cs2 signature for {name}")))?;
276        let annotation = |name| {
277            signature
278                .annotations
279                .iter()
280                .find(|annotation| annotation.name == name)
281                .map(|annotation| annotation.value.as_str())
282        };
283        let kind = match annotation("signature").unwrap_or("fixed") {
284            "fixed" => CommandKind::Fixed,
285            "hook" => CommandKind::Hook,
286            "hook_component" => CommandKind::HookComponent,
287            "enum" => CommandKind::Enum,
288            "enum_output" => CommandKind::EnumOutput,
289            "param" => CommandKind::Param,
290            kind => return Err(invalid(format!("Unknown command kind {kind}"))),
291        };
292        let component_last = annotation("stack") == Some("component_last");
293        commands.push(Command {
294            opcode,
295            name: name.clone(),
296            params: signature
297                .params
298                .iter()
299                .map(|param| param.param_type)
300                .collect(),
301            returns: signature.return_types,
302            kind,
303            component_last,
304        });
305    }
306    if !signatures.is_empty() {
307        return Err(invalid(
308            "engine.cs2 contains commands without opcode definitions",
309        ));
310    }
311    Ok(commands)
312}
313
314/// The registry an interface's hooks read against: every script and what it takes.
315pub fn registry_with_scripts(source_dir: &Path, pack: &Path) -> Result<SymbolRegistry> {
316    let mut registry = registry(source_dir, pack)?;
317    register_sources(&load_sources(source_dir)?, pack, &mut registry)?;
318    Ok(registry)
319}
320
321pub fn registry(source_dir: &Path, pack: &Path) -> Result<SymbolRegistry> {
322    let root = crate::sources::target_dir(source_dir, crate::sources::Scope::Client);
323    let source_dir = root.as_path();
324    let mut registry = SymbolRegistry::new();
325    load_packs(&mut registry, pack);
326    for (key, id) in script_ids(pack)? {
327        let (trigger, name) = key[1..key.len() - 1].split_once(',').unwrap();
328        registry
329            .trigger_script_ids
330            .insert(format!("{trigger}:{name}"), id);
331        registry.script_ids.insert(name.to_owned(), id);
332        if trigger == "proc" {
333            registry.proc_script_ids.insert(name.to_owned(), id);
334        }
335    }
336    registry.clear_commands();
337    registry.game_vars.retain(|_, symbol| {
338        matches!(
339            &symbol.kind, SymbolKind::GameVar { category, .. }
340            if matches!(category.as_str(), "varp" | "varpbit")
341        )
342    });
343    let engine_path = crate::sources::engine_file(source_dir, crate::sources::Scope::Client)?
344        .ok_or_else(|| {
345            invalid(format!(
346                "No engine.cs2 found under {}",
347                source_dir.display()
348            ))
349        })?;
350    for command in load_commands(&pack.join("cs2_command.pack"), &engine_path)? {
351        registry.register_command(
352            command.name.to_owned(),
353            command.opcode as i32,
354            command.params.clone(),
355            command.returns.clone(),
356        );
357        registry.stack_commands.insert(command.name.to_owned());
358        registry.set_component_first_command(&command.name, command.component_last);
359        if matches!(command.kind, CommandKind::Hook | CommandKind::HookComponent) {
360            registry.hook_commands.insert(
361                command.name.to_owned(),
362                command.kind == CommandKind::HookComponent,
363            );
364        }
365        let dynamic = match command.kind {
366            CommandKind::Enum => Some(ReturnType::TypeArgument(1)),
367            CommandKind::Param => Some(ReturnType::ParamArgument(
368                command.params.len().saturating_sub(1),
369            )),
370            _ => None,
371        };
372        if let Some(dynamic) = dynamic {
373            registry
374                .dynamic_returns
375                .insert(command.name.clone(), dynamic);
376        }
377    }
378    for (name, ty) in [
379        ("__pop_int", Type::Int),
380        ("__pop_string", Type::String),
381        ("__pop_long", Type::Long),
382        ("__join", Type::String),
383        ("__get_array", Type::Int),
384    ] {
385        registry.register_command(name.to_owned(), 0, Vec::new(), vec![ty]);
386    }
387    for (kind, ty) in [("varc", Type::Int), ("varcstr", Type::String)] {
388        let path = pack.join(format!("{kind}.pack"));
389        if !path.exists() {
390            continue;
391        }
392        for line in fs::read_to_string(path)?.lines() {
393            if line.trim_start().starts_with("//") {
394                continue;
395            }
396            if let Some((id, name)) = line.split_once('=') {
397                registry.register_game_var(
398                    name.to_owned(),
399                    ty,
400                    id.parse::<i32>().map_err(invalid)?,
401                    kind.to_owned(),
402                );
403            }
404        }
405    }
406    let configs = crate::sources::target_config_files(source_dir, crate::sources::Scope::Client)?;
407    {
408        for file in configs
409            .iter()
410            .filter(|path| path.extension().is_some_and(|ext| ext == "param"))
411        {
412            let text = fs::read_to_string(file)?;
413            let mut id = None;
414            for line in text.lines().map(str::trim) {
415                if let Some(name) = line
416                    .strip_prefix('[')
417                    .and_then(|line| line.strip_suffix(']'))
418                {
419                    id = registry.lookup_reference(name, Type::Param);
420                    if let Some(id) = id {
421                        registry.register_param_type(id, Type::Int);
422                    }
423                } else if let Some(ty) = line.strip_prefix("type=")
424                    && let Some(id) = id
425                {
426                    let ty = ty.trim();
427                    let ty = if let Some(byte) = ty.strip_prefix("byte:0x") {
428                        let byte = u8::from_str_radix(byte, 16).map_err(invalid)?;
429                        Type::from_char(byte as char).unwrap_or(Type::Int)
430                    } else {
431                        Type::from_name(ty)
432                            .ok_or_else(|| invalid(format!("Unknown parameter type {ty}")))?
433                    };
434                    registry.register_param_type(id, ty);
435                }
436            }
437        }
438    }
439    load_constant_files(&mut registry, &configs);
440    load_game_var_types(&mut registry, &configs);
441    load_varc_types(&mut registry, &configs)?;
442    load_clan_settings(&mut registry, &configs, pack)?;
443    registry.visibility =
444        std::sync::Arc::new(crate::sources::Visibility::load(source_dir, &registry));
445    Ok(registry)
446}
447
448/// `varc.pack` only says which stack a varc is on; its file declares its type.
449fn load_varc_types(registry: &mut SymbolRegistry, files: &[PathBuf]) -> Result<()> {
450    for file in files
451        .iter()
452        .filter(|path| path.extension().is_some_and(|ext| ext == "varc"))
453    {
454        let mut section = None;
455        for line in fs::read_to_string(file)?.lines().map(str::trim) {
456            if let Some(name) = line
457                .strip_prefix('[')
458                .and_then(|line| line.strip_suffix(']'))
459            {
460                section = Some(name.to_owned());
461            } else if let Some(ty) = line.strip_prefix("type=").and_then(Type::from_name)
462                && let Some(SymbolKind::GameVar { var_type, .. }) = section
463                    .as_ref()
464                    .and_then(|name| registry.game_vars.get_mut(name))
465                    .map(|symbol| &mut symbol.kind)
466            {
467                *var_type = ty;
468            }
469        }
470    }
471    Ok(())
472}
473
474/// A clan setting's opcodes follow its type, which only its config declares:
475/// `basevar` for a bit range, otherwise `type`.
476pub(crate) fn load_clan_settings(
477    registry: &mut SymbolRegistry,
478    files: &[PathBuf],
479    pack: &Path,
480) -> Result<()> {
481    let ids: HashMap<String, i32> = fs::read_to_string(pack.join("varclansetting.pack"))
482        .unwrap_or_default()
483        .lines()
484        .filter_map(|line| line.split_once('='))
485        .filter_map(|(id, name)| Some((name.trim().to_owned(), id.parse().ok()?)))
486        .collect();
487    let mut add = |name: &str, ty: Option<&str>, bits: bool| -> Result<()> {
488        let id = ids
489            .get(name)
490            .copied()
491            .or_else(|| name.strip_prefix("varclansetting_")?.parse().ok())
492            .ok_or_else(|| invalid(format!("Unknown clan setting {name}")))?;
493        let (category, ty) = match (bits, ty) {
494            (true, _) => ("clansetting_varbit", Type::Int),
495            (_, Some("int" | "bit")) => ("clansetting_int", Type::Int),
496            (_, Some("long")) => ("clansetting_long", Type::Long),
497            (_, Some("clanforumqfc")) => ("clansetting_long", Type::ClanForumQfc),
498            (_, Some("string")) => ("clansetting_string", Type::String),
499            _ => {
500                return Err(invalid(format!(
501                    "Clan setting {name} has no opcodes for type {ty:?}"
502                )));
503            }
504        };
505        registry.register_game_var(name.to_owned(), ty, id, category.to_owned());
506        Ok(())
507    };
508    for file in files {
509        if file.extension().is_none_or(|ext| ext != "varclansetting") {
510            continue;
511        }
512        let text = fs::read_to_string(file)?;
513        let mut section: Option<(&str, Option<&str>, bool)> = None;
514        for line in text.lines().map(str::trim) {
515            if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
516                if let Some((name, ty, bits)) = section {
517                    add(name, ty, bits)?;
518                }
519                section = Some((name, None, false));
520            } else if let Some((_, ty, bits)) = &mut section {
521                if let Some(value) = line.strip_prefix("type=") {
522                    *ty = Some(value.trim());
523                } else if line.starts_with("basevar=") {
524                    *bits = true;
525                }
526            }
527        }
528        if let Some((name, ty, bits)) = section {
529            add(name, ty, bits)?;
530        }
531    }
532    Ok(())
533}
534
535pub fn parse(source: &str, path: &Path) -> Result<ScriptFile> {
536    let path = path.to_path_buf();
537    let tokens = Lexer::new(source, &path).tokenize().map_err(invalid)?;
538    Parser::new(tokens, &path).parse().map_err(invalid)
539}
540
541pub fn register(
542    file: &ScriptFile,
543    ids: &HashMap<String, i32>,
544    registry: &mut SymbolRegistry,
545) -> Result<()> {
546    for script in &file.scripts {
547        for statement in &script.body {
548            register_variables(statement, registry);
549        }
550        if triggers::lookup(&script.trigger).is_none() {
551            return Err(invalid(format!(
552                "Invalid client trigger {}",
553                script.trigger
554            )));
555        }
556        let id = ids
557            .get(&format!("[{},{}]", script.trigger, script.name))
558            .or_else(|| ids.get(&script.name))
559            .copied()
560            .or_else(|| {
561                script
562                    .name
563                    .strip_prefix("clientscript_")
564                    .and_then(|id| id.parse::<i32>().ok())
565                    .filter(|id| *id >= 0)
566            })
567            .ok_or_else(|| invalid(format!("Missing clientscript ID for {}", script.name)))?;
568        registry
569            .preloaded_script_ids
570            .insert(format!("{}:{}", script.trigger, script.name), id);
571        registry.register_script(
572            script.name.clone(),
573            script.trigger.clone(),
574            script.params.iter().map(|p| p.param_type).collect(),
575            script.return_types.clone(),
576        );
577        registry
578            .stack_scripts
579            .insert(format!("{}:{}", script.trigger, script.name));
580    }
581    Ok(())
582}
583
584pub(crate) fn register_variables(statement: &Statement, registry: &mut SymbolRegistry) {
585    match statement {
586        Statement::VarDeclaration {
587            value: Some(value), ..
588        }
589        | Statement::Expression { expr: value, .. }
590        | Statement::ArrayDeclaration { size: value, .. } => {
591            register_expr_variables(value, registry)
592        }
593        Statement::Assignment { target, value, .. } => {
594            register_expr_variables(target, registry);
595            register_expr_variables(value, registry);
596        }
597        Statement::Return { values, .. } => {
598            for value in values {
599                register_expr_variables(value, registry);
600            }
601        }
602        Statement::If {
603            condition,
604            body,
605            else_if,
606            else_body,
607            ..
608        } => {
609            register_expr_variables(condition, registry);
610            for statement in body {
611                register_variables(statement, registry);
612            }
613            for (condition, body, _) in else_if {
614                register_expr_variables(condition, registry);
615                for statement in body {
616                    register_variables(statement, registry);
617                }
618            }
619            if let Some(body) = else_body {
620                for statement in body {
621                    register_variables(statement, registry);
622                }
623            }
624        }
625        Statement::While {
626            condition, body, ..
627        } => {
628            register_expr_variables(condition, registry);
629            for statement in body {
630                register_variables(statement, registry);
631            }
632        }
633        Statement::Switch {
634            expr,
635            cases,
636            default,
637            ..
638        } => {
639            register_expr_variables(expr, registry);
640            for case in cases {
641                for statement in &case.body {
642                    register_variables(statement, registry);
643                }
644            }
645            if let Some(body) = default {
646                for statement in body {
647                    register_variables(statement, registry);
648                }
649            }
650        }
651        _ => {}
652    }
653}
654
655fn register_expr_variables(expr: &Expr, registry: &mut SymbolRegistry) {
656    match expr {
657        Expr::GameVar(name, _) if registry.lookup_game_var(name).is_none() => {
658            for (kind, ty) in [
659                ("varp", Type::Int),
660                ("varpbit", Type::Int),
661                ("varc", Type::Int),
662                ("varcstr", Type::String),
663            ] {
664                if let Some(id) = name
665                    .strip_prefix(&format!("{}_", hooks::var_placeholder(kind)))
666                    .and_then(|s| s.parse::<u16>().ok())
667                {
668                    registry.register_game_var(name.clone(), ty, id as i32, kind.to_owned());
669                }
670            }
671        }
672        Expr::ArrayAccess { index, .. } | Expr::Calc(index) => {
673            register_expr_variables(index, registry)
674        }
675        Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
676            register_expr_variables(lhs, registry);
677            register_expr_variables(rhs, registry);
678        }
679        Expr::CommandCall { name, args, .. } => {
680            if let Some(&explicit) = registry.hook_commands.get(name.trim_start_matches('.'))
681                && args.len() == 1 + usize::from(explicit)
682                && let Some(Expr::StringLiteral(text)) = args.first()
683                && let Ok(values) = hooks::parse(text)
684            {
685                if hooks::transmit_kind(name).is_some_and(|kind| kind.starts_with("var"))
686                    && let Some(Expr::Tuple(transmits)) = values.get(2)
687                {
688                    for value in transmits {
689                        if let Expr::Identifier(name) = value {
690                            register_expr_variables(&Expr::GameVar(name.clone(), 0), registry);
691                        }
692                    }
693                }
694                for value in &values {
695                    register_expr_variables(value, registry);
696                }
697            }
698            for arg in args {
699                register_expr_variables(arg, registry);
700            }
701        }
702        Expr::ProcCall { args, .. }
703        | Expr::JumpCall { args, .. }
704        | Expr::MultiAssign(args, _)
705        | Expr::Tuple(args) => {
706            for arg in args {
707                register_expr_variables(arg, registry);
708            }
709        }
710        Expr::JoinedString { parts } => {
711            for part in parts {
712                if let StringPart::Expr(expr) = part {
713                    register_expr_variables(expr, registry);
714                }
715            }
716        }
717        _ => {}
718    }
719}
720
721pub fn compile(
722    file: &ScriptFile,
723    path: &Path,
724    registry: &SymbolRegistry,
725    format: &Format,
726) -> Result<Vec<(i32, Vec<u8>)>> {
727    let scripts = checked_codegen(file, path, registry)?;
728    PointerChecker::new_client(&scripts, registry)
729        .run()
730        .print_all();
731    scripts
732        .into_iter()
733        .map(|compiled| Ok((compiled.id, encode(&compiled, format)?)))
734        .collect()
735}
736
737fn checked_codegen(
738    file: &ScriptFile,
739    path: &Path,
740    registry: &SymbolRegistry,
741) -> Result<Vec<CompiledScript>> {
742    let mut checker = TypeChecker::new(registry);
743    checker.check_file(file, path);
744    if checker.diagnostics.has_errors() {
745        return Err(invalid(
746            checker
747                .diagnostics
748                .errors()
749                .iter()
750                .map(ToString::to_string)
751                .collect::<Vec<_>>()
752                .join("\n"),
753        ));
754    }
755    codegen(file, path, registry)
756}
757
758pub(crate) fn codegen(
759    file: &ScriptFile,
760    path: &Path,
761    registry: &SymbolRegistry,
762) -> Result<Vec<CompiledScript>> {
763    let mut diagnostics = crate::diagnostics::DiagnosticsCollector::new();
764    let compiled = crate::compiler::compile_file(file, path, registry, true, &mut diagnostics);
765    if diagnostics.has_errors() {
766        return Err(invalid(
767            diagnostics
768                .errors()
769                .iter()
770                .map(ToString::to_string)
771                .collect::<Vec<_>>()
772                .join(
773                    "
774",
775                ),
776        ));
777    }
778    Ok(compiled)
779}
780
781pub fn encode(script: &CompiledScript, format: &Format) -> Result<Vec<u8>> {
782    encode_named(script, "", format)
783}
784
785pub fn encode_named(script: &CompiledScript, name: &str, format: &Format) -> Result<Vec<u8>> {
786    let mut positions = Vec::with_capacity(script.instructions.len() + 1);
787    let mut count = 0;
788    for instruction in &script.instructions {
789        positions.push(count);
790        if instruction.opcode != Opcode::LineNumber {
791            count += 1;
792        }
793    }
794    positions.push(count);
795    let mut out = Vec::new();
796    write_string(&mut out, name)?;
797    let mut switches = Vec::new();
798    for (i, instruction) in script.instructions.iter().enumerate() {
799        if instruction.opcode == Opcode::LineNumber {
800            continue;
801        }
802        if instruction.opcode == Opcode::Raw {
803            let Operand::Long(value) = instruction.operand else {
804                return Err(invalid("Invalid raw client instruction"));
805            };
806            let opcode = (value >> 32) as u16;
807            let operand = value as i32;
808            out.extend_from_slice(&opcode.to_be_bytes());
809            format.width(opcode).integer(&mut out, operand as i64)?;
810            continue;
811        }
812        let (opcode, width) = match instruction.opcode {
813            Opcode::Command => match instruction.operand {
814                Operand::Int(value) => (value as u16, format.width(value as u16)),
815                _ => return Err(invalid("Unresolved client command")),
816            },
817            value => format.instruction(value)?,
818        };
819        let value = match &instruction.operand {
820            Operand::None => 0,
821            Operand::Int(value) if instruction.opcode == Opcode::Command => (value >> 16) & 255,
822            Operand::Int(value) => *value,
823            Operand::JumpTarget(target) => {
824                *positions
825                    .get(*target)
826                    .ok_or_else(|| invalid("Invalid branch target"))?
827                    - positions[i]
828                    - 1
829            }
830            Operand::StringCount(value) => i32::try_from(*value).map_err(invalid)?,
831            Operand::ArrayDef(slot, kind) => (slot << 16) | *kind as i32,
832            Operand::SwitchTable(index) => {
833                let table = script
834                    .switch_tables
835                    .get(*index as usize)
836                    .ok_or_else(|| invalid("Invalid switch table"))?;
837                let mut cases = Vec::with_capacity(table.len());
838                for (key, target) in table {
839                    let position = positions
840                        .get(*target)
841                        .ok_or_else(|| invalid("Invalid switch target"))?;
842                    cases.push((*key, *position - positions[i] - 1));
843                }
844                switches.push(cases);
845                i32::try_from(switches.len() - 1).map_err(invalid)?
846            }
847            Operand::Str(index) => {
848                if width != Width::String {
849                    return Err(invalid(
850                        "String instruction requires a string operand definition",
851                    ));
852                }
853                out.extend_from_slice(&opcode.to_be_bytes());
854                write_string(&mut out, &script.strings[*index as usize])?;
855                continue;
856            }
857            Operand::Long(value) => {
858                out.extend_from_slice(&opcode.to_be_bytes());
859                width.integer(&mut out, *value)?;
860                continue;
861            }
862        };
863        out.extend_from_slice(&opcode.to_be_bytes());
864        width.integer(&mut out, value as i64)?;
865    }
866    out.extend_from_slice(&count.to_be_bytes());
867    for counts in [
868        [
869            script.int_local_count,
870            script.string_local_count,
871            script.long_local_count,
872        ],
873        [
874            script.int_arg_count,
875            script.string_arg_count,
876            script.long_arg_count,
877        ],
878    ] {
879        for (kind, value) in [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long]
880            .into_iter()
881            .zip(counts)
882        {
883            if value != 0 && !format.local_types.contains(&kind) {
884                return Err(invalid(format!("Unsupported {kind:?} locals")));
885            }
886        }
887        for kind in &format.local_types {
888            let index = match kind {
889                BaseVarType::Integer => 0,
890                BaseVarType::String => 1,
891                BaseVarType::Long => 2,
892            };
893            out.extend_from_slice(&counts[index].to_be_bytes());
894        }
895    }
896    if !format.switches {
897        if !switches.is_empty() {
898            return Err(invalid(
899                "Switch tables are unsupported by input bytecode definitions",
900            ));
901        }
902        return Ok(out);
903    }
904    let start = out.len();
905    out.push(u8::try_from(switches.len()).map_err(invalid)?);
906    for table in switches {
907        out.extend_from_slice(&u16::try_from(table.len()).map_err(invalid)?.to_be_bytes());
908        for (key, offset) in table {
909            out.extend_from_slice(&key.to_be_bytes());
910            out.extend_from_slice(&offset.to_be_bytes());
911        }
912    }
913    let size = u16::try_from(out.len() - start).map_err(invalid)?;
914    out.extend_from_slice(&size.to_be_bytes());
915    Ok(out)
916}
917
918pub fn write_string(out: &mut Vec<u8>, text: &str) -> Result<()> {
919    const CP1252: &str = "€\u{81}‚ƒ„…†‡ˆ‰Š‹Œ\u{8d}Ž\u{8f}\u{90}‘’“”•–—˜™š›œ\u{9d}žŸ";
920    for ch in text.chars() {
921        let value = ch as u32;
922        if value == 0 {
923            return Err(invalid("NUL in clientscript string"));
924        }
925        if value < 128 || (160..=255).contains(&value) {
926            out.push(value as u8);
927        } else if let Some(index) = CP1252.chars().position(|c| c == ch) {
928            out.push(128 + index as u8);
929        } else {
930            return Err(invalid(format!(
931                "Character {ch:?} cannot be encoded in CP1252"
932            )));
933        }
934    }
935    out.push(0);
936    Ok(())
937}
938
939fn invalid(message: impl ToString) -> Error {
940    Error::new(ErrorKind::InvalidData, message.to_string())
941}
942
943#[cfg(test)]
944mod tests {
945    use super::*;
946
947    #[test]
948    fn clan_settings_take_their_opcodes_from_their_type() {
949        let dir = std::env::temp_dir().join(format!("runec_clan_{}", std::process::id()));
950        fs::create_dir_all(&dir).unwrap();
951        let file = dir.join("all.varclansetting");
952        fs::write(
953            &file,
954            "// 0\n[varclansetting_0]\ntype=int\n\n// 1\n[named]\ntype=long\n\n\
955             // 2\n[varclansetting_2]\ntype=string\n\n\
956             // 3\n[varclansetting_3]\ntype=byte:0x01\nbasevar=2\nstartbit=0\nendbit=0\n",
957        )
958        .unwrap();
959        fs::write(dir.join("varclansetting.pack"), "1=named\n").unwrap();
960        let mut registry = SymbolRegistry::new();
961        load_clan_settings(&mut registry, std::slice::from_ref(&file), &dir).unwrap();
962        for (name, id, expected) in [
963            ("varclansetting_0", 0, "clansetting_int"),
964            ("named", 1, "clansetting_long"),
965            ("varclansetting_2", 2, "clansetting_string"),
966            ("varclansetting_3", 3, "clansetting_varbit"),
967        ] {
968            let Some(SymbolKind::GameVar {
969                var_id, category, ..
970            }) = registry.lookup_game_var(name).map(|symbol| &symbol.kind)
971            else {
972                panic!("{name} is not registered");
973            };
974            assert_eq!((*var_id, category.as_str()), (id, expected), "{name}");
975        }
976        fs::remove_dir_all(dir).unwrap();
977    }
978
979    #[test]
980    fn a_varc_takes_the_type_its_file_declares() {
981        let dir = std::env::temp_dir().join(format!("runec-varc-types-{}", std::process::id()));
982        fs::create_dir_all(&dir).unwrap();
983        let file = dir.join("all.varc");
984        fs::write(
985            &file,
986            "// 5\n[varclient_5]\ntype=boolean\n\n// 6\n[varclient_6]\ntype=byte:0x65\n\n// 7\n[varclient_7]\n",
987        )
988        .unwrap();
989        let mut registry = SymbolRegistry::new();
990        for id in 5..8 {
991            registry.register_game_var(format!("varclient_{id}"), Type::Int, id, "varc".into());
992        }
993        load_varc_types(&mut registry, std::slice::from_ref(&file)).unwrap();
994        let declared = |name: &str| match registry.lookup_game_var(name).map(|symbol| &symbol.kind)
995        {
996            Some(SymbolKind::GameVar { var_type, .. }) => *var_type,
997            _ => panic!("{name} is not registered"),
998        };
999        assert_eq!(declared("varclient_5"), Type::Boolean);
1000        assert_eq!(declared("varclient_6"), Type::Int);
1001        assert_eq!(declared("varclient_7"), Type::Int);
1002        fs::remove_dir_all(dir).unwrap();
1003    }
1004
1005    #[test]
1006    fn a_transmit_name_is_never_the_dotted_alias() {
1007        let mut registry = SymbolRegistry::new();
1008        registry.register_game_var("bank_open".into(), Type::Int, 90, "varp".into());
1009        registry.register_game_var(".bank_open".into(), Type::Int, 90, "varp".into());
1010        assert_eq!(
1011            hooks::transmit_name(&registry, "varp", 90).as_deref(),
1012            Some("bank_open")
1013        );
1014    }
1015}