Skip to content

Commit

Permalink
Update to new spec
Browse files Browse the repository at this point in the history
  • Loading branch information
VirxEC committed Oct 10, 2024
1 parent f0fee03 commit cfa2b72
Show file tree
Hide file tree
Showing 13 changed files with 302 additions and 105 deletions.
22 changes: 11 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rlbot-flatbuffers-py"
version = "0.9.1"
version = "0.10.0"
edition = "2021"
description = "A Python module implemented in Rust for serializing and deserializing RLBot's flatbuffers"
repository = "https://github.com/VirxEC/rlbot_flatbuffers_py"
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ All values are optional when creating a class and have the proper defaults.
```python
import rlbot_flatbuffers as flat

def handle_packet(packet: flat.GameTickPacket):
if packet.game_info.game_state_type not in {
flat.GameStateType.Active,
flat.GameStateType.Kickoff,
def handle_packet(packet: flat.GamePacket):
if packet.game_info.game_status not in {
flat.GameStatus.Active,
flat.GameStatus.Kickoff,
}:
# Return early if the game isn't active
return
Expand Down
49 changes: 38 additions & 11 deletions codegen/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,17 @@ impl EnumBindGenerator {
continue;
}

let definition = line_trim.trim_start_matches("pub const ").trim_end_matches(';');
let definition = line_trim
.trim_start_matches("pub const ")
.trim_end_matches(';');

let mut parts = definition.split(": Self = ");

let variable_name = parts.next()?;
let variable_value = parts.next()?.trim_start_matches("Self(").trim_end_matches(')');
let variable_value = parts
.next()?
.trim_start_matches("Self(")
.trim_end_matches(')');

types.push((variable_name, variable_value));

Expand All @@ -143,11 +148,14 @@ impl EnumBindGenerator {
let union_end_definition = "}\n";
let union_end = contents[union_start..].find(union_end_definition).unwrap();

let union_definition =
&contents[union_start + union_definition.len()..union_start + union_end - union_end_definition.len()];
let union_definition = &contents[union_start + union_definition.len()
..union_start + union_end - union_end_definition.len()];

for (line, variable) in union_definition.split('\n').zip(&mut custom_types) {
let line_trim = line.trim().trim_start_matches(&variable.name).trim_end_matches(',');
let line_trim = line
.trim()
.trim_start_matches(&variable.name)
.trim_end_matches(',');

if line_trim.is_empty() {
variable.value = None;
Expand All @@ -156,7 +164,9 @@ impl EnumBindGenerator {

variable.snake_case_name = camel_to_snake_case(variable.name.as_str());

let new_type = line_trim.trim_start_matches("(Box<").trim_end_matches("T>)");
let new_type = line_trim
.trim_start_matches("(Box<")
.trim_end_matches("T>)");
variable.value = Some(new_type.to_string());
}

Expand Down Expand Up @@ -225,7 +235,10 @@ impl Generator for EnumBindGenerator {
contents = contents.replace("\r\n", "\n");
}

contents = contents.replace("use self::flatbuffers", "use get_size::GetSize;\nuse self::flatbuffers");
contents = contents.replace(
"use self::flatbuffers",
"use get_size::GetSize;\nuse self::flatbuffers",
);

contents = contents.replace(
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]\n",
Expand All @@ -241,7 +254,10 @@ impl Generator for EnumBindGenerator {
self,
"#[pyclass(module = \"rlbot_flatbuffers\", frozen, hash, eq, eq_int)]"
);
write_str!(self, "#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]");
write_str!(
self,
"#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]"
);
write_fmt!(self, "pub enum {} {{", self.struct_name);
write_str!(self, " #[default]");

Expand All @@ -261,7 +277,11 @@ impl Generator for EnumBindGenerator {
self.struct_name,
self.struct_name
);
write_fmt!(self, " fn from(flat_t: flat::{}) -> Self {{", self.struct_name);
write_fmt!(
self,
" fn from(flat_t: flat::{}) -> Self {{",
self.struct_name
);
write_str!(self, " match flat_t {");

for variable_info in &self.types {
Expand All @@ -274,7 +294,10 @@ impl Generator for EnumBindGenerator {
);
}

write_str!(self, " v => unreachable!(\"Unknown value: {v:?}\"),");
write_str!(
self,
" v => unreachable!(\"Unknown value: {v:?}\"),"
);

write_str!(self, " }");
write_str!(self, " }");
Expand All @@ -289,7 +312,11 @@ impl Generator for EnumBindGenerator {
self.struct_name,
self.struct_name
);
write_fmt!(self, " fn from(py_type: &{}) -> Self {{", self.struct_name);
write_fmt!(
self,
" fn from(py_type: &{}) -> Self {{",
self.struct_name
);
write_str!(self, " match *py_type {");

for variable_info in &self.types {
Expand Down
38 changes: 28 additions & 10 deletions codegen/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ pub enum PythonBindType {

impl PythonBindType {
pub const BASE_TYPES: [&'static str; 6] = ["bool", "i32", "u32", "f32", "String", "u8"];
pub const FROZEN_TYPES: [&'static str; 18] = [
pub const FROZEN_TYPES: [&'static str; 21] = [
"FieldInfo",
"BoostPad",
"GoalInfo",
"GameTickPacket",
"GamePacket",
"PlayerInfo",
"ScoreInfo",
"BallInfo",
Expand All @@ -44,9 +44,17 @@ impl PythonBindType {
"BallPrediction",
"PredictionSlice",
"Physics",
"Vector2",
"ControllableInfo",
"ControllableTeamInfo",
];
pub const FROZEN_NEEDS_PY: [&'static str; 3] = ["GamePacket", "BallInfo", "CollisionShape"];
pub const UNIONS: [&'static str; 4] = [
"PlayerClass",
"CollisionShape",
"RelativeAnchor",
"RenderType",
];
pub const FROZEN_NEEDS_PY: [&'static str; 3] = ["GameTickPacket", "BallInfo", "CollisionShape"];
pub const UNIONS: [&'static str; 4] = ["PlayerClass", "CollisionShape", "RelativeAnchor", "RenderType"];

fn new(path: &Path) -> Option<Self> {
// get the filename without the extension
Expand Down Expand Up @@ -84,11 +92,15 @@ impl PythonBindType {
)?));
}

if let Some((types, enum_type)) = enums::EnumBindGenerator::get_types(&contents, &struct_name) {
if let Some((types, enum_type)) =
enums::EnumBindGenerator::get_types(&contents, &struct_name)
{
return Some(match enum_type {
enums::EnumType::Enum => {
Self::Enum(enums::EnumBindGenerator::new(filename.to_string(), struct_name, types)?)
}
enums::EnumType::Enum => Self::Enum(enums::EnumBindGenerator::new(
filename.to_string(),
struct_name,
types,
)?),
enums::EnumType::Union => Self::Union(unions::UnionBindGenerator::new(
filename.to_string(),
struct_name,
Expand Down Expand Up @@ -138,7 +150,10 @@ fn mod_rs_generator(type_data: &[PythonBindType]) -> io::Result<()> {

file_contents.push(Cow::Borrowed(""));

fs::write(format!("{PYTHON_OUT_FOLDER}/mod.rs"), file_contents.join("\n"))?;
fs::write(
format!("{PYTHON_OUT_FOLDER}/mod.rs"),
file_contents.join("\n"),
)?;

Ok(())
}
Expand All @@ -155,7 +170,10 @@ fn run_flatc() -> io::Result<()> {
let mut schema_folder = Path::new(SCHEMA_FOLDER);
if !schema_folder.exists() {
schema_folder = Path::new(SCHEMA_FOLDER_BACKUP);
assert!(schema_folder.exists(), "Could not find flatbuffers schema folder");
assert!(
schema_folder.exists(),
"Could not find flatbuffers schema folder"
);
}

let schema_folder_str = schema_folder.display();
Expand Down
44 changes: 38 additions & 6 deletions codegen/pyi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ pub fn generator(type_data: &[PythonBindType]) -> io::Result<()> {
);
write_str!(file, " \"\"\"");
write_str!(file, " def __int__(self) -> int: ...");
write_fmt!(file, " def __eq__(self, other: {type_name}) -> bool: ...");
write_fmt!(
file,
" def __eq__(self, other: {type_name}) -> bool: ..."
);
write_str!(file, " def __hash__(self) -> str: ...");
}
PythonBindType::Struct(gen) => {
Expand All @@ -111,6 +114,20 @@ pub fn generator(type_data: &[PythonBindType]) -> io::Result<()> {
python_types.push("bytes".to_string());
write_fmt!(file, " {variable_name}: bytes");
}
RustType::Vec(InnerVecType::Base(type_name)) => {
let python_type = if type_name == "bool" {
"bool"
} else if type_name == "i32" || type_name == "u32" {
"int"
} else if type_name == "f32" {
"float"
} else {
type_name
};

python_types.push(format!("Sequence[{python_type}]"));
write_fmt!(file, " {variable_name}: Sequence[{python_type}]");
}
RustType::Vec(InnerVecType::String) => {
python_types.push("Sequence[str]".to_string());
write_fmt!(file, " {variable_name}: Sequence[str]");
Expand Down Expand Up @@ -166,16 +183,26 @@ pub fn generator(type_data: &[PythonBindType]) -> io::Result<()> {
let union_types = type_data
.iter()
.find_map(|item| match item {
PythonBindType::Union(gen) if gen.struct_name() == type_name => {
Some(gen.types.iter().skip(1).map(|v| v.name.as_str()).collect::<Vec<_>>())
PythonBindType::Union(gen)
if gen.struct_name() == type_name =>
{
Some(
gen.types
.iter()
.skip(1)
.map(|v| v.name.as_str())
.collect::<Vec<_>>(),
)
}
_ => None,
})
.unwrap();
let types = union_types.join(" | ");
python_types.push(format!("Optional[{types}]"));
}
RustType::Custom(type_name) | RustType::Other(type_name) | RustType::Base(type_name) => {
RustType::Custom(type_name)
| RustType::Other(type_name)
| RustType::Base(type_name) => {
python_types.push(type_name.to_string());
write_fmt!(file, " {variable_name}: {type_name}");
}
Expand Down Expand Up @@ -212,7 +239,9 @@ pub fn generator(type_data: &[PythonBindType]) -> io::Result<()> {
"String" => Cow::Borrowed("\"\""),
"Vec<u8>" => Cow::Borrowed("b\"\""),
t => {
if python_type.starts_with("Optional") || t.starts_with("Option<") {
if python_type.starts_with("Optional")
|| t.starts_with("Option<")
{
Cow::Borrowed("None")
} else if t.starts_with("Vec<") {
Cow::Borrowed("[]")
Expand All @@ -228,7 +257,10 @@ pub fn generator(type_data: &[PythonBindType]) -> io::Result<()> {
}
};

write_fmt!(file, " {variable_name}: {python_type} = {default_value},");
write_fmt!(
file,
" {variable_name}: {python_type} = {default_value},"
);
}

write_str!(file, " ): ...");
Expand Down
Loading

0 comments on commit cfa2b72

Please sign in to comment.