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