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