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
157fn 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, ®istry)?);
217 }
218 PointerChecker::new_client(&scripts, ®istry)
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
270pub 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
321pub 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, ®istry));
448 Ok(registry)
449}
450
451fn 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
477pub(crate) fn load_clan_settings(
480 registry: &mut SymbolRegistry,
481 files: &[PathBuf],
482 pack: &Path,
483) -> Result<()> {
484 let ids: HashMap<String, i32> = fs::read_to_string(pack.join("varclansetting.pack"))
485 .unwrap_or_default()
486 .lines()
487 .filter_map(|line| line.split_once('='))
488 .filter_map(|(id, name)| Some((name.trim().to_owned(), id.parse().ok()?)))
489 .collect();
490 let mut add = |name: &str, ty: Option<&str>, bits: bool| -> Result<()> {
491 let id = ids
492 .get(name)
493 .copied()
494 .or_else(|| name.strip_prefix("varclansetting_")?.parse().ok())
495 .ok_or_else(|| invalid(format!("Unknown clan setting {name}")))?;
496 let (category, ty) = match (bits, ty) {
497 (true, _) => ("clansetting_varbit", Type::Int),
498 (_, Some("int" | "bit")) => ("clansetting_int", Type::Int),
499 (_, Some("long")) => ("clansetting_long", Type::Long),
500 (_, Some("clanforumqfc")) => ("clansetting_long", Type::ClanForumQfc),
501 (_, Some("string")) => ("clansetting_string", Type::String),
502 _ => {
503 return Err(invalid(format!(
504 "Clan setting {name} has no opcodes for type {ty:?}"
505 )));
506 }
507 };
508 registry.register_game_var(name.to_owned(), ty, id, category.to_owned());
509 Ok(())
510 };
511 for file in files {
512 if file.extension().is_none_or(|ext| ext != "varclansetting") {
513 continue;
514 }
515 let text = fs::read_to_string(file)?;
516 let mut section: Option<(&str, Option<&str>, bool)> = None;
517 for line in text.lines().map(str::trim) {
518 if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
519 if let Some((name, ty, bits)) = section {
520 add(name, ty, bits)?;
521 }
522 section = Some((name, None, false));
523 } else if let Some((_, ty, bits)) = &mut section {
524 if let Some(value) = line.strip_prefix("type=") {
525 *ty = Some(value.trim());
526 } else if line.starts_with("basevar=") {
527 *bits = true;
528 }
529 }
530 }
531 if let Some((name, ty, bits)) = section {
532 add(name, ty, bits)?;
533 }
534 }
535 Ok(())
536}
537
538pub fn parse(source: &str, path: &Path) -> Result<ScriptFile> {
539 let path = path.to_path_buf();
540 let tokens = Lexer::new(source, &path).tokenize().map_err(invalid)?;
541 Parser::new(tokens, &path).parse().map_err(invalid)
542}
543
544pub fn register(
545 file: &ScriptFile,
546 ids: &HashMap<String, i32>,
547 registry: &mut SymbolRegistry,
548) -> Result<()> {
549 for script in &file.scripts {
550 for statement in &script.body {
551 register_variables(statement, registry);
552 }
553 if !matches!(
554 script.trigger.as_str(),
555 "proc"
556 | "clientscript"
557 | "opworldmapelement1"
558 | "opworldmapelement2"
559 | "opworldmapelement3"
560 | "opworldmapelement4"
561 | "opworldmapelement5"
562 | "worldmapelementmouseover"
563 | "worldmapelementmouseleave"
564 | "worldmapelementmouserepeat"
565 ) {
566 return Err(invalid(format!(
567 "Invalid client trigger {}",
568 script.trigger
569 )));
570 }
571 let id = ids
572 .get(&format!("[{},{}]", script.trigger, script.name))
573 .or_else(|| ids.get(&script.name))
574 .copied()
575 .or_else(|| {
576 script
577 .name
578 .strip_prefix("clientscript_")
579 .and_then(|id| id.parse::<i32>().ok())
580 .filter(|id| *id >= 0)
581 })
582 .ok_or_else(|| invalid(format!("Missing clientscript ID for {}", script.name)))?;
583 registry
584 .preloaded_script_ids
585 .insert(format!("{}:{}", script.trigger, script.name), id);
586 registry.register_script(
587 script.name.clone(),
588 script.trigger.clone(),
589 script.params.iter().map(|p| p.param_type).collect(),
590 script.return_types.clone(),
591 );
592 registry
593 .stack_scripts
594 .insert(format!("{}:{}", script.trigger, script.name));
595 }
596 Ok(())
597}
598
599pub(crate) fn register_variables(statement: &Statement, registry: &mut SymbolRegistry) {
600 match statement {
601 Statement::VarDeclaration {
602 value: Some(value), ..
603 }
604 | Statement::Expression { expr: value, .. }
605 | Statement::ArrayDeclaration { size: value, .. } => {
606 register_expr_variables(value, registry)
607 }
608 Statement::Assignment { target, value, .. } => {
609 register_expr_variables(target, registry);
610 register_expr_variables(value, registry);
611 }
612 Statement::Return { values, .. } => {
613 for value in values {
614 register_expr_variables(value, registry);
615 }
616 }
617 Statement::If {
618 condition,
619 body,
620 else_if,
621 else_body,
622 ..
623 } => {
624 register_expr_variables(condition, registry);
625 for statement in body {
626 register_variables(statement, registry);
627 }
628 for (condition, body, _) in else_if {
629 register_expr_variables(condition, registry);
630 for statement in body {
631 register_variables(statement, registry);
632 }
633 }
634 if let Some(body) = else_body {
635 for statement in body {
636 register_variables(statement, registry);
637 }
638 }
639 }
640 Statement::While {
641 condition, body, ..
642 } => {
643 register_expr_variables(condition, registry);
644 for statement in body {
645 register_variables(statement, registry);
646 }
647 }
648 Statement::Switch {
649 expr,
650 cases,
651 default,
652 ..
653 } => {
654 register_expr_variables(expr, registry);
655 for case in cases {
656 for statement in &case.body {
657 register_variables(statement, registry);
658 }
659 }
660 if let Some(body) = default {
661 for statement in body {
662 register_variables(statement, registry);
663 }
664 }
665 }
666 _ => {}
667 }
668}
669
670fn register_expr_variables(expr: &Expr, registry: &mut SymbolRegistry) {
671 match expr {
672 Expr::GameVar(name, _) if registry.lookup_game_var(name).is_none() => {
673 for (kind, ty) in [
674 ("varp", Type::Int),
675 ("varbit", Type::Int),
676 ("varc", Type::Int),
677 ("varcs", Type::String),
678 ] {
679 if let Some(id) = name
680 .strip_prefix(&format!("{}_", hooks::var_placeholder(kind)))
681 .and_then(|s| s.parse::<u16>().ok())
682 {
683 registry.register_game_var(name.clone(), ty, id as i32, kind.to_owned());
684 }
685 }
686 }
687 Expr::ArrayAccess { index, .. } | Expr::Calc(index) => {
688 register_expr_variables(index, registry)
689 }
690 Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
691 register_expr_variables(lhs, registry);
692 register_expr_variables(rhs, registry);
693 }
694 Expr::CommandCall { name, args, .. } => {
695 if let Some(&explicit) = registry.hook_commands.get(name.trim_start_matches('.'))
696 && args.len() == 1 + usize::from(explicit)
697 && let Some(Expr::StringLiteral(text)) = args.first()
698 && let Ok(values) = hooks::parse(text)
699 {
700 if hooks::transmit_kind(name).is_some_and(|kind| kind.starts_with("var"))
701 && let Some(Expr::Tuple(transmits)) = values.get(2)
702 {
703 for value in transmits {
704 if let Expr::Identifier(name) = value {
705 register_expr_variables(&Expr::GameVar(name.clone(), 0), registry);
706 }
707 }
708 }
709 for value in &values {
710 register_expr_variables(value, registry);
711 }
712 }
713 for arg in args {
714 register_expr_variables(arg, registry);
715 }
716 }
717 Expr::ProcCall { args, .. }
718 | Expr::JumpCall { args, .. }
719 | Expr::MultiAssign(args, _)
720 | Expr::Tuple(args) => {
721 for arg in args {
722 register_expr_variables(arg, registry);
723 }
724 }
725 Expr::JoinedString { parts } => {
726 for part in parts {
727 if let StringPart::Expr(expr) = part {
728 register_expr_variables(expr, registry);
729 }
730 }
731 }
732 _ => {}
733 }
734}
735
736pub fn compile(
737 file: &ScriptFile,
738 path: &Path,
739 registry: &SymbolRegistry,
740 format: &Format,
741) -> Result<Vec<(i32, Vec<u8>)>> {
742 let scripts = checked_codegen(file, path, registry)?;
743 PointerChecker::new_client(&scripts, registry)
744 .run()
745 .print_all();
746 scripts
747 .into_iter()
748 .map(|compiled| Ok((compiled.id, encode(&compiled, format)?)))
749 .collect()
750}
751
752fn checked_codegen(
753 file: &ScriptFile,
754 path: &Path,
755 registry: &SymbolRegistry,
756) -> Result<Vec<CompiledScript>> {
757 let mut checker = TypeChecker::new(registry);
758 checker.check_file(file, path);
759 if checker.diagnostics.has_errors() {
760 return Err(invalid(
761 checker
762 .diagnostics
763 .errors()
764 .iter()
765 .map(ToString::to_string)
766 .collect::<Vec<_>>()
767 .join("\n"),
768 ));
769 }
770 codegen(file, path, registry)
771}
772
773pub(crate) fn codegen(
774 file: &ScriptFile,
775 path: &Path,
776 registry: &SymbolRegistry,
777) -> Result<Vec<CompiledScript>> {
778 let mut diagnostics = crate::diagnostics::DiagnosticsCollector::new();
779 let compiled = crate::compiler::compile_file(file, path, registry, true, &mut diagnostics);
780 if diagnostics.has_errors() {
781 return Err(invalid(
782 diagnostics
783 .errors()
784 .iter()
785 .map(ToString::to_string)
786 .collect::<Vec<_>>()
787 .join(
788 "
789",
790 ),
791 ));
792 }
793 Ok(compiled)
794}
795
796pub fn encode(script: &CompiledScript, format: &Format) -> Result<Vec<u8>> {
797 encode_named(script, "", format)
798}
799
800pub fn encode_named(script: &CompiledScript, name: &str, format: &Format) -> Result<Vec<u8>> {
801 let mut positions = Vec::with_capacity(script.instructions.len() + 1);
802 let mut count = 0;
803 for instruction in &script.instructions {
804 positions.push(count);
805 if instruction.opcode != Opcode::LineNumber {
806 count += 1;
807 }
808 }
809 positions.push(count);
810 let mut out = Vec::new();
811 write_string(&mut out, name)?;
812 let mut switches = Vec::new();
813 for (i, instruction) in script.instructions.iter().enumerate() {
814 if instruction.opcode == Opcode::LineNumber {
815 continue;
816 }
817 if instruction.opcode == Opcode::Raw {
818 let Operand::Long(value) = instruction.operand else {
819 return Err(invalid("Invalid raw client instruction"));
820 };
821 let opcode = (value >> 32) as u16;
822 let operand = value as i32;
823 out.extend_from_slice(&opcode.to_be_bytes());
824 format.width(opcode).integer(&mut out, operand as i64)?;
825 continue;
826 }
827 let (opcode, width) = match instruction.opcode {
828 Opcode::Command => match instruction.operand {
829 Operand::Int(value) => (value as u16, format.width(value as u16)),
830 _ => return Err(invalid("Unresolved client command")),
831 },
832 value => format.instruction(value)?,
833 };
834 let value = match &instruction.operand {
835 Operand::None => 0,
836 Operand::Int(value) if instruction.opcode == Opcode::Command => (value >> 16) & 255,
837 Operand::Int(value) => *value,
838 Operand::JumpTarget(target) => {
839 *positions
840 .get(*target)
841 .ok_or_else(|| invalid("Invalid branch target"))?
842 - positions[i]
843 - 1
844 }
845 Operand::StringCount(value) => i32::try_from(*value).map_err(invalid)?,
846 Operand::ArrayDef(slot, kind) => (slot << 16) | *kind as i32,
847 Operand::SwitchTable(index) => {
848 let table = script
849 .switch_tables
850 .get(*index as usize)
851 .ok_or_else(|| invalid("Invalid switch table"))?;
852 let mut cases = Vec::with_capacity(table.len());
853 for (key, target) in table {
854 let position = positions
855 .get(*target)
856 .ok_or_else(|| invalid("Invalid switch target"))?;
857 cases.push((*key, *position - positions[i] - 1));
858 }
859 switches.push(cases);
860 i32::try_from(switches.len() - 1).map_err(invalid)?
861 }
862 Operand::Str(index) => {
863 if width != Width::String {
864 return Err(invalid(
865 "String instruction requires a string operand definition",
866 ));
867 }
868 out.extend_from_slice(&opcode.to_be_bytes());
869 write_string(&mut out, &script.strings[*index as usize])?;
870 continue;
871 }
872 Operand::Long(value) => {
873 out.extend_from_slice(&opcode.to_be_bytes());
874 width.integer(&mut out, *value)?;
875 continue;
876 }
877 };
878 out.extend_from_slice(&opcode.to_be_bytes());
879 width.integer(&mut out, value as i64)?;
880 }
881 out.extend_from_slice(&count.to_be_bytes());
882 for counts in [
883 [
884 script.int_local_count,
885 script.string_local_count,
886 script.long_local_count,
887 ],
888 [
889 script.int_arg_count,
890 script.string_arg_count,
891 script.long_arg_count,
892 ],
893 ] {
894 for (kind, value) in [BaseVarType::Integer, BaseVarType::String, BaseVarType::Long]
895 .into_iter()
896 .zip(counts)
897 {
898 if value != 0 && !format.local_types.contains(&kind) {
899 return Err(invalid(format!("Unsupported {kind:?} locals")));
900 }
901 }
902 for kind in &format.local_types {
903 let index = match kind {
904 BaseVarType::Integer => 0,
905 BaseVarType::String => 1,
906 BaseVarType::Long => 2,
907 };
908 out.extend_from_slice(&counts[index].to_be_bytes());
909 }
910 }
911 if !format.switches {
912 if !switches.is_empty() {
913 return Err(invalid(
914 "Switch tables are unsupported by input bytecode definitions",
915 ));
916 }
917 return Ok(out);
918 }
919 let start = out.len();
920 out.push(u8::try_from(switches.len()).map_err(invalid)?);
921 for table in switches {
922 out.extend_from_slice(&u16::try_from(table.len()).map_err(invalid)?.to_be_bytes());
923 for (key, offset) in table {
924 out.extend_from_slice(&key.to_be_bytes());
925 out.extend_from_slice(&offset.to_be_bytes());
926 }
927 }
928 let size = u16::try_from(out.len() - start).map_err(invalid)?;
929 out.extend_from_slice(&size.to_be_bytes());
930 Ok(out)
931}
932
933pub fn write_string(out: &mut Vec<u8>, text: &str) -> Result<()> {
934 const CP1252: &str = "€\u{81}‚ƒ„…†‡ˆ‰Š‹Œ\u{8d}Ž\u{8f}\u{90}‘’“”•–—˜™š›œ\u{9d}žŸ";
935 for ch in text.chars() {
936 let value = ch as u32;
937 if value == 0 {
938 return Err(invalid("NUL in clientscript string"));
939 }
940 if value < 128 || (160..=255).contains(&value) {
941 out.push(value as u8);
942 } else if let Some(index) = CP1252.chars().position(|c| c == ch) {
943 out.push(128 + index as u8);
944 } else {
945 return Err(invalid(format!(
946 "Character {ch:?} cannot be encoded in CP1252"
947 )));
948 }
949 }
950 out.push(0);
951 Ok(())
952}
953
954fn invalid(message: impl ToString) -> Error {
955 Error::new(ErrorKind::InvalidData, message.to_string())
956}
957
958#[cfg(test)]
959mod tests {
960 use super::*;
961
962 #[test]
963 fn clan_settings_take_their_opcodes_from_their_type() {
964 let dir = std::env::temp_dir().join(format!("runec_clan_{}", std::process::id()));
965 fs::create_dir_all(&dir).unwrap();
966 let file = dir.join("all.varclansetting");
967 fs::write(
968 &file,
969 "// 0\n[varclansetting_0]\ntype=int\n\n// 1\n[named]\ntype=long\n\n\
970 // 2\n[varclansetting_2]\ntype=string\n\n\
971 // 3\n[varclansetting_3]\ntype=byte:0x01\nbasevar=2\nstartbit=0\nendbit=0\n",
972 )
973 .unwrap();
974 fs::write(dir.join("varclansetting.pack"), "1=named\n").unwrap();
975 let mut registry = SymbolRegistry::new();
976 load_clan_settings(&mut registry, std::slice::from_ref(&file), &dir).unwrap();
977 for (name, id, expected) in [
978 ("varclansetting_0", 0, "clansetting_int"),
979 ("named", 1, "clansetting_long"),
980 ("varclansetting_2", 2, "clansetting_string"),
981 ("varclansetting_3", 3, "clansetting_varbit"),
982 ] {
983 let Some(SymbolKind::GameVar {
984 var_id, category, ..
985 }) = registry.lookup_game_var(name).map(|symbol| &symbol.kind)
986 else {
987 panic!("{name} is not registered");
988 };
989 assert_eq!((*var_id, category.as_str()), (id, expected), "{name}");
990 }
991 fs::remove_dir_all(dir).unwrap();
992 }
993
994 #[test]
995 fn a_varc_takes_the_type_its_file_declares() {
996 let dir = std::env::temp_dir().join(format!("runec-varc-types-{}", std::process::id()));
997 fs::create_dir_all(&dir).unwrap();
998 let file = dir.join("all.varc");
999 fs::write(
1000 &file,
1001 "// 5\n[varclient_5]\ntype=boolean\n\n// 6\n[varclient_6]\ntype=byte:0x65\n\n// 7\n[varclient_7]\n",
1002 )
1003 .unwrap();
1004 let mut registry = SymbolRegistry::new();
1005 for id in 5..8 {
1006 registry.register_game_var(format!("varclient_{id}"), Type::Int, id, "varc".into());
1007 }
1008 load_varc_types(&mut registry, std::slice::from_ref(&file)).unwrap();
1009 let declared = |name: &str| match registry.lookup_game_var(name).map(|symbol| &symbol.kind)
1010 {
1011 Some(SymbolKind::GameVar { var_type, .. }) => *var_type,
1012 _ => panic!("{name} is not registered"),
1013 };
1014 assert_eq!(declared("varclient_5"), Type::Boolean);
1015 assert_eq!(declared("varclient_6"), Type::Int);
1016 assert_eq!(declared("varclient_7"), Type::Int);
1017 fs::remove_dir_all(dir).unwrap();
1018 }
1019
1020 #[test]
1021 fn a_transmit_name_is_never_the_dotted_alias() {
1022 let mut registry = SymbolRegistry::new();
1023 registry.register_game_var("bank_open".into(), Type::Int, 90, "varp".into());
1024 registry.register_game_var(".bank_open".into(), Type::Int, 90, "varp".into());
1025 assert_eq!(
1026 hooks::transmit_name(®istry, "varp", 90).as_deref(),
1027 Some("bank_open")
1028 );
1029 }
1030}