-
Notifications
You must be signed in to change notification settings - Fork 10
/
gen_binding.py
366 lines (324 loc) · 9.7 KB
/
gen_binding.py
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
from doxybindgen.model import Class, ClassManager, pascal_to_snake
from doxybindgen.binding import CxxClassBinding, RustClassBinding
from itertools import chain
import string
import subprocess
import toml
# place wxWidgets doxygen xml files in wxml/ dir and run this.
def main():
with open('Doxybindgen.toml', 'r') as f:
config = toml.load(f)
classes = ClassManager()
parsed = []
xmlfiles = config['wxml_files']
progress('Parsing')
for file in xmlfiles:
progress('.')
for cls in Class.in_xml(classes, file, config['types']):
parsed.append(cls)
# Register all classes once parsing finished.
classes.register(parsed)
progress('\nGenerating')
with open('docs/OverloadTree.md', 'w') as overload_tree_md:
print('''\
# Overload Method Name Decision Tree
''', file=overload_tree_md)
generate_library(classes, config, 'base', overload_tree_md)
generate_library(classes, config, 'core', overload_tree_md)
generate_events(classes, config)
generated = []
def generate_library(classes, config, libname, overload_tree_md):
generated.append(libname)
files_per_initial = {
'src/generated/ffi_%s.rs': ffi_i_rs,
'src/generated/methods_%s.rs': methods_i_rs,
'src/generated/class_%s.rs': class_i_rs,
'include/generated/ffi_%s.h': ffi_i_h,
'src/generated/ffi_%s.cpp': ffi_i_cpp,
}
rust_bindings = [RustClassBinding(cls, overload_tree_md) for cls in classes.in_lib(libname, generated)]
cxx_bindings = [CxxClassBinding(cls, config) for cls in classes.in_lib(libname, generated)]
initials = []
for initial in string.ascii_lowercase:
rust_bindings_i = [b for b in rust_bindings if b.has_initial(initial)]
if len(rust_bindings_i) == 0:
continue
initials.append(initial)
cxx_bindings_i = [c for c in cxx_bindings if c.has_initial(initial)]
for path, generator in files_per_initial.items():
progress('.')
path = path % (initial,)
is_rust = path.endswith('.rs')
if libname:
path = 'wx-%s/%s' % (libname, path)
with open(path, 'w', newline='\n', encoding='utf-8') as f:
for chunk in generator(
rust_bindings_i if is_rust else cxx_bindings_i,
libname
):
print(chunk, file=f)
if is_rust:
error = subprocess.check_output(['rustfmt', path])
if error:
print(error)
to_be_generated = {
'src/generated/class.rs': class_rs,
'src/generated/ffi.rs': ffi_rs,
'src/generated/methods.rs': methods_rs,
'src/generated.rs': generated_rs,
'include/generated.h': generated_h,
'src/generated.cpp': generated_cpp,
}
for path, generator in to_be_generated.items():
progress('.')
is_rust = path.endswith('.rs')
if libname:
path = 'wx-%s/%s' % (libname, path)
with open(path, 'w', newline='\n', encoding='utf-8') as f:
for chunk in generator(
initials,
libname
):
print(chunk, file=f)
def progress(s):
print(s, end='', flush=True)
def ffi_i_rs(classes, libname):
yield '''\
use super::*;
extern "C" {'''
indent = ' ' * 4 * 1
for cls in classes:
for line in cls.lines(for_ffi=True):
if not line:
yield ''
else:
yield '%s%s' % (indent, line)
yield '''\
}\
'''
def methods_i_rs(classes, libname):
yield '''\
use super::*;
'''
for cls in classes:
for line in cls.lines(for_methods=True):
yield line
def class_i_rs(classes, libname):
yield '''\
use super::*;
'''
for cls in classes:
for line in cls.lines():
yield line
def ffi_i_h(classes, libname):
yield '''\
#pragma once
'''
uniq = set()
for cls in classes:
uniq.add(cls.include())
for (include, condition) in sorted(uniq):
if condition:
yield condition
yield include
if condition:
yield '#endif'
yield '''\
extern "C" {
'''
for cls in classes:
for line in cls.lines():
yield line
yield '''\
} // extern "C"
'''
def ffi_i_cpp(classes, libname):
yield '''\
#include "generated.h"
extern "C" {
'''
for cls in classes:
for line in cls.lines(is_cc=True):
yield line
yield '''\
} // extern "C"
'''
def class_rs(initials, libname):
yield '''\
use super::*;
'''
for i in initials:
yield 'pub use class_%s::*;' % (i,)
def ffi_rs(initials, libname):
yield '''\
pub use crate::ffi::*;
'''
for i in initials:
yield 'pub use super::ffi_%s::*;' % (i,)
def methods_rs(initials, libname):
if libname == 'base':
yield '''\
use std::os::raw::c_void;
pub trait WxRustMethods {
type CppManaged;
unsafe fn as_ptr(&self) -> *mut c_void;
unsafe fn from_ptr(ptr: *mut c_void) -> Self;
unsafe fn from_cpp_managed_ptr(ptr: *mut c_void) -> Self::CppManaged;
unsafe fn with_ptr<F: Fn(&Self)>(ptr: *mut c_void, closure: F);
unsafe fn option_from(ptr: *mut c_void) -> Option<Self::CppManaged>
where
Self: Sized,
{
if ptr.is_null() {
None
} else {
Some(Self::from_cpp_managed_ptr(ptr))
}
}
}
'''
else:
yield '''\
#[doc(no_inline)]
pub use wx_base::methods::*;
'''
for i in initials:
yield 'pub use super::methods_%s::*;' % (i,)
def generated_rs(initials, libname):
yield '''\
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
use std::os::raw::{c_double, c_int, c_long, c_uchar, c_uint, c_void};
use super::*;
use methods::*;
'''
if libname == 'base':
yield '''\
pub use events::*;
mod events;
'''
yield 'mod ffi;'
for i in initials:
yield 'mod ffi_%s;' % (i,)
yield ''
yield 'pub mod methods;'
for i in initials:
yield 'mod methods_%s;' % (i,)
yield ''
yield 'pub mod class;'
for i in initials:
yield 'mod class_%s;' % (i,)
def generated_h(initials, libname):
yield '''\
#pragma once
#include <wx/wx.h>
'''
if libname == 'core':
yield '''\
// wxBitmapBundle compatibility hack(for a while)
#if !wxCHECK_VERSION(3, 1, 6)
typedef wxBitmap wxBitmapBundle;
#endif
typedef wxMessageDialog::ButtonLabel ButtonLabel;
'''
else:
yield '''\
typedef wxDateTime::TimeZone TimeZone;
typedef wxDateTime::Tm Tm;
typedef wxDateTime::WeekDay WeekDay;
'''
for i in initials:
yield '#include "generated/ffi_%s.h"' % (i,)
def generated_cpp(initials, libname):
yield '''\
#include "generated.h"
// Including splitted source files into single source file to keep build.rs simple\
'''
for i in initials:
yield '#include "generated/ffi_%s.cpp"' % (i,)
def generate_events(classes, config):
to_be_generated = {
'wx-base/src/generated/events.rs': events_rs,
'wx-base/src/generated/events.cpp': events_cpp,
}
event_classes = [c for c in classes.all() if classes.is_a(c, 'wxEvent')]
for path, generator in to_be_generated.items():
is_rust = path.endswith('.rs')
with open(path, 'w', newline='\n', encoding='utf-8') as f:
for chunk in generator(event_classes, config):
print(chunk, file=f)
if is_rust:
error = subprocess.check_output(['rustfmt', path])
if error:
print(error)
def events_rs(event_classes, config):
yield '''\
pub enum RustEvent {\
'''
event_types = sorted(chain.from_iterable(c.event_types for c in event_classes))
for event_type in event_types:
yield ' %s,' % (event_type,)
yield '''\
}
'''
def events_cpp(event_classes, config):
yield '''\
#include <wx/bookctrl.h>
#include "manual.h"
enum WxRustEvent {\
'''
event_types = sorted(chain.from_iterable(c.event_types for c in event_classes))
for event_type in event_types:
yield ' RUST_EVT_%s,' % (pascal_to_snake(event_type).upper(),)
yield '''\
};
#define MAP_RUST_EVT(name) case RUST_EVT_##name: return wxEVT_##name;
#define DEFINE_TYPE_TAG_OF_EVT(name, clazz) \\
template<> wxEventTypeTag<clazz> TypeTagOf(int eventType) { \\
switch (eventType) { \\
MAP_RUST_EVT(name) \\
} \\
return wxEVT_NULL; \\
}
template<typename T> wxEventTypeTag<T> TypeTagOf(int eventType) {
return wxEVT_NULL;
}'''
for cls in event_classes:
if len(cls.event_types) < 1:
continue
if len(cls.event_types) == 1:
yield 'DEFINE_TYPE_TAG_OF_EVT(%s, %s)' % (
pascal_to_snake(cls.event_types[0]).upper(),
cls.name,
)
continue
yield '''\
template<> wxEventTypeTag<%s> TypeTagOf(int eventType) {
switch (eventType) {\
''' % (cls.name,)
for event_type in cls.event_types:
yield ' MAP_RUST_EVT(%s)' % (
pascal_to_snake(event_type).upper(),
)
yield '''\
}
return wxEVT_NULL;
}'''
yield '''
template<typename T> void BindIfEventIs(wxEvtHandler *self, int eventType, void *aFn, void *aParam) {
wxEventTypeTag<T> typeTag = TypeTagOf<T>(eventType);
if (typeTag != wxEVT_NULL) {
CxxClosure<T &> functor(aFn, aParam);
self->Bind(typeTag, functor);
}
}
void wxEvtHandler_Bind(wxEvtHandler *self, int eventType, void *aFn, void *aParam) {\
'''
for cls in event_classes:
if len(cls.event_types) < 1:
continue
yield ' BindIfEventIs<%s>(self, eventType, aFn, aParam);' % (cls.name,)
yield '''\
}'''
if __name__ == '__main__':
main()