Skip to content

Commit

Permalink
Generate client traits
Browse files Browse the repository at this point in the history
  • Loading branch information
morr0ne committed Aug 16, 2024
1 parent aa5849f commit 52b235e
Show file tree
Hide file tree
Showing 4 changed files with 8,308 additions and 57 deletions.
43 changes: 40 additions & 3 deletions gen/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use heck::ToUpperCamelCase;
use proc_macro2::TokenStream;
use quote::quote;
use tracing::debug;

use crate::{
parser::Protocol,
utils::{description_to_docs, make_ident},
utils::{description_to_docs, make_ident, write_enums},
};

pub fn generate_client_code(protocols: &[Protocol]) -> TokenStream {
Expand All @@ -15,8 +16,43 @@ pub fn generate_client_code(protocols: &[Protocol]) -> TokenStream {

let mut inner_modules = Vec::new();

for _interface in &protocol.interfaces {
inner_modules.push(quote! {})
for interface in &protocol.interfaces {
let docs = description_to_docs(interface.description.as_ref());
let module_name = make_ident(&interface.name);
let trait_name = make_ident(interface.name.to_upper_camel_case());
let trait_docs = format!("Trait to implement the {} interface. See the module level documentation for more info", interface.name);

let name = &interface.name;
let version = &interface.version;

let enums = write_enums(&interface);


inner_modules.push(quote! {
#(#docs)*
pub mod #module_name {
#(#enums)*

#[doc = #trait_docs]
pub trait #trait_name: crate::client::Dispatcher {
const INTERFACE: &'static str = #name;
const VERSION: u32 = #version;

async fn handle_event(
&self,
message: &mut crate::wire::Message,
) -> crate::client::Result<()> {
match message.opcode {
// #(#dispatchers),*
_ => Err(crate::client::Error::UnknownOpcode),
}
}

// #(#requests)*
// #(#events)*
}
}
})
}

let docs = description_to_docs(protocol.description.as_ref());
Expand All @@ -31,6 +67,7 @@ pub fn generate_client_code(protocols: &[Protocol]) -> TokenStream {
}

quote! {
#![allow(async_fn_in_trait)]
#(#modules)*
}
}
17 changes: 17 additions & 0 deletions src/client/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::io;

use crate::wire::DecodeError;

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Internal Error")]
Internal,
#[error("Malformed")]
Malformed(#[from] DecodeError),
#[error("Io Error: {0}")]
IoError(#[from] io::Error),
#[error("Unknown Opcode")]
UnknownOpcode,
}

pub type Result<T, E = Error> = core::result::Result<T, E>;
9 changes: 9 additions & 0 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
mod error;
pub mod protocol;

pub use error::{Error, Result};

use crate::wire::Socket;

pub trait Dispatcher {
fn socket(&mut self) -> &mut Socket;
}
Loading

0 comments on commit 52b235e

Please sign in to comment.