ast.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #![allow(unused_attributes)]
  2. #![allow(dead_code)]
  3. #![allow(unused_imports)]
  4. #![allow(unused_results)]
  5. use crate::protobuf_file::template::{EnumTemplate, StructTemplate, RUST_TYPE_MAP};
  6. use crate::protobuf_file::{parse_crate_info_from_path, ProtoFile, ProtobufCrateContext};
  7. use crate::util::*;
  8. use fancy_regex::Regex;
  9. use flowy_ast::*;
  10. use lazy_static::lazy_static;
  11. use std::path::PathBuf;
  12. use std::{fs::File, io::Read, path::Path};
  13. use syn::Item;
  14. use walkdir::WalkDir;
  15. pub fn parse_protobuf_context_from(crate_paths: Vec<String>) -> Vec<ProtobufCrateContext> {
  16. let crate_infos = parse_crate_info_from_path(crate_paths);
  17. crate_infos
  18. .into_iter()
  19. .map(|crate_info| {
  20. let proto_output_path = crate_info.proto_output_path();
  21. let files = crate_info
  22. .proto_input_paths()
  23. .iter()
  24. .flat_map(|proto_crate_path| parse_files_protobuf(proto_crate_path, &proto_output_path))
  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: &Path, proto_output_path: &Path) -> 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 = format!("{}.proto", &file_name);
  52. let proto_file_path = path_string_with_component(proto_output_path, vec![&proto_file]);
  53. let proto_syntax = find_proto_syntax(proto_file_path.as_ref());
  54. let mut proto_content = String::new();
  55. // The types that are not defined in the current file.
  56. let mut ref_types: Vec<String> = vec![];
  57. structs.iter().for_each(|s| {
  58. let mut struct_template = StructTemplate::new();
  59. struct_template.set_message_struct_name(&s.name);
  60. s.fields
  61. .iter()
  62. .filter(|field| field.pb_attrs.pb_index().is_some())
  63. .for_each(|field| {
  64. ref_types.push(field.ty_as_str());
  65. struct_template.set_field(field);
  66. });
  67. let s = struct_template.render().unwrap();
  68. proto_content.push_str(s.as_ref());
  69. proto_content.push('\n');
  70. });
  71. let enums = get_ast_enums(&ast);
  72. enums.iter().for_each(|e| {
  73. let mut enum_template = EnumTemplate::new();
  74. enum_template.set_message_enum(e);
  75. let s = enum_template.render().unwrap();
  76. proto_content.push_str(s.as_ref());
  77. ref_types.push(e.name.clone());
  78. proto_content.push('\n');
  79. });
  80. if !enums.is_empty() || !structs.is_empty() {
  81. let structs: Vec<String> = structs.iter().map(|s| s.name.clone()).collect();
  82. let enums: Vec<String> = enums.iter().map(|e| e.name.clone()).collect();
  83. ref_types.retain(|s| !structs.contains(s));
  84. ref_types.retain(|s| !enums.contains(s));
  85. let info = ProtoFile {
  86. file_path: path.clone(),
  87. file_name: file_name.clone(),
  88. ref_types,
  89. structs,
  90. enums,
  91. syntax: proto_syntax,
  92. content: proto_content,
  93. };
  94. gen_proto_vec.push(info);
  95. }
  96. }
  97. gen_proto_vec
  98. }
  99. pub fn get_ast_structs(ast: &syn::File) -> Vec<Struct> {
  100. // let mut content = format!("{:#?}", &ast);
  101. // let mut file = File::create("./foo.txt").unwrap();
  102. // file.write_all(content.as_bytes()).unwrap();
  103. let ast_result = ASTResult::new();
  104. let mut proto_structs: Vec<Struct> = vec![];
  105. ast.items.iter().for_each(|item| {
  106. if let Item::Struct(item_struct) = item {
  107. let (_, fields) = struct_from_ast(&ast_result, &item_struct.fields);
  108. if fields
  109. .iter()
  110. .filter(|f| f.pb_attrs.pb_index().is_some())
  111. .count()
  112. > 0
  113. {
  114. proto_structs.push(Struct {
  115. name: item_struct.ident.to_string(),
  116. fields,
  117. });
  118. }
  119. }
  120. });
  121. ast_result.check().unwrap();
  122. proto_structs
  123. }
  124. pub fn get_ast_enums(ast: &syn::File) -> Vec<FlowyEnum> {
  125. let mut flowy_enums: Vec<FlowyEnum> = vec![];
  126. let ast_result = ASTResult::new();
  127. ast.items.iter().for_each(|item| {
  128. // https://docs.rs/syn/1.0.54/syn/enum.Item.html
  129. if let Item::Enum(item_enum) = item {
  130. let attrs = flowy_ast::enum_from_ast(
  131. &ast_result,
  132. &item_enum.ident,
  133. &item_enum.variants,
  134. &ast.attrs,
  135. );
  136. flowy_enums.push(FlowyEnum {
  137. name: item_enum.ident.to_string(),
  138. attrs,
  139. });
  140. }
  141. });
  142. ast_result.check().unwrap();
  143. flowy_enums
  144. }
  145. pub struct FlowyEnum<'a> {
  146. pub name: String,
  147. pub attrs: Vec<ASTEnumVariant<'a>>,
  148. }
  149. pub struct Struct<'a> {
  150. pub name: String,
  151. pub fields: Vec<ASTField<'a>>,
  152. }
  153. lazy_static! {
  154. static ref SYNTAX_REGEX: Regex = Regex::new("syntax.*;").unwrap();
  155. // static ref IMPORT_REGEX: Regex = Regex::new("(import\\s).*;").unwrap();
  156. }
  157. fn find_proto_syntax(path: &str) -> String {
  158. if !Path::new(path).exists() {
  159. return String::from("syntax = \"proto3\";\n");
  160. }
  161. let mut result = String::new();
  162. let mut file = File::open(path).unwrap();
  163. let mut content = String::new();
  164. file.read_to_string(&mut content).unwrap();
  165. content.lines().for_each(|line| {
  166. ////Result<Option<Match<'t>>>
  167. if let Ok(Some(m)) = SYNTAX_REGEX.find(line) {
  168. result.push_str(m.as_str());
  169. }
  170. // if let Ok(Some(m)) = IMPORT_REGEX.find(line) {
  171. // result.push_str(m.as_str());
  172. // result.push('\n');
  173. // }
  174. });
  175. result.push('\n');
  176. result
  177. }