generation.rs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. use proc_macro2::TokenStream;
  2. use quote::{format_ident, quote, ToTokens};
  3. use crate::model::{MethodModel, ProtocolModel};
  4. impl ToTokens for ProtocolModel {
  5. fn to_tokens(&self, tokens: &mut TokenStream) {
  6. tokens.extend(self.generate_message_enum());
  7. tokens.extend(self.generate_state_traits());
  8. }
  9. }
  10. impl ProtocolModel {
  11. fn generate_message_enum(&self) -> TokenStream {
  12. let msg_lookup = self.msg_lookup();
  13. let get_variants = || msg_lookup.msg_iter().map(|msg| msg.msg_name());
  14. let variants0 = get_variants();
  15. let variants1 = get_variants();
  16. let variant_names = get_variants().map(|variant| variant.to_string());
  17. let msg_types = msg_lookup.msg_iter().map(|msg| msg.msg_type());
  18. let all_replies = msg_lookup.msg_iter().all(|msg| msg.is_reply());
  19. let enum_name = format_ident!("{}Msgs", self.def().name_def.name);
  20. let send_impl = if all_replies {
  21. quote! {}
  22. } else {
  23. quote! {
  24. impl ::btrun::SendMsg for #enum_name {}
  25. }
  26. };
  27. let proto_name = &self.def().name_def.name;
  28. let doc_comment = format!("Message type for the {proto_name} protocol.");
  29. quote! {
  30. #[doc = #doc_comment]
  31. #[derive(::serde::Serialize, ::serde::Deserialize)]
  32. pub enum #enum_name {
  33. #( #variants0(#msg_types) ),*
  34. }
  35. impl #enum_name {
  36. pub fn name(&self) -> &'static str {
  37. match self {
  38. #( Self::#variants1(_) => #variant_names),*
  39. }
  40. }
  41. }
  42. impl ::btrun::CallMsg for #enum_name {
  43. type Reply = Self;
  44. }
  45. #send_impl
  46. }
  47. }
  48. fn generate_state_traits(&self) -> TokenStream {
  49. let traits = self
  50. .states_iter()
  51. .map(|state| (state.name(), state.methods().values()));
  52. let mut tokens = TokenStream::new();
  53. for (trait_ident, methods) in traits {
  54. let method_tokens = methods.map(|x| x.generate_tokens());
  55. quote! {
  56. pub trait #trait_ident : Send + Sync {
  57. #( #method_tokens )*
  58. }
  59. }
  60. .to_tokens(&mut tokens);
  61. }
  62. tokens
  63. }
  64. }
  65. impl MethodModel {
  66. /// Generates the tokens for the code which implements this transition.
  67. fn generate_tokens(&self) -> TokenStream {
  68. let method_ident = self.name().as_ref();
  69. let msg_args = self.inputs().iter();
  70. let output_decls = self.outputs().iter().flat_map(|output| output.decl());
  71. let output_types = self.outputs().iter().flat_map(|output| output.type_name());
  72. let future_name = self.future();
  73. quote! {
  74. #( #output_decls )*
  75. type #future_name: Send + ::std::future::Future<Output = Result<( #( #output_types ),* )>>;
  76. fn #method_ident(self #( , #msg_args )*) -> Self::#future_name;
  77. }
  78. }
  79. }