1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
mod data;
mod gen;
mod util;
use self::data::{Package, PackageOrMessage};
use self::gen::PackageOrMessageExt as _;
use crate::Result;
use ::itertools::Itertools;
use ::proc_macro2::TokenStream;
use ::quote::quote;
use ::stable_puroro::protobuf::google::protobuf::compiler::code_generator_response::File;
use ::stable_puroro::protobuf::google::protobuf::compiler::CodeGeneratorResponse;
use ::stable_puroro::protobuf::google::protobuf::FileDescriptorProtoView;
use ::std::iter;
use ::std::rc::Rc;
#[derive(Default)]
pub struct CodegenOptions {
pub root_module_name: Option<String>,
pub root_file_name: Option<String>,
pub puroro_library_path: Option<String>,
}
pub fn generate_file_names_and_tokens<'a>(
files: impl Iterator<Item = &'a FileDescriptorProtoView>,
options: &CodegenOptions,
) -> Result<impl IntoIterator<Item = (String, TokenStream)>> {
let root_package = Package::new_root(files);
let file_generating_items =
iter::once(Ok(Rc::clone(&root_package) as Rc<dyn PackageOrMessage>))
.chain(
root_package
.all_child_packages()?
.into_iter()
.map(|p| Ok(p as Rc<dyn PackageOrMessage>)),
)
.chain(
root_package
.all_child_messages()?
.into_iter()
.filter_map(|m| {
match m.should_generate_module_file() {
Ok(true) => Some(Ok(m as Rc<dyn PackageOrMessage>)),
Ok(false) => None,
Err(e) => Some(Err(e)),
}
}),
);
file_generating_items
.map_ok(|item| {
let file_name = item
.module_file_path(
options.root_module_name.as_deref(),
options.root_file_name.as_deref(),
)?
.to_string();
let file_content = item.gen_module_file(options.puroro_library_path.as_deref())?;
Ok((file_name, quote! { #file_content }))
})
.map(|rr| rr.flatten())
.collect::<Result<Vec<_>>>()
}
pub fn generate_output_file_protos<'a>(
files: impl Iterator<Item = &'a FileDescriptorProtoView>,
options: &CodegenOptions,
) -> Result<CodeGeneratorResponse> {
let mut cgr = CodeGeneratorResponse::default();
*cgr.file_mut() = generate_file_names_and_tokens(files, options)?
.into_iter()
.map(|(file_name, ts)| {
let formatted = if let Ok(syn_file) = syn::parse2::<syn::File>(ts.clone()) {
prettyplease::unparse(&syn_file)
} else {
eprintln!("Generated code error!");
format!("{}", ts)
};
let mut output_file = File::default();
*output_file.name_mut() = file_name;
*output_file.content_mut() = formatted;
Ok(output_file)
})
.collect::<Result<Vec<_>>>()?;
Ok(cgr)
}
pub fn generate_tokens_for_inline<'a>(
files: impl Iterator<Item = &'a FileDescriptorProtoView>,
options: &CodegenOptions,
) -> Result<TokenStream> {
let root_package = Package::new_root(files);
root_package.gen_inline_code(options.puroro_library_path.as_deref())
}