/
mod.rs
332 lines (263 loc) · 8.23 KB
/
mod.rs
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
pub mod core;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::collections::HashSet;
use syn::{
parse::{ParseStream, Parser},
*,
};
pub fn get_exports() -> HashMap<Ident, Path> {
let mut exports = HashMap::new();
let mut ext_path: Path = parse2(quote!(::ext)).unwrap();
ext_path.segments.push_punct(Default::default());
core::get_exports(&ext_path, &mut exports);
exports
}
pub fn get_store() -> HashMap<(Path, Ident), ItemTrait> {
let mut token_list = vec![];
let mut ext_path: Path = parse2(quote!(::ext)).unwrap();
ext_path.segments.push_punct(Default::default());
core::get_impl(&ext_path, &mut token_list);
let mut parsed_traits = HashMap::new();
for (path, body) in token_list {
let traits = Parser::parse2(parse_traits, body).expect("Failed to parse traits");
for tr in traits {
parsed_traits.insert((path.clone(), tr.ident.clone()), tr);
}
}
parsed_traits
}
fn subpath_to_tokens(path: &Path, skip: usize) -> TokenStream {
let mut out = TokenStream::new();
for seg in path.segments.pairs().skip(skip) {
match seg {
punctuated::Pair::Punctuated(p, punc) => {
out.extend(quote!(#p #punc));
}
punctuated::Pair::End(p) => {
out.extend(quote!(#p));
}
}
}
out
}
type Modules = HashMap<usize, HashMap<Path, (TokenStream, HashSet<Ident>)>>;
fn impl_mod(
path: &Path,
name: &Ident,
depth: usize,
mut mod_impl: TokenStream,
children: HashSet<Ident>,
modules: &mut Modules,
) -> TokenStream {
let child_depth = depth + 1;
for ident in children {
let mut path = path.clone();
let name = ident.clone();
path.segments.push_value(PathSegment {
ident,
arguments: Default::default(),
});
path.segments.push_punct(Default::default());
let (ts, children) = modules
.get_mut(&child_depth)
.expect("Module depth not found")
.remove(&path)
.expect("Child module not found");
mod_impl.extend(impl_mod(&path, &name, child_depth, ts, children, modules));
}
quote! {
pub mod #name {
#mod_impl
}
}
}
/// Remaps all Ident paths that are in the export list to become ::ext::Ident
pub fn prelude_remap(path: Path) -> Path {
if let Some(ident) = path.get_ident().cloned() {
if let Some(path) = get_exports().get(&ident) {
let mut new_path = path.clone();
new_path.segments.push(PathSegment {
ident,
arguments: Default::default(),
});
new_path
} else {
path
}
} else {
path
}
}
/// Returns the absolute export path if ident is in exports, and path is empty.
pub fn prelude_remap_with_ident(path: Path, ident: &Ident) -> Path {
if !path.segments.is_empty() {
path
} else if let Some(path) = get_exports().get(&ident) {
path.clone()
} else {
path
}
}
/// Remaps all ::ext:: paths to become ::cglue::ext:: paths.
pub fn ext_abs_remap(path: Path) -> Path {
let mut iter = path.segments.iter();
if let (Some(_), Some(seg)) = (path.leading_colon, iter.next()) {
if seg.ident == "ext" {
let (leading_colon, ident) = crate::util::crate_path_ident();
let mut new_path = Path {
leading_colon,
segments: Default::default(),
};
new_path.segments.push_value(PathSegment {
ident,
arguments: Default::default(),
});
new_path.segments.push_punct(Default::default());
std::mem::drop(iter);
new_path.segments.extend(path.segments.into_pairs());
new_path
} else {
std::mem::drop(iter);
path
}
} else {
std::mem::drop(iter);
path
}
}
pub fn impl_ext_forward() -> TokenStream {
impl_inner(
|_, _| quote!(),
|p, _| quote!(#[cglue_forward_ext(::#p)]),
|_, _| {},
)
}
/// Implement the external trait store.
pub fn impl_store() -> TokenStream {
impl_inner(
|subpath, name| quote!(pub use #subpath #name;),
|_, _| quote!(#[cglue_trait_ext]),
|exports, out| {
// Re-export everything
for (k, v) in exports.into_iter() {
let subpath = subpath_to_tokens(&v, 1);
for ident in [
"",
"Ext",
"Vtbl",
"RetTmp",
"Box",
"CtxBox",
"ArcBox",
"Mut",
"Ref",
"Base",
"BaseBox",
"BaseCtxBox",
"BaseArcBox",
"BaseMut",
"BaseRef",
]
.iter()
.map(|p| format_ident!("{}{}", k, p))
{
out.extend(quote!(pub use self:: #subpath #ident;));
}
}
},
)
}
fn impl_inner(
use_gen: impl Fn(&TokenStream, &Ident) -> TokenStream,
attribute_gen: impl Fn(&TokenStream, &ItemTrait) -> TokenStream,
exports_gen: impl Fn(HashMap<Ident, Path>, &mut TokenStream),
) -> TokenStream {
let mut out = TokenStream::new();
let exports = get_exports();
let store = get_store();
let mut modules = HashMap::<usize, HashMap<Path, (TokenStream, HashSet<Ident>)>>::new();
exports_gen(exports, &mut out);
for ((p, _), t) in store.into_iter() {
// exclude :: ext :: segment, and the whole layer altogether
let segments = p.segments.len();
assert!(segments > 1, "External traits defined in external root!");
let depth = segments - 2;
push_to_parent(depth, &p, &mut modules);
let (module, _) = modules
.entry(depth)
.or_default()
.entry(p.clone())
.or_default();
let name = &t.ident;
let subpath = subpath_to_tokens(&p, 1);
let use_gened = use_gen(&subpath, name);
let attribute = attribute_gen(&subpath, &t);
module.extend(quote! {
#use_gened
use ::cglue_macro::*;
#attribute
#t
});
}
if let Some(root) = modules.remove(&0) {
for (p, (ts, children)) in root {
let name = &p.segments.iter().next_back().unwrap().ident;
out.extend(impl_mod(&p, &name, 0, ts, children, &mut modules))
}
} else if !modules.is_empty() {
panic!("Module implementations defined, but everything is disjoint from the root!");
}
out
}
fn push_to_parent(depth: usize, path: &Path, modules: &mut Modules) {
if depth == 0 {
return;
}
let child_depth = depth - 1;
let mut parent_path = path.clone();
let my_ident = parent_path
.segments
.pop()
.map(punctuated::Pair::into_value)
.unwrap()
.ident;
let entry = modules
.entry(child_depth)
.or_default()
.entry(parent_path.clone());
match entry {
Entry::Occupied(mut e) => e.get_mut().1.insert(my_ident),
Entry::Vacant(_) => {
push_to_parent(child_depth, &parent_path, modules);
let (_, children) = modules
.entry(child_depth)
.or_default()
.entry(parent_path)
.or_default();
children.insert(my_ident)
}
};
}
fn parse_traits(input: ParseStream) -> Result<Vec<ItemTrait>> {
let mut out = vec![];
while !input.is_empty() {
let val = input.parse()?;
out.push(val);
}
Ok(out)
}
fn join_paths(path: &Path, ident: Ident) -> Path {
let mut ret = path.clone();
if !ret.segments.empty_or_trailing() {
ret.segments.push_punct(Default::default());
}
ret.segments.push_value(PathSegment {
ident,
arguments: Default::default(),
});
ret.segments.push_punct(Default::default());
ret
}