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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#![doc(
html_logo_url = "https://github.com/cloudwego/pilota/raw/main/.github/assets/logo.png?sanitize=true"
)]
#![cfg_attr(not(doctest), doc = include_str!("../README.md"))]
pub mod codegen;
pub mod db;
mod fmt;
mod index;
mod ir;
mod middle;
pub mod parser;
mod resolve;
mod symbol;
pub mod tags;
mod util;
use std::{
io::Write,
path::{Path, PathBuf},
sync::Arc,
};
pub mod plugin;
mod test;
use codegen::protobuf::{ProstPlugin, ProtobufBackend};
pub use codegen::{thrift::ThriftBackend, traits::CodegenBackend, Codegen};
use db::RootDatabase;
use fmt::fmt_file;
use middle::{context::tls::CONTEXT, rir::NodeKind, type_graph::TypeGraph};
pub use middle::{rir, ty};
use parser::{protobuf::ProtobufParser, thrift::ThriftParser, ParseResult, Parser};
use plugin::{
AutoDerivePlugin, BoxedPlugin, EnumNumPlugin, ImplDefaultPlugin, PredicateResult,
WithAttrsPlugin,
};
pub use plugin::{BoxClonePlugin, ClonePlugin, Plugin};
use resolve::{ResolveResult, Resolver};
use salsa::{Durability, ParallelDatabase};
pub use symbol::DefId;
use syn::parse_quote;
use crate::db::RirDatabase;
pub use crate::middle::context::Context;
pub trait MakeBackend: Sized {
type Target: CodegenBackend;
fn make_backend(self, context: Arc<Context>) -> Self::Target;
}
pub struct MkThriftBackend;
impl MakeBackend for MkThriftBackend {
type Target = ThriftBackend;
fn make_backend(self, context: Arc<Context>) -> Self::Target {
ThriftBackend::new(context)
}
}
pub struct MkProtobufBackend;
impl MakeBackend for MkProtobufBackend {
type Target = ProtobufBackend;
fn make_backend(self, context: Arc<Context>) -> Self::Target {
ProtobufBackend::new(context)
}
}
pub struct Builder<MkB, P> {
mk_backend: MkB,
parser: P,
plugins: Vec<Box<dyn Plugin>>,
remove_unused: bool,
}
impl Builder<MkThriftBackend, ThriftParser> {
pub fn thrift() -> Self {
Builder {
mk_backend: MkThriftBackend,
parser: ThriftParser::default(),
plugins: vec![
Box::new(WithAttrsPlugin(vec![parse_quote!(#[derive(Debug)])])),
Box::new(ImplDefaultPlugin),
Box::new(EnumNumPlugin),
],
remove_unused: true,
}
}
}
impl Builder<MkProtobufBackend, ProtobufParser> {
pub fn protobuf() -> Self {
Builder {
mk_backend: MkProtobufBackend,
parser: ProtobufParser::default(),
plugins: vec![Box::new(ProstPlugin)],
remove_unused: false,
}
}
}
impl<MkB, P> Builder<MkB, P>
where
P: Parser,
{
pub fn include_dirs(mut self, include_dirs: Vec<PathBuf>) -> Self {
self.parser.include_dirs(include_dirs);
self
}
}
impl<MkB, P> Builder<MkB, P> {
pub fn with_backend<B: MakeBackend>(self, mk_backend: B) -> Builder<B, P> {
Builder {
mk_backend,
parser: self.parser,
plugins: self.plugins,
remove_unused: self.remove_unused,
}
}
pub fn plugin<Plu: Plugin + 'static>(mut self, p: Plu) -> Self {
self.plugins.push(Box::new(p));
self
}
pub fn remove_unused(mut self, flag: bool) -> Self {
self.remove_unused = flag;
self
}
}
impl<MkB, P> Builder<MkB, P>
where
MkB: MakeBackend,
P: Parser,
{
pub fn compile<O: AsRef<Path>>(mut self, files: &[impl AsRef<Path>], out: O) {
let _ = tracing_subscriber::fmt::try_init();
let mut db = RootDatabase::default();
self.parser.inputs(files);
let ParseResult { files, input_files } = self.parser.parse();
let ResolveResult { files, nodes, tags } = Resolver::default().resolve_files(&files);
db.set_files_with_durability(Arc::new(files), Durability::HIGH);
let items = nodes.iter().filter_map(|(k, v)| {
if let NodeKind::Item(item) = &v.kind {
Some((*k, item.clone()))
} else {
None
}
});
let type_graph = Arc::from(TypeGraph::from_items(items));
db.set_type_graph_with_durability(type_graph, Durability::HIGH);
db.set_nodes_with_durability(Arc::new(nodes), Durability::HIGH);
let mut cx = Context::new(db.snapshot());
cx.set_tags_map(tags);
cx.exec_plugin(BoxedPlugin);
cx.exec_plugin(AutoDerivePlugin::new(
vec![parse_quote!(#[derive(PartialOrd)])],
|ty| {
let ty = match &ty.kind {
ty::Vec(ty) => ty,
_ => ty,
};
if matches!(ty.kind, ty::Map(_, _) | ty::Set(_)) {
PredicateResult::No
} else {
PredicateResult::GoOn
}
},
));
cx.exec_plugin(AutoDerivePlugin::new(
vec![parse_quote!(#[derive(Hash, Eq, Ord)])],
|ty| {
let ty = match &ty.kind {
ty::Vec(ty) => ty,
_ => ty,
};
if matches!(ty.kind, ty::Map(_, _) | ty::Set(_) | ty::F64) {
PredicateResult::No
} else {
PredicateResult::GoOn
}
},
));
self.plugins.into_iter().for_each(|p| cx.exec_plugin(p));
let mut input = Vec::with_capacity(input_files.len());
for file_id in input_files {
let file = cx.file(file_id).unwrap();
file.items.iter().for_each(|def_id| {
if matches!(&*cx.item(*def_id).unwrap(), rir::Item::Service(_)) {
input.push(*def_id)
}
});
}
let context = Arc::from(cx);
CONTEXT.set(&context.clone(), || {
let mut cg = Codegen::new(
context.clone(),
self.mk_backend.make_backend(context),
input,
);
cg.write_pkgs(self.remove_unused);
let file_name = out
.as_ref()
.file_name()
.and_then(|s| s.to_str())
.and_then(|s| s.split('.').next())
.unwrap();
let stream = cg.link(file_name);
let mut file = std::io::BufWriter::new(std::fs::File::create(&out).unwrap());
file.write_all(stream.to_string().as_bytes()).unwrap();
file.flush().unwrap();
fmt_file(out)
});
}
}