ast.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #![allow(unused_attributes)]
  2. #![allow(dead_code)]
  3. #![allow(unused_imports)]
  4. #![allow(unused_results)]
  5. use crate::code_gen::protobuf_file::template::{EnumTemplate, StructTemplate};
  6. use crate::code_gen::protobuf_file::{parse_crate_info_from_path, ProtoFile, ProtobufCrateContext};
  7. use crate::code_gen::util::*;
  8. use fancy_regex::Regex;
  9. use flowy_ast::*;
  10. use lazy_static::lazy_static;
  11. use std::{fs::File, io::Read, path::Path};
  12. use syn::Item;
  13. use walkdir::WalkDir;
  14. pub fn parse_crate_protobuf(crate_paths: Vec<String>) -> Vec<ProtobufCrateContext> {
  15. let crate_infos = parse_crate_info_from_path(crate_paths);
  16. crate_infos
  17. .into_iter()
  18. .map(|crate_info| {
  19. let proto_output_dir = crate_info.proto_output_dir();
  20. let files = crate_info
  21. .proto_paths
  22. .iter()
  23. .map(|proto_crate_path| parse_files_protobuf(proto_crate_path, &proto_output_dir))
  24. .flatten()
  25. .collect::<Vec<ProtoFile>>();
  26. ProtobufCrateContext::from_crate_info(crate_info, files)
  27. })
  28. .collect::<Vec<ProtobufCrateContext>>()
  29. }
  30. fn parse_files_protobuf(proto_crate_path: &str, proto_output_dir: &str) -> Vec<ProtoFile> {
  31. let mut gen_proto_vec: Vec<ProtoFile> = vec![];
  32. // file_stem https://doc.rust-lang.org/std/path/struct.Path.html#method.file_stem
  33. for (path, file_name) in WalkDir::new(proto_crate_path)
  34. .into_iter()
  35. .filter_entry(|e| !is_hidden(e))
  36. .filter_map(|e| e.ok())
  37. .filter(|e| !e.file_type().is_dir())
  38. .map(|e| {
  39. let path = e.path().to_str().unwrap().to_string();
  40. let file_name = e.path().file_stem().unwrap().to_str().unwrap().to_string();
  41. (path, file_name)
  42. })
  43. {
  44. if file_name == "mod" {
  45. continue;
  46. }
  47. // https://docs.rs/syn/1.0.54/syn/struct.File.html
  48. let ast = syn::parse_file(read_file(&path).unwrap().as_ref())
  49. .unwrap_or_else(|_| panic!("Unable to parse file at {}", path));
  50. let structs = get_ast_structs(&ast);
  51. let proto_file_path = format!("{}/{}.proto", &proto_output_dir, &file_name);
  52. let mut proto_file_content = parse_or_init_proto_file(proto_file_path.as_ref());
  53. structs.iter().for_each(|s| {
  54. let mut struct_template = StructTemplate::new();
  55. struct_template.set_message_struct_name(&s.name);
  56. s.fields.iter().filter(|f| f.attrs.pb_index().is_some()).for_each(|f| {
  57. struct_template.set_field(f);
  58. });
  59. let s = struct_template.render().unwrap();
  60. proto_file_content.push_str(s.as_ref());
  61. proto_file_content.push('\n');
  62. });
  63. let enums = get_ast_enums(&ast);
  64. enums.iter().for_each(|e| {
  65. let mut enum_template = EnumTemplate::new();
  66. enum_template.set_message_enum(e);
  67. let s = enum_template.render().unwrap();
  68. proto_file_content.push_str(s.as_ref());
  69. proto_file_content.push('\n');
  70. });
  71. if !enums.is_empty() || !structs.is_empty() {
  72. let info = ProtoFile {
  73. file_path: path.clone(),
  74. file_name: file_name.clone(),
  75. structs: structs.iter().map(|s| s.name.clone()).collect(),
  76. enums: enums.iter().map(|e| e.name.clone()).collect(),
  77. generated_content: proto_file_content.clone(),
  78. };
  79. gen_proto_vec.push(info);
  80. }
  81. }
  82. gen_proto_vec
  83. }
  84. pub fn parse_or_init_proto_file(path: &str) -> String {
  85. let mut proto_file_content = String::new();
  86. let imported_content = find_proto_file_import(path);
  87. proto_file_content.push_str(imported_content.as_ref());
  88. proto_file_content.push('\n');
  89. proto_file_content
  90. }
  91. pub fn get_ast_structs(ast: &syn::File) -> Vec<Struct> {
  92. // let mut content = format!("{:#?}", &ast);
  93. // let mut file = File::create("./foo.txt").unwrap();
  94. // file.write_all(content.as_bytes()).unwrap();
  95. let ctxt = Ctxt::new();
  96. let mut proto_structs: Vec<Struct> = vec![];
  97. ast.items.iter().for_each(|item| {
  98. if let Item::Struct(item_struct) = item {
  99. let (_, fields) = struct_from_ast(&ctxt, &item_struct.fields);
  100. if fields.iter().filter(|f| f.attrs.pb_index().is_some()).count() > 0 {
  101. proto_structs.push(Struct {
  102. name: item_struct.ident.to_string(),
  103. fields,
  104. });
  105. }
  106. }
  107. });
  108. ctxt.check().unwrap();
  109. proto_structs
  110. }
  111. pub fn get_ast_enums(ast: &syn::File) -> Vec<FlowyEnum> {
  112. let mut flowy_enums: Vec<FlowyEnum> = vec![];
  113. let ctxt = Ctxt::new();
  114. ast.items.iter().for_each(|item| {
  115. // https://docs.rs/syn/1.0.54/syn/enum.Item.html
  116. if let Item::Enum(item_enum) = item {
  117. let attrs = flowy_ast::enum_from_ast(&ctxt, &item_enum.ident, &item_enum.variants, &ast.attrs);
  118. flowy_enums.push(FlowyEnum {
  119. name: item_enum.ident.to_string(),
  120. attrs,
  121. });
  122. }
  123. });
  124. ctxt.check().unwrap();
  125. flowy_enums
  126. }
  127. pub struct FlowyEnum<'a> {
  128. pub name: String,
  129. pub attrs: Vec<ASTEnumVariant<'a>>,
  130. }
  131. pub struct Struct<'a> {
  132. pub name: String,
  133. pub fields: Vec<ASTField<'a>>,
  134. }
  135. lazy_static! {
  136. static ref SYNTAX_REGEX: Regex = Regex::new("syntax.*;").unwrap();
  137. static ref IMPORT_REGEX: Regex = Regex::new("(import\\s).*;").unwrap();
  138. }
  139. fn find_proto_file_import(path: &str) -> String {
  140. let mut result = String::new();
  141. if !Path::new(path).exists() {
  142. // log::error!("{} not exist", path);
  143. result = String::from("syntax = \"proto3\";");
  144. return result;
  145. }
  146. let mut file = File::open(path).unwrap();
  147. let mut content = String::new();
  148. file.read_to_string(&mut content).unwrap();
  149. content.lines().for_each(|line| {
  150. ////Result<Option<Match<'t>>>
  151. if let Ok(Some(m)) = SYNTAX_REGEX.find(line) {
  152. result.push_str(m.as_str());
  153. result.push('\n');
  154. }
  155. if let Ok(Some(m)) = IMPORT_REGEX.find(line) {
  156. result.push_str(m.as_str());
  157. result.push('\n');
  158. }
  159. });
  160. result
  161. }