Refactor code writer and fix minor things

Also added the ability to specify which files should be generated based on their file type.

E.g. `cs2-dumper.exe -f hpp,json`
This commit is contained in:
a2x
2024-04-10 00:53:17 +10:00
parent 541f4acf1d
commit 8b1ecb7afb
19 changed files with 559 additions and 669 deletions

View File

@@ -1,59 +1,49 @@
use std::collections::BTreeMap;
use std::fmt::Write;
use std::fmt::{self, Write};
use super::{Button, CodeGen, Results};
use super::{Button, CodeWriter, Formatter};
use crate::error::Result;
impl CodeWriter for Vec<Button> {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.block("namespace CS2Dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
impl CodeGen for Vec<Button> {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
fmt.block("public static class Buttons", false, |fmt| {
for button in self {
writeln!(
fmt,
"public const nint {} = {:#X};",
button.name, button.value
)?;
}
fmt.block("public static class Buttons", false, |fmt| {
for button in self {
writeln!(
fmt,
"public const nint {} = {:#X};",
button.name, button.value
)?;
}
Ok(())
})
})?;
Ok(())
Ok(())
})
})
}
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
fmt.block("namespace buttons", false, |fmt| {
for button in self {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X};",
button.name, button.value
)?;
}
fmt.block("namespace buttons", false, |fmt| {
for button in self {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X};",
button.name, button.value
)?;
}
Ok(())
})
})?;
Ok(())
Ok(())
})
})
}
fn to_json(&self, _results: &Results, _indent_size: usize) -> Result<String> {
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
let content = {
let buttons: BTreeMap<_, _> = self
.iter()
@@ -63,35 +53,28 @@ impl CodeGen for Vec<Button> {
BTreeMap::from_iter([("client.dll", buttons)])
};
serde_json::to_string_pretty(&content).map_err(Into::into)
fmt.write_str(&serde_json::to_string_pretty(&content).expect("failed to serialize"))
}
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: client.dll")?;
fmt.block("pub mod buttons", false, |fmt| {
for button in self {
let mut name = button.name.clone();
fmt.block("pub mod buttons", false, |fmt| {
for button in self {
let mut name = button.name.clone();
if name == "use" {
name = format!("r#{}", name);
}
writeln!(fmt, "pub const {}: usize = {:#X};", name, button.value)?;
if name == "use" {
name = format!("r#{}", name);
}
Ok(())
})
})?;
writeln!(fmt, "pub const {}: usize = {:#X};", name, button.value)?;
}
Ok(())
Ok(())
})
})
}
}

View File

@@ -1,15 +1,9 @@
use std::fmt::{self, Write};
#[derive(Debug)]
pub struct Formatter<'a> {
/// Write destination.
pub out: &'a mut String,
/// Number of spaces per indentation level.
pub indent_size: usize,
/// Current indentation level.
pub indent_level: usize,
out: &'a mut String,
indent_size: usize,
indent_level: usize,
}
impl<'a> Formatter<'a> {
@@ -34,17 +28,17 @@ impl<'a> Formatter<'a> {
Ok(())
}
pub fn indent<F, R>(&mut self, f: F) -> R
pub fn indent<F>(&mut self, f: F) -> fmt::Result
where
F: FnOnce(&mut Self) -> R,
F: FnOnce(&mut Self) -> fmt::Result,
{
self.indent_level += 1;
let ret = f(self);
f(self)?;
self.indent_level -= 1;
ret
Ok(())
}
#[inline]

View File

@@ -1,30 +1,54 @@
use std::collections::BTreeMap;
use std::fmt::Write;
use std::fmt::{self, Write};
use heck::{AsPascalCase, AsSnakeCase};
use super::{CodeGen, InterfaceMap, Results};
use super::{slugify, CodeWriter, Formatter, InterfaceMap};
use crate::error::Result;
impl CodeWriter for InterfaceMap {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.block("namespace CS2Dumper.Interfaces", false, |fmt| {
for (module_name, ifaces) in self {
writeln!(fmt, "// Module: {}", module_name)?;
impl CodeGen for InterfaceMap {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper.Interfaces", false, |fmt| {
fmt.block(
&format!("public static class {}", AsPascalCase(slugify(module_name))),
false,
|fmt| {
for iface in ifaces {
writeln!(
fmt,
"public const nint {} = {:#X};",
iface.name, iface.value
)?;
}
Ok(())
},
)?;
}
Ok(())
})
}
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace interfaces", false, |fmt| {
for (module_name, ifaces) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!(
"public static class {}",
AsPascalCase(Self::slugify(module_name))
),
&format!("namespace {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for iface in ifaces {
writeln!(
fmt,
"public const nint {} = {:#X};",
"constexpr std::ptrdiff_t {} = {:#X};",
iface.name, iface.value
)?;
}
@@ -35,48 +59,11 @@ impl CodeGen for InterfaceMap {
}
Ok(())
})?;
Ok(())
})
})
}
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace interfaces", false, |fmt| {
for (module_name, ifaces) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("namespace {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for iface in ifaces {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X};",
iface.name, iface.value
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
})
}
fn to_json(&self, _results: &Results, _indent_size: usize) -> Result<String> {
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
let content: BTreeMap<_, _> = self
.iter()
.map(|(module_name, ifaces)| {
@@ -89,43 +76,36 @@ impl CodeGen for InterfaceMap {
})
.collect();
serde_json::to_string_pretty(&content).map_err(Into::into)
fmt.write_str(&serde_json::to_string_pretty(&content).expect("failed to serialize"))
}
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod interfaces", false, |fmt| {
for (module_name, ifaces) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod interfaces", false, |fmt| {
for (module_name, ifaces) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for iface in ifaces {
writeln!(
fmt,
"pub const {}: usize = {:#X};",
iface.name, iface.value
)?;
}
fmt.block(
&format!("pub mod {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for iface in ifaces {
writeln!(
fmt,
"pub const {}: usize = {:#X};",
iface.name, iface.value
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
Ok(())
})
})
}
}

View File

@@ -1,4 +1,4 @@
use std::fmt::Write;
use std::fmt::{self, Write};
use std::fs;
use std::path::Path;
@@ -6,7 +6,7 @@ use chrono::{DateTime, Utc};
use memflow::prelude::v1::*;
use serde::{Deserialize, Serialize};
use serde::Serialize;
use serde_json::json;
use formatter::Formatter;
@@ -30,216 +30,160 @@ enum Item<'a> {
}
impl<'a> Item<'a> {
fn generate(&self, results: &Results, indent_size: usize, file_ext: &str) -> Result<String> {
fn write(&self, fmt: &mut Formatter<'a>, file_ext: &str) -> fmt::Result {
match file_ext {
"cs" => self.to_cs(results, indent_size),
"hpp" => self.to_hpp(results, indent_size),
"json" => self.to_json(results, indent_size),
"rs" => self.to_rs(results, indent_size),
_ => unreachable!(),
"cs" => self.write_cs(fmt),
"hpp" => self.write_hpp(fmt),
"json" => self.write_json(fmt),
"rs" => self.write_rs(fmt),
_ => unimplemented!(),
}
}
}
trait CodeGen {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String>;
trait CodeWriter {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result;
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String>;
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result;
fn to_json(&self, results: &Results, indent_size: usize) -> Result<String>;
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result;
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String>;
/// Replaces non-alphanumeric characters in a string with underscores.
#[inline]
fn slugify(input: &str) -> String {
input.replace(|c: char| !c.is_alphanumeric(), "_")
}
fn write_content<F>(&self, results: &Results, indent_size: usize, f: F) -> Result<String>
where
F: FnOnce(&mut Formatter<'_>) -> Result<()>,
{
let mut buf = String::new();
let mut fmt = Formatter::new(&mut buf, indent_size);
results.write_banner(&mut fmt)?;
f(&mut fmt)?;
Ok(buf)
}
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result;
}
impl<'a> CodeGen for Item<'a> {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
impl<'a> CodeWriter for Item<'a> {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
Item::Buttons(buttons) => buttons.to_cs(results, indent_size),
Item::Interfaces(ifaces) => ifaces.to_cs(results, indent_size),
Item::Offsets(offsets) => offsets.to_cs(results, indent_size),
Item::Schemas(schemas) => schemas.to_cs(results, indent_size),
Item::Buttons(buttons) => buttons.write_cs(fmt),
Item::Interfaces(ifaces) => ifaces.write_cs(fmt),
Item::Offsets(offsets) => offsets.write_cs(fmt),
Item::Schemas(schemas) => schemas.write_cs(fmt),
}
}
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String> {
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
Item::Buttons(buttons) => buttons.to_hpp(results, indent_size),
Item::Interfaces(ifaces) => ifaces.to_hpp(results, indent_size),
Item::Offsets(offsets) => offsets.to_hpp(results, indent_size),
Item::Schemas(schemas) => schemas.to_hpp(results, indent_size),
Item::Buttons(buttons) => buttons.write_hpp(fmt),
Item::Interfaces(ifaces) => ifaces.write_hpp(fmt),
Item::Offsets(offsets) => offsets.write_hpp(fmt),
Item::Schemas(schemas) => schemas.write_hpp(fmt),
}
}
fn to_json(&self, results: &Results, indent_size: usize) -> Result<String> {
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
Item::Buttons(buttons) => buttons.to_json(results, indent_size),
Item::Interfaces(ifaces) => ifaces.to_json(results, indent_size),
Item::Offsets(offsets) => offsets.to_json(results, indent_size),
Item::Schemas(schemas) => schemas.to_json(results, indent_size),
Item::Buttons(buttons) => buttons.write_json(fmt),
Item::Interfaces(ifaces) => ifaces.write_json(fmt),
Item::Offsets(offsets) => offsets.write_json(fmt),
Item::Schemas(schemas) => schemas.write_json(fmt),
}
}
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
Item::Buttons(buttons) => buttons.to_rs(results, indent_size),
Item::Interfaces(ifaces) => ifaces.to_rs(results, indent_size),
Item::Offsets(offsets) => offsets.to_rs(results, indent_size),
Item::Schemas(schemas) => schemas.to_rs(results, indent_size),
Item::Buttons(buttons) => buttons.write_rs(fmt),
Item::Interfaces(ifaces) => ifaces.write_rs(fmt),
Item::Offsets(offsets) => offsets.write_rs(fmt),
Item::Schemas(schemas) => schemas.write_rs(fmt),
}
}
}
#[derive(Deserialize, Serialize)]
pub struct Results {
/// Timestamp of the dump.
pub timestamp: DateTime<Utc>,
/// List of buttons to dump.
pub buttons: Vec<Button>,
/// Map of interfaces to dump.
pub interfaces: InterfaceMap,
/// Map of offsets to dump.
pub offsets: OffsetMap,
/// Map of schema classes/enums to dump.
pub schemas: SchemaMap,
pub struct Output<'a> {
file_types: &'a Vec<String>,
indent_size: usize,
out_dir: &'a Path,
result: &'a AnalysisResult,
timestamp: DateTime<Utc>,
}
impl Results {
impl<'a> Output<'a> {
pub fn new(
buttons: Vec<Button>,
interfaces: InterfaceMap,
offsets: OffsetMap,
schemas: SchemaMap,
) -> Self {
Self {
timestamp: Utc::now(),
buttons,
interfaces,
offsets,
schemas,
}
}
pub fn dump_all<P: AsRef<Path>>(
&self,
process: &mut IntoProcessInstanceArcBox<'_>,
out_dir: P,
file_types: &'a Vec<String>,
indent_size: usize,
) -> Result<()> {
// TODO: Make this user-configurable.
const FILE_EXTS: &[&str] = &["cs", "hpp", "json", "rs"];
out_dir: &'a Path,
result: &'a AnalysisResult,
) -> Result<Self> {
fs::create_dir_all(&out_dir)?;
Ok(Self {
file_types,
indent_size,
out_dir,
result,
timestamp: Utc::now(),
})
}
pub fn dump_all(&self, process: &mut IntoProcessInstanceArcBox<'_>) -> Result<()> {
let items = [
("buttons", Item::Buttons(&self.buttons)),
("interfaces", Item::Interfaces(&self.interfaces)),
("offsets", Item::Offsets(&self.offsets)),
("buttons", Item::Buttons(&self.result.buttons)),
("interfaces", Item::Interfaces(&self.result.interfaces)),
("offsets", Item::Offsets(&self.result.offsets)),
];
for (file_name, item) in &items {
self.dump_item(item, &out_dir, indent_size, FILE_EXTS, file_name)?;
self.dump_item(file_name, item)?;
}
self.dump_info(process, &out_dir)?;
self.dump_schemas(&out_dir, indent_size, FILE_EXTS)?;
self.dump_schemas()?;
self.dump_info(process)?;
Ok(())
}
fn dump_file<P: AsRef<Path>>(
&self,
out_dir: P,
file_name: &str,
file_ext: &str,
content: &str,
) -> Result<()> {
let file_path = out_dir.as_ref().join(format!("{}.{}", file_name, file_ext));
fn dump_info(&self, process: &mut IntoProcessInstanceArcBox<'_>) -> Result<()> {
let file_path = self.out_dir.join("info.json");
fs::write(&file_path, content)?;
Ok(())
}
fn dump_item<P: AsRef<Path>>(
&self,
item: &Item,
out_dir: P,
indent_size: usize,
file_exts: &[&str],
file_name: &str,
) -> Result<()> {
for ext in file_exts {
let content = item.generate(self, indent_size, ext)?;
self.dump_file(&out_dir, file_name, ext, &content)?;
}
Ok(())
}
fn dump_info<P: AsRef<Path>>(
&self,
process: &mut IntoProcessInstanceArcBox<'_>,
out_dir: P,
) -> Result<()> {
let content = &serde_json::to_string_pretty(&json!({
"timestamp": self.timestamp.to_rfc3339(),
"build_number": self.read_build_number(process).unwrap_or(0),
}))?;
self.dump_file(&out_dir, "info", "json", &content)
}
fn dump_schemas<P: AsRef<Path>>(
&self,
out_dir: P,
indent_size: usize,
file_exts: &[&str],
) -> Result<()> {
for (module_name, (classes, enums)) in &self.schemas {
let map = SchemaMap::from([(module_name.clone(), (classes.clone(), enums.clone()))]);
let item = Item::Schemas(&map);
self.dump_item(&item, &out_dir, indent_size, file_exts, &module_name)?;
}
Ok(())
}
fn read_build_number(&self, process: &mut IntoProcessInstanceArcBox<'_>) -> Result<u32> {
self.offsets
let build_number = self
.result
.offsets
.iter()
.find_map(|(module_name, offsets)| {
let module = process.module_by_name(module_name).ok()?;
let offset = offsets.iter().find(|(name, _)| *name == "dwBuildNumber")?;
let offset = offsets.iter().find(|(name, _)| *name == "dwBuildNumber")?.1;
process.read(module.base + offset.1).ok()
process.read::<u32>(module.base + offset).ok()
})
.ok_or(Error::Other("unable to read build number"))
.ok_or(Error::Other("unable to read build number"))?;
let content = serde_json::to_string_pretty(&json!({
"timestamp": self.timestamp.to_rfc3339(),
"build_number": build_number,
}))?;
fs::write(&file_path, &content)?;
Ok(())
}
fn dump_item(&self, file_name: &str, item: &Item) -> Result<()> {
for file_type in self.file_types {
let mut out = String::new();
let mut fmt = Formatter::new(&mut out, self.indent_size);
if file_type != "json" {
self.write_banner(&mut fmt)?;
}
item.write(&mut fmt, file_type)?;
let file_path = self.out_dir.join(format!("{}.{}", file_name, file_type));
fs::write(&file_path, out)?;
}
Ok(())
}
fn dump_schemas(&self) -> Result<()> {
for (module_name, (classes, enums)) in &self.result.schemas {
let map = SchemaMap::from([(module_name.clone(), (classes.clone(), enums.clone()))]);
self.dump_item(module_name, &Item::Schemas(&map))?;
}
Ok(())
}
fn write_banner(&self, fmt: &mut Formatter<'_>) -> Result<()> {
@@ -249,3 +193,7 @@ impl Results {
Ok(())
}
}
fn slugify(input: &str) -> String {
input.replace(|c: char| !c.is_alphanumeric(), "_")
}

View File

@@ -1,27 +1,47 @@
use std::fmt::Write;
use std::fmt::{self, Write};
use heck::{AsPascalCase, AsSnakeCase};
use super::{CodeGen, OffsetMap, Results};
use super::{slugify, CodeWriter, Formatter, OffsetMap};
use crate::error::Result;
impl CodeWriter for OffsetMap {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.block("namespace CS2Dumper.Offsets", false, |fmt| {
for (module_name, offsets) in self {
writeln!(fmt, "// Module: {}", module_name)?;
impl CodeGen for OffsetMap {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper.Offsets", false, |fmt| {
fmt.block(
&format!("public static class {}", AsPascalCase(slugify(module_name))),
false,
|fmt| {
for (name, value) in offsets {
writeln!(fmt, "public const nint {} = {:#X};", name, value)?;
}
Ok(())
},
)?;
}
Ok(())
})
}
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace offsets", false, |fmt| {
for (module_name, offsets) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!(
"public static class {}",
AsPascalCase(Self::slugify(module_name))
),
&format!("namespace {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for (name, value) in offsets {
writeln!(fmt, "public const nint {} = {:#X};", name, value)?;
writeln!(fmt, "constexpr std::ptrdiff_t {} = {:#X};", name, value)?;
}
Ok(())
@@ -30,81 +50,37 @@ impl CodeGen for OffsetMap {
}
Ok(())
})?;
Ok(())
})
})
}
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace offsets", false, |fmt| {
for (module_name, offsets) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("namespace {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for (name, value) in offsets {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X};",
name, value
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
})
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.write_str(&serde_json::to_string_pretty(self).expect("failed to serialize"))
}
fn to_json(&self, _results: &Results, _indent_size: usize) -> Result<String> {
serde_json::to_string_pretty(self).map_err(Into::into)
}
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod offsets", false, |fmt| {
for (module_name, offsets) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod offsets", false, |fmt| {
for (module_name, offsets) in self {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for (name, value) in offsets {
writeln!(fmt, "pub const {}: usize = {:#X};", name, value)?;
}
fmt.block(
&format!("pub mod {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for (name, value) in offsets {
writeln!(fmt, "pub const {}: usize = {:#X};", name, value)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
Ok(())
})
})
}
}

View File

@@ -5,33 +5,113 @@ use heck::{AsPascalCase, AsSnakeCase};
use serde_json::json;
use super::{CodeGen, Formatter, Results, SchemaMap};
use super::{slugify, CodeWriter, Formatter, SchemaMap};
use crate::analysis::ClassMetadata;
use crate::error::Result;
impl CodeGen for SchemaMap {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper.Schemas", false, |fmt| {
impl CodeWriter for SchemaMap {
fn write_cs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.block("namespace CS2Dumper.Schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!("public static class {}", AsPascalCase(slugify(module_name))),
false,
|fmt| {
for enum_ in enums {
let type_name = match enum_.alignment {
1 => "byte",
2 => "ushort",
4 => "uint",
8 => "ulong",
_ => continue,
};
writeln!(fmt, "// Alignment: {}", enum_.alignment)?;
writeln!(fmt, "// Members count: {}", enum_.size)?;
fmt.block(
&format!("public enum {} : {}", slugify(&enum_.name), type_name),
false,
|fmt| {
// TODO: Handle the case where multiple members share
// the same value.
let members = enum_
.members
.iter()
.map(|member| {
format!("{} = {:#X}", member.name, member.value)
})
.collect::<Vec<_>>()
.join(",\n");
writeln!(fmt, "{}", members)
},
)?;
}
for class in classes {
let parent_name = class
.parent
.as_ref()
.map(|parent| slugify(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
writeln!(fmt, "// Fields count: {}", class.fields.len())?;
write_metadata(fmt, &class.metadata)?;
fmt.block(
&format!("public static class {}", slugify(&class.name)),
false,
|fmt| {
for field in &class.fields {
writeln!(
fmt,
"public const nint {} = {:#X}; // {}",
field.name, field.offset, field.type_name
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
})
}
fn write_hpp(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!(
"public static class {}",
AsPascalCase(Self::slugify(module_name))
),
&format!("namespace {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for enum_ in enums {
let type_name = match enum_.alignment {
1 => "byte",
2 => "ushort",
4 => "uint",
8 => "ulong",
1 => "uint8_t",
2 => "uint16_t",
4 => "uint32_t",
8 => "uint64_t",
_ => continue,
};
@@ -39,12 +119,8 @@ impl CodeGen for SchemaMap {
writeln!(fmt, "// Members count: {}", enum_.size)?;
fmt.block(
&format!(
"public enum {} : {}",
Self::slugify(&enum_.name),
type_name
),
false,
&format!("enum class {} : {}", slugify(&enum_.name), type_name),
true,
|fmt| {
// TODO: Handle the case where multiple members share
// the same value.
@@ -66,7 +142,7 @@ impl CodeGen for SchemaMap {
let parent_name = class
.parent
.as_ref()
.map(|parent| Self::slugify(&parent.name))
.map(|parent| slugify(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
@@ -75,13 +151,13 @@ impl CodeGen for SchemaMap {
write_metadata(fmt, &class.metadata)?;
fmt.block(
&format!("public static class {}", Self::slugify(&class.name)),
&format!("namespace {}", slugify(&class.name)),
false,
|fmt| {
for field in &class.fields {
writeln!(
fmt,
"public const nint {} = {:#X}; // {}",
"constexpr std::ptrdiff_t {} = {:#X}; // {}",
field.name, field.offset, field.type_name
)?;
}
@@ -97,107 +173,11 @@ impl CodeGen for SchemaMap {
}
Ok(())
})?;
Ok(())
})
})
}
fn to_hpp(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#pragma once\n")?;
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!("namespace {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for enum_ in enums {
let type_name = match enum_.alignment {
1 => "uint8_t",
2 => "uint16_t",
4 => "uint32_t",
8 => "uint64_t",
_ => continue,
};
writeln!(fmt, "// Alignment: {}", enum_.alignment)?;
writeln!(fmt, "// Members count: {}", enum_.size)?;
fmt.block(
&format!(
"enum class {} : {}",
Self::slugify(&enum_.name),
type_name
),
true,
|fmt| {
// TODO: Handle the case where multiple members share
// the same value.
let members = enum_
.members
.iter()
.map(|member| {
format!("{} = {:#X}", member.name, member.value)
})
.collect::<Vec<_>>()
.join(",\n");
writeln!(fmt, "{}", members)
},
)?;
}
for class in classes {
let parent_name = class
.parent
.as_ref()
.map(|parent| Self::slugify(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
writeln!(fmt, "// Fields count: {}", class.fields.len())?;
write_metadata(fmt, &class.metadata)?;
fmt.block(
&format!("namespace {}", Self::slugify(&class.name)),
false,
|fmt| {
for field in &class.fields {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X}; // {}",
field.name, field.offset, field.type_name
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
})
}
fn to_json(&self, _results: &Results, _indent_size: usize) -> Result<String> {
fn write_json(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
let content: BTreeMap<_, _> = self
.iter()
.map(|(module_name, (classes, enums))| {
@@ -231,7 +211,7 @@ impl CodeGen for SchemaMap {
.collect();
(
Self::slugify(&class.name),
slugify(&class.name),
json!({
"parent": class.parent.as_ref().map(|parent| &parent.name),
"fields": fields,
@@ -259,7 +239,7 @@ impl CodeGen for SchemaMap {
};
(
Self::slugify(&enum_.name),
slugify(&enum_.name),
json!({
"alignment": enum_.alignment,
"type": type_name,
@@ -279,110 +259,106 @@ impl CodeGen for SchemaMap {
})
.collect();
serde_json::to_string_pretty(&content).map_err(Into::into)
fmt.write_str(&serde_json::to_string_pretty(&content).expect("failed to serialize"))
}
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, unused)]\n"
)?;
fn write_rs(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(Self::slugify(module_name))),
false,
|fmt| {
for enum_ in enums {
let type_name = match enum_.alignment {
1 => "u8",
2 => "u16",
4 => "u32",
8 => "u64",
_ => continue,
};
fmt.block(
&format!("pub mod {}", AsSnakeCase(slugify(module_name))),
false,
|fmt| {
for enum_ in enums {
let type_name = match enum_.alignment {
1 => "u8",
2 => "u16",
4 => "u32",
8 => "u64",
_ => continue,
};
writeln!(fmt, "// Alignment: {}", enum_.alignment)?;
writeln!(fmt, "// Members count: {}", enum_.size)?;
writeln!(fmt, "// Alignment: {}", enum_.alignment)?;
writeln!(fmt, "// Members count: {}", enum_.size)?;
fmt.block(
&format!(
"#[repr({})]\npub enum {}",
type_name,
Self::slugify(&enum_.name),
),
false,
|fmt| {
// TODO: Handle the case where multiple members share
// the same value.
let members = enum_
.members
.iter()
.map(|member| {
format!(
"{} = {}",
member.name,
if member.value == -1 {
format!("{}::MAX", type_name)
} else {
format!("{:#X}", member.value)
}
)
})
.collect::<Vec<_>>()
.join(",\n");
fmt.block(
&format!(
"#[repr({})]\npub enum {}",
type_name,
slugify(&enum_.name),
),
false,
|fmt| {
// TODO: Handle the case where multiple members share
// the same value.
let members = enum_
.members
.iter()
.map(|member| {
format!(
"{} = {}",
member.name,
if member.value == -1 {
format!("{}::MAX", type_name)
} else {
format!("{:#X}", member.value)
}
)
})
.collect::<Vec<_>>()
.join(",\n");
writeln!(fmt, "{}", members)
},
)?;
}
writeln!(fmt, "{}", members)
},
)?;
}
for class in classes {
let parent_name = class
.parent
.as_ref()
.map(|parent| Self::slugify(&parent.name))
.unwrap_or_else(|| "None".to_string());
for class in classes {
let parent_name = class
.parent
.as_ref()
.map(|parent| slugify(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
writeln!(fmt, "// Fields count: {}", class.fields.len())?;
writeln!(fmt, "// Parent: {}", parent_name)?;
writeln!(fmt, "// Fields count: {}", class.fields.len())?;
write_metadata(fmt, &class.metadata)?;
write_metadata(fmt, &class.metadata)?;
fmt.block(
&format!("pub mod {}", Self::slugify(&class.name)),
false,
|fmt| {
for field in &class.fields {
writeln!(
fmt,
"pub const {}: usize = {:#X}; // {}",
field.name, field.offset, field.type_name
)?;
}
fmt.block(
&format!("pub mod {}", slugify(&class.name)),
false,
|fmt| {
for field in &class.fields {
writeln!(
fmt,
"pub const {}: usize = {:#X}; // {}",
field.name, field.offset, field.type_name
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
},
)?;
}
Ok(())
})
})?;
Ok(())
Ok(())
})
})
}
}