struct_template.rs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. use crate::util::get_tera;
  2. use flowy_ast::*;
  3. use phf::phf_map;
  4. use tera::Context;
  5. // Protobuf data type : https://developers.google.com/protocol-buffers/docs/proto3
  6. static RUST_TYPE_MAP: phf::Map<&'static str, &'static str> = phf_map! {
  7. "String" => "string",
  8. "i64" => "int64",
  9. "i32" => "int32",
  10. "u64" => "uint64",
  11. "u32" => "uint32",
  12. "Vec" => "repeated",
  13. "f64" => "double",
  14. "HashMap" => "map",
  15. };
  16. pub struct StructTemplate {
  17. context: Context,
  18. fields: Vec<String>,
  19. }
  20. #[allow(dead_code)]
  21. impl StructTemplate {
  22. pub fn new() -> Self {
  23. return StructTemplate {
  24. context: Context::new(),
  25. fields: vec![],
  26. };
  27. }
  28. pub fn set_message_struct_name(&mut self, name: &str) {
  29. self.context.insert("struct_name", name);
  30. }
  31. pub fn set_field(&mut self, field: &ASTField) {
  32. // {{ field_type }} {{ field_name }} = {{index}};
  33. let name = field.name().unwrap().to_string();
  34. let index = field.attrs.pb_index().unwrap();
  35. let ty: &str = &field.ty_as_str();
  36. let mut mapped_ty: &str = ty;
  37. if RUST_TYPE_MAP.contains_key(ty) {
  38. mapped_ty = RUST_TYPE_MAP[ty];
  39. }
  40. match field.bracket_category {
  41. Some(ref category) => match category {
  42. BracketCategory::Opt => self.fields.push(format!(
  43. "oneof one_of_{} {{ {} {} = {}; }};",
  44. name, mapped_ty, name, index
  45. )),
  46. BracketCategory::Map((k, v)) => {
  47. let key: &str = k;
  48. let value: &str = v;
  49. self.fields.push(format!(
  50. // map<string, string> attrs = 1;
  51. "map<{}, {}> {} = {};",
  52. RUST_TYPE_MAP.get(key).unwrap_or(&key),
  53. RUST_TYPE_MAP.get(value).unwrap_or(&value),
  54. name,
  55. index
  56. ));
  57. }
  58. BracketCategory::Vec => {
  59. let bracket_ty: &str = &field.bracket_ty.as_ref().unwrap().to_string();
  60. if mapped_ty == "u8" && bracket_ty == "Vec" {
  61. self.fields.push(format!("bytes {} = {};", name, index))
  62. } else {
  63. self.fields.push(format!(
  64. "{} {} {} = {};",
  65. RUST_TYPE_MAP[bracket_ty], mapped_ty, name, index
  66. ))
  67. }
  68. }
  69. BracketCategory::Other => self
  70. .fields
  71. .push(format!("{} {} = {};", mapped_ty, name, index)),
  72. },
  73. None => {}
  74. }
  75. }
  76. pub fn render(&mut self) -> Option<String> {
  77. self.context.insert("fields", &self.fields);
  78. let tera = get_tera("proto/template/proto_file");
  79. match tera.render("struct.tera", &self.context) {
  80. Ok(r) => Some(r),
  81. Err(e) => {
  82. log::error!("{:?}", e);
  83. None
  84. }
  85. }
  86. }
  87. }