interoptopus_backend_cpython_cffi 0.1.7

Generates CPython CFFI bindings.
Documentation
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Generates CPython CFFI bindings for [Interoptopus](https://github.com/ralfbiedert/interoptopus).
//!
//! ## Usage
//!
//! In your library or a support project add this:
//!
//! ```
//! # mod my_crate { use interoptopus::{Library}; pub fn ffi_inventory() -> Library { todo!() } }
//! use my_crate::ffi_inventory;
//!
//! #[test]
//! fn generate_python_bindings() {
//!     use interoptopus::Interop;
//!     use interoptopus_backend_cpython_cffi::{Generator, InteropCPythonCFFI, Config};
//!
//!     // Converts an `ffi_inventory()` into Python interop definitions.
//!     Generator::new(Config::default(), ffi_inventory()).write_to("module.py")
//! }
//! ```
//!
//! And we might produce something like this:
//!
//! ```python
//! from cffi import FFI
//!
//! api_definition = """
//! typedef struct Vec3f32
//!     {
//!     float x;
//!     float y;
//!     float z;
//!     } Vec2f32;
//!
//! Vec3f32 my_game_function(Vec3f32* input);
//! """
//!
//!
//! ffi = FFI()
//! ffi.cdef(api_definition)
//! _api = None
//!
//!
//! def init_api(dll):
//!     """Initializes this library, call with path to DLL."""
//!     global _api
//!     _api = ffi.dlopen(dll)
//!
//!
//! class raw:
//!     """Raw access to all exported functions."""
//!
//!     def my_game_function(input):
//!     global _api
//!     return _api.my_game_function(input)
//! ```

use interoptopus::lang::c::{CType, ConstantValue, EnumType, FnPointerType, Function, PrimitiveValue};
use interoptopus::patterns::class::Class;
use interoptopus::patterns::{LibraryPattern, TypePattern};
use interoptopus::util::{longest_common_prefix, safe_name};
use interoptopus::writer::IndentWriter;
use interoptopus::Interop;
use interoptopus::{Error, Library};
use interoptopus_backend_c::InteropC;

/// Configures Python code generation.
#[derive(Clone, Debug)]
pub struct Config {
    /// How to name the function responsible for loading the DLL, e.g., `init_api`.
    pub init_api_function_name: String,
    /// Attribute by which the `cffi` object is exposed, e.g., `ffi`.
    pub ffi_attribute: String,
    /// Namespace to put functions into, e.g., `raw`.
    pub raw_fn_namespace: String,
    /// Namespace for callback helpers, e.g., `callbacks`.
    pub callback_namespace: String,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            init_api_function_name: "init_api".to_string(),
            ffi_attribute: "ffi".to_string(),
            raw_fn_namespace: "raw".to_string(),
            callback_namespace: "callbacks".to_string(),
        }
    }
}

/// Helper type implementing [`InteropCPythonCFFI`] and [`Interop`].
pub struct Generator {
    c_generator: interoptopus_backend_c::Generator,
    config: Config,
    library: Library,
}

impl Generator {
    pub fn new(config: Config, library: Library) -> Self {
        let c_generator = interoptopus_backend_c::Generator::new(
            interoptopus_backend_c::Config {
                directives: false,
                imports: false,
                file_header_comment: "".to_string(),
                ..interoptopus_backend_c::Config::default()
            },
            library.clone(),
        );

        Self { c_generator, config, library }
    }
}

/// Contains all Python generators, create sub-trait to customize.
pub trait InteropCPythonCFFI: Interop {
    /// Returns the user config.
    fn config(&self) -> &Config;

    /// Returns the library to produce bindings for.
    fn library(&self) -> &Library;

    /// Returns the C-generator
    fn c_generator(&self) -> &interoptopus_backend_c::Generator;

    fn constant_value_to_value(&self, value: &ConstantValue) -> String {
        match value {
            ConstantValue::Primitive(x) => match x {
                PrimitiveValue::Bool(x) => format!("{}", x),
                PrimitiveValue::U8(x) => format!("{}", x),
                PrimitiveValue::U16(x) => format!("{}", x),
                PrimitiveValue::U32(x) => format!("{}", x),
                PrimitiveValue::U64(x) => format!("{}", x),
                PrimitiveValue::I8(x) => format!("{}", x),
                PrimitiveValue::I16(x) => format!("{}", x),
                PrimitiveValue::I32(x) => format!("{}", x),
                PrimitiveValue::I64(x) => format!("{}", x),
                PrimitiveValue::F32(x) => format!("{}", x),
                PrimitiveValue::F64(x) => format!("{}", x),
            },
        }
    }

    fn write_imports(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"from cffi import FFI"#))?;
        Ok(())
    }

    fn write_api_load_fuction(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"{} = FFI()"#, self.config().ffi_attribute))?;
        w.indented(|w| writeln!(w, r#"{}.cdef(api_definition)"#, self.config().ffi_attribute))?;
        w.indented(|w| writeln!(w, r#"_api = None"#))?;
        w.newline()?;
        w.newline()?;

        w.indented(|w| writeln!(w, r#"def {}(dll):"#, self.config().init_api_function_name))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""Initializes this library, call with path to DLL.""""#))?;
        w.indented(|w| writeln!(w, r#"global _api"#))?;
        w.indented(|w| writeln!(w, r#"_api = {}.dlopen(dll)"#, self.config().ffi_attribute))?;
        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn write_constants(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for constant in self.library().constants() {
            let docs = constant
                .meta()
                .documentation()
                .lines()
                .iter()
                .map(|x| format!("# {}", x))
                .collect::<Vec<_>>()
                .join("\n");
            w.indented(|w| writeln!(w, r#"{}"#, docs))?;
            w.indented(|w| writeln!(w, r#"{} = {}"#, constant.name(), self.constant_value_to_value(constant.value())))?;
        }

        Ok(())
    }

    fn write_types(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for the_type in self.library().ctypes() {
            match the_type {
                CType::Enum(e) => self.write_enum(w, e)?,
                CType::Pattern(TypePattern::SuccessEnum(e)) => self.write_enum(w, e.the_enum())?,
                _ => {}
            }
        }

        Ok(())
    }

    fn write_enum(&self, w: &mut IndentWriter, e: &EnumType) -> Result<(), Error> {
        let docs = e.meta().documentation().lines().join("\n");

        w.indented(|w| writeln!(w, r#"class {}:"#, e.rust_name()))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
        for v in e.variants() {
            w.indented(|w| writeln!(w, r#"{} = {}"#, v.name(), v.value()))?;
        }
        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn write_callback_helpers(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"class {}:"#, self.config().callback_namespace))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""Helpers to define `@ffi.callback`-style callbacks.""""#))?;

        for callback in self.library().ctypes().iter().filter_map(|x| match x {
            CType::FnPointer(x) => Some(x),
            _ => None,
        }) {
            w.indented(|w| writeln!(w, r#"{} = "{}""#, safe_name(&callback.internal_name()), self.type_fnpointer_to_typename(callback)))?;
        }

        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn type_fnpointer_to_typename(&self, fn_pointer: &FnPointerType) -> String {
        let rval = self.c_generator().type_to_type_specifier(&fn_pointer.signature().rval());
        let params = fn_pointer
            .signature()
            .params()
            .iter()
            .map(|x| self.c_generator().type_to_type_specifier(x.the_type()))
            .collect::<Vec<_>>()
            .join(",");

        format!("{}({})", rval, params)
    }

    fn write_function_proxies(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"class {}:"#, self.config().raw_fn_namespace))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""Raw access to all exported functions.""""#))?;

        for function in self.library().functions() {
            let args = function.signature().params().iter().map(|x| x.name().to_string()).collect::<Vec<_>>().join(", ");
            let docs = function.meta().documentation().lines().join("\n");

            w.indented(|w| writeln!(w, r#"def {}({}):"#, function.name(), &args))?;
            w.indent();
            w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
            w.indented(|w| writeln!(w, r#"global _api"#))?;
            w.indented(|w| writeln!(w, r#"return _api.{}({})"#, function.name(), &args))?;
            w.unindent();

            w.newline()?;
        }

        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn write_patterns(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for pattern in self.library().patterns() {
            match pattern {
                LibraryPattern::Class(cls) => self.write_pattern_class(w, cls)?,
            }
        }

        Ok(())
    }

    fn pattern_class_args_without_first_to_string(&self, function: &Function) -> String {
        function
            .signature()
            .params()
            .iter()
            .skip(1)
            .map(|x| x.name().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn write_pattern_class_success_enum_aware_rval(&self, w: &mut IndentWriter, _class: &Class, function: &Function, deref_ctx: bool) -> Result<(), Error> {
        let args = self.pattern_class_args_without_first_to_string(function);

        let ctx = if deref_ctx { "self.ctx[0]" } else { "self.ctx" };

        match function.signature().rval() {
            CType::Pattern(TypePattern::SuccessEnum(e)) => {
                w.indented(|w| writeln!(w, r#"rval = _api.{}({}, {})"#, function.name(), ctx, &args))?;
                w.indented(|w| writeln!(w, r#"if rval == {}.{}:"#, e.the_enum().rust_name(), e.success_variant().name()))?;
                w.indent();
                w.indented(|w| writeln!(w, r#"return None"#))?;
                w.unindent();
                w.indented(|w| writeln!(w, r#"else:"#))?;
                w.indent();
                w.indented(|w| writeln!(w, r#"raise Exception(f"return value ${{rval}}")"#))?;
                w.unindent();
            }
            _ => {
                w.indented(|w| writeln!(w, r#"return _api.{}(self.ctx[0], {})"#, function.name(), &args))?;
            }
        }

        Ok(())
    }

    fn write_pattern_class(&self, w: &mut IndentWriter, class: &Class) -> Result<(), Error> {
        let context_type_name = class.the_type().rust_name();

        let mut all_functions = vec![class.constructor().clone(), class.destructor().clone()];
        all_functions.extend_from_slice(class.methods());
        let common_prefix = longest_common_prefix(&all_functions);

        w.indented(|w| writeln!(w, r#"class {}(object):"#, context_type_name))?;
        w.indent();

        // Ctor
        let args = self.pattern_class_args_without_first_to_string(class.constructor());
        let docs = class.constructor().meta().documentation().lines().join("\n");
        w.indented(|w| writeln!(w, r#"def __init__(self, {}):"#, args))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
        w.indented(|w| writeln!(w, r#"global _api, ffi"#))?;
        w.indented(|w| writeln!(w, r#"self.ctx = ffi.new("{}**")"#, context_type_name))?;
        self.write_pattern_class_success_enum_aware_rval(w, class, class.constructor(), false)?;
        w.unindent();
        w.newline()?;

        // Dtor
        let docs = class.destructor().meta().documentation().lines().join("\n");
        w.indented(|w| writeln!(w, r#"def __del__(self):"#))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
        w.indented(|w| writeln!(w, r#"global _api, ffi"#))?;
        self.write_pattern_class_success_enum_aware_rval(w, class, class.destructor(), false)?;
        w.unindent();
        w.newline()?;

        for function in class.methods() {
            let args = self.pattern_class_args_without_first_to_string(function);
            let docs = function.meta().documentation().lines().join("\n");

            w.indented(|w| writeln!(w, r#"def {}(self, {}):"#, function.name().replace(&common_prefix, ""), &args))?;
            w.indent();
            w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
            w.indented(|w| writeln!(w, r#"global _api"#))?;

            self.write_pattern_class_success_enum_aware_rval(w, class, function, true)?;

            w.unindent();
            w.newline()?;
        }

        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn write_c_header(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"api_definition = """"#))?;
        self.c_generator().write_to(w)?;
        w.indented(|w| writeln!(w, r#"""""#))?;
        Ok(())
    }
}

impl Interop for Generator {
    fn write_to(&self, w: &mut IndentWriter) -> Result<(), Error> {
        self.write_imports(w)?;
        w.newline()?;

        self.write_c_header(w)?;
        w.newline()?;
        w.newline()?;

        self.write_api_load_fuction(w)?;
        w.newline()?;
        w.newline()?;

        self.write_constants(w)?;
        w.newline()?;
        w.newline()?;

        self.write_types(w)?;
        w.newline()?;
        w.newline()?;

        self.write_callback_helpers(w)?;
        w.newline()?;
        w.newline()?;

        self.write_function_proxies(w)?;
        w.newline()?;
        w.newline()?;

        self.write_patterns(w)?;
        w.newline()?;
        w.newline()?;

        Ok(())
    }
}

impl InteropCPythonCFFI for Generator {
    fn config(&self) -> &Config {
        &self.config
    }

    fn library(&self) -> &Library {
        &self.library
    }

    fn c_generator(&self) -> &interoptopus_backend_c::Generator {
        &self.c_generator
    }
}