| 1 | use proc_macro2::TokenStream; |
| 2 | use protobuf::reflect::{FieldDescriptor, ReflectValueRef}; |
| 3 | use quote::quote; |
| 4 | use serde_json::Map; |
| 5 | use std::io::{BufWriter, Write}; |
| 6 | use std::{env, fs::File, path::Path}; |
| 7 | |
| 8 | fn main() { |
| 9 | // First we load up the descriptor using the protobuf crate |
| 10 | // so that we can do reflection on it. |
| 11 | let descriptors = protobuf_parse::Parser::new() |
| 12 | .pure() |
| 13 | .include(".") |
| 14 | .input("Lib/axisregistry/axes.proto") |
| 15 | .file_descriptor_set() |
| 16 | .expect("Could not parse axes.proto"); |
| 17 | let protofile = descriptors.file.first().expect("No file in descriptor"); |
| 18 | let descriptor = protobuf::reflect::FileDescriptor::new_dynamic(protofile.clone(), &[]) |
| 19 | .expect("Could not create descriptor"); |
| 20 | |
| 21 | // Now we use the prost crate to compile them, so that we can |
| 22 | // generate Rust structs. |
| 23 | let mut config = prost_build::Config::new(); |
| 24 | // config.boxed(".google.axes.LanguageProto.sample_text"); |
| 25 | // config.boxed(".google.axes.LanguageProto.exemplar_chars"); |
| 26 | |
| 27 | // The reflection can tell us what messages we have, so we can configure |
| 28 | // them to be deserializable with serde |
| 29 | for message in descriptor.messages() { |
| 30 | config.type_attribute( |
| 31 | message.full_name(), |
| 32 | "#[derive(serde::Serialize, serde::Deserialize)]", |
| 33 | ); |
| 34 | } |
| 35 | // Let's make our structs; this produces google.axes.rs |
| 36 | config |
| 37 | .compile_protos(&["Lib/axisregistry/axes.proto"], &["Lib/axisregistry/"]) |
| 38 | .expect("Could not compile axes.proto"); |
| 39 | |
| 40 | let path = Path::new(&env::var("OUT_DIR").unwrap()).join("data.rs"); |
| 41 | let mut file = BufWriter::new(File::create(path).unwrap()); |
| 42 | let mut output = quote! { use std::collections::BTreeMap; use std::sync::LazyLock; }; |
| 43 | |
| 44 | output.extend(serialize_a_structure( |
| 45 | ".AxisProto", |
| 46 | "Lib/axisregistry/data/*.textproto", |
| 47 | "AXES", |
| 48 | &descriptor, |
| 49 | )); |
| 50 | |
| 51 | // file.write_all(output.to_string().as_bytes()) |
| 52 | // .expect("Could not write to file"); |
| 53 | |
| 54 | let abstract_file: syn::File = syn::parse2(output).expect("Could not parse output"); |
| 55 | let formatted = prettyplease::unparse(&abstract_file); |
| 56 | file.write_all(formatted.as_bytes()) |
| 57 | .expect("Could not write to file"); |
| 58 | } |
| 59 | |
| 60 | fn serialize_a_structure( |
| 61 | proto_name: &str, |
| 62 | pathglob: &str, |
| 63 | output_variable: &str, |
| 64 | descriptor: &protobuf::reflect::FileDescriptor, |
| 65 | ) -> TokenStream { |
| 66 | let proto = descriptor |
| 67 | .message_by_full_name(proto_name) |
| 68 | .unwrap_or_else(|| panic!("No {} message", proto_name)); |
| 69 | let files: Vec<std::path::PathBuf> = glob::glob(pathglob) |
| 70 | .expect("Failed to read glob pattern") |
| 71 | .flatten() |
| 72 | .collect(); |
| 73 | let name: TokenStream = proto.name().parse().unwrap(); |
| 74 | let variable: TokenStream = output_variable.parse().unwrap(); |
| 75 | let mut map = Map::new(); |
| 76 | for file in files.into_iter() { |
| 77 | serialize_file(file, &proto, &mut map); |
| 78 | } |
| 79 | let json_var: TokenStream = format!("__{}", output_variable).parse().unwrap(); |
| 80 | let docmsg = format!("A map of all the {} objects", name); |
| 81 | let json_dump = serde_json::to_string(&map).expect("Could not serialize"); |
| 82 | quote! { |
| 83 | static #json_var: &str = #json_dump; |
| 84 | |
| 85 | #[doc = #docmsg] |
| 86 | pub static #variable: LazyLock<BTreeMap<String, Box<#name>>> = LazyLock::new(|| { |
| 87 | serde_json::from_str(#json_var).expect("Could not deserialize") |
| 88 | }); |
| 89 | } |
| 90 | } |
| 91 | fn serialize_file( |
| 92 | path: std::path::PathBuf, |
| 93 | descriptor: &protobuf::reflect::MessageDescriptor, |
| 94 | value: &mut Map<String, serde_json::Value>, |
| 95 | ) { |
| 96 | let mut message = descriptor.new_instance(); |
| 97 | let message_mut = message.as_mut(); |
| 98 | let input = std::fs::read_to_string(&path).expect("Could not read file"); |
| 99 | protobuf::text_format::merge_from_str(message_mut, &input) |
| 100 | .unwrap_or_else(|e| panic!("Could not parse file {:?}: {:?}", path, e)); |
| 101 | let message = serialize_message(message_mut); |
| 102 | value.insert( |
| 103 | message.get("tag").unwrap().as_str().unwrap().to_string(), |
| 104 | message, |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | fn serialize_message(message: &dyn protobuf::MessageDyn) -> serde_json::Value { |
| 109 | let descriptor = message.descriptor_dyn(); |
| 110 | // let descriptor_name: TokenStream = descriptor.name().parse().unwrap(); |
| 111 | let mut output = Map::new(); |
| 112 | for field in descriptor.fields() { |
| 113 | let field_name: TokenStream = field.name().parse().unwrap(); |
| 114 | let field_contents = serialize_field(&field, message); |
| 115 | output.insert(field_name.to_string(), field_contents); |
| 116 | } |
| 117 | output.into() |
| 118 | } |
| 119 | |
| 120 | fn serialize_field( |
| 121 | field: &FieldDescriptor, |
| 122 | message: &dyn protobuf::MessageDyn, |
| 123 | ) -> serde_json::Value { |
| 124 | if field.is_repeated() { |
| 125 | let v: Vec<serde_json::Value> = field |
| 126 | .get_repeated(message) |
| 127 | .into_iter() |
| 128 | .map(|value| serialize_field_value(field, value)) |
| 129 | .collect(); |
| 130 | v.into() |
| 131 | } else if field.is_required() { |
| 132 | serialize_field_value(field, field.get_singular(message).unwrap()) |
| 133 | } else if field.has_field(message) { |
| 134 | let value = serialize_field_value(field, field.get_singular(message).unwrap()); |
| 135 | value.into() |
| 136 | } else { |
| 137 | serde_json::Value::Null |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | fn serialize_field_value(_field: &FieldDescriptor, value: ReflectValueRef) -> serde_json::Value { |
| 142 | match value { |
| 143 | ReflectValueRef::Bool(value) => value.into(), |
| 144 | ReflectValueRef::I32(value) => value.into(), |
| 145 | ReflectValueRef::I64(value) => value.into(), |
| 146 | ReflectValueRef::U32(value) => value.into(), |
| 147 | ReflectValueRef::U64(value) => value.into(), |
| 148 | ReflectValueRef::F32(value) => value.into(), |
| 149 | ReflectValueRef::F64(value) => value.into(), |
| 150 | ReflectValueRef::String(value) => value.into(), |
| 151 | ReflectValueRef::Bytes(value) => value.into(), |
| 152 | ReflectValueRef::Enum(_value, _ix) => unimplemented!(), |
| 153 | ReflectValueRef::Message(value) => serialize_message(&*value), |
| 154 | } |
| 155 | } |