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