miniffi 0.1.0

A simple but opinionated FFI system
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! This is a simple but opinionated FFI system for Rust. It allows you to call
//! Rust code from other languages, and vice versa. Some design principles:
//!
//! - Intended for writing platform-agnostic Rust with platform-specific details in the host language
//! - FFI support is split into data (structs passed by copy) and code (traits passed by reference)
//! - Rather than have a separate schema language, the public API in your `lib.rs` is your schema
//! - The generated binding code is compact, dependency-free, and straightforward to integrate with
//!
//! ## Supported Features
//!
//! - Primitive types (`bool`, `i32`, `f64`, `String`, etc.)
//! - Tuples
//! - Structs
//! - Enums
//! - Top-level constants
//! - Top-level functions
//! - Traits (must be either `Box<dyn T>` or `Rc<dyn T>`)
//! - `Vec<T>`
//! - `Option<T>`
//! - `Box<T>`
//!
//! ## Simple Usage
//!
//! To get up and running:
//!
//! 1. Add `miniffi` to your `[build-dependencies]` in `Cargo.toml`:
//!
//!     ```text
//!     cargo add --build miniffi
//!     ```
//!
//! 2. Add the following code to the end of your `src/lib.rs` file:
//!
//!     ```
//!     # macro_rules! env { ($a:expr) => { $a } }
//!     # macro_rules! include { ($a:expr) => { $a } }
//!     include!(concat!(env!("OUT_DIR"), "/miniffi.rs"));
//!     ```
//!
//! 3. Add a `build.rs` script that calls [`build`](Target::build) on at least one [`Target`]:
//!
//!     ```no_run
//!     use miniffi::*;
//!
//!     fn main() {
//!         CppTarget::new().build();
//!     }
//!     ```
//!
//! 4. Import the generated bindings from the host language (see each target for details)
//!
//! ## Advanced Usage
//!
//! You can only build for one target at a time. However, the flexibility of
//! build scripts means you can use the same build script for different targets
//! in different situations using your own custom logic.
//!
//! For example, you may want to build for different host languages depending
//! on the value of cargo's `--target` flag:
//!
//! ```no_run
//! use miniffi::*;
//!
//! fn main() {
//!     let target = std::env::var("TARGET").unwrap();
//!     if target == "wasm32-unknown-unknown" {
//!         WasmTarget::new()
//!             .write_ts_to("../web/rust.ts")
//!             .set_panic_hook()
//!             .build();
//!     } else if target == "aarch64-apple-darwin" {
//!         SwiftTarget::new()
//!             .write_swift_to("../macos/rust.swift")
//!             .write_header_to("../macos/rust.h")
//!             .build();
//!     } else if target == "x86_64-pc-windows-msvc" {
//!         CppTarget::new()
//!             .write_source_to("../windows/rust.cpp")
//!             .write_header_to("../windows/rust.h")
//!             .build();
//!     } else {
//!         NullTarget::new().build();
//!     }
//! }
//! ```

mod ast;
mod cpp;
mod rust;
mod scan;
mod swift;
mod util;
mod wasm;

use ast::*;
use rust::*;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use syn::spanned::Spanned;
use util::*;

pub use cpp::CppTarget;
pub use swift::SwiftTarget;
pub use wasm::WasmTarget;

use crate::scan::make_warning;

#[cfg(test)]
mod tests;

const DO_NOT_EDIT_COMMENT: &str = concat!(
    "This file was generated by miniffi v",
    env!("CARGO_PKG_VERSION"),
    ". Do not edit."
);

/// The common trait for all language-specific targets.
///
/// The following targets are available:
///
/// - [`CppTarget`] for C++
/// - [`SwiftTarget`] for Swift
/// - [`WasmTarget`] for JavaScript/TypeScript
/// - [`NullTarget`] otherwise
///
/// Typical usage involves creating a target with `new()`, chaining some
/// methods to configure it, and then calling [`build`](Target::build).
pub trait Target {
    /// Call this on the desired target from your `build.rs` script to generate
    /// the FFI bindings. It automatically locates your `src/lib.rs` file using
    /// the directory containing your `Cargo.toml` manifest, parses it to
    /// determine your packages public API, and then generates FFI bindings for
    /// that API.
    ///
    /// This will always generate the file `miniffi.rs` along with some
    /// additional files that are target-dependent. For example, the
    /// [`SwiftTarget`] additionally generates a `.swift` file and a `.h` file.
    /// The `miniffi.rs` file will be written inside of cargo's `target`
    /// directory, and is normally not something you'll need to think about too
    /// much (other than referencing it via `include!` in your `lib.rs` file).
    /// The other target-dependent files are intended to be included by you
    /// into the host language project. For example, you might add the `.swift`
    /// and `.h` files from the [`SwiftTarget`] to your Xcode project. You
    /// should probably also add all generated files to your `.gitignore` so
    /// they are not checked into source control as they are automatically
    /// generated.
    ///
    /// The returned [`BuildResult`] will be configured to automatically print
    /// some instructions for cargo when it is dropped. Typical usage involves
    /// just calling `build()` on the target without storing the return value.
    /// But you can use the return value to inspect the results of the build.
    /// You can also modify the return value to disable the printing of cargo
    /// instructions on drop if you need different behavior instead.
    fn build(&self) -> BuildResult {
        fn fail(error: &str) -> BuildResult {
            let mut result = BuildResult::default();
            result.errors.push(error.into());
            return result;
        }

        let Ok(input_dir) = std::env::var("CARGO_MANIFEST_DIR") else {
            return fail("missing environment variable: CARGO_MANIFEST_DIR");
        };
        let Ok(output_dir) = std::env::var("OUT_DIR") else {
            return fail("missing environment variable: OUT_DIR");
        };
        let input_path = PathBuf::from(input_dir).join("src").join("lib.rs");
        let output_path = PathBuf::from(output_dir).join("miniffi.rs");

        match std::fs::read_to_string(&input_path) {
            Err(err) => BuildResult {
                errors: vec![format!("Failed to read from {input_path:?}: {err}")],
                warnings: Vec::new(),
                input_path,
                output_files: Vec::new(),
                finish_on_drop: true,
            },
            Ok(contents) => {
                let input_file = FileData {
                    path: input_path,
                    contents,
                };
                let mut result = self.build_custom(input_file, output_path);
                result.finish_on_drop = true;
                result
            }
        }
    }

    /// This is the same as [`build`](Target::build) but without any of the
    /// cargo-specific logic (automatically locating and reading `src/lib.rs`
    /// and automatically printing out instructions for cargo). This can be
    /// useful for running miniffi outside of a cargo build script. If you're
    /// writing a cargo build script, you likely want to call
    /// [`build`](Target::build) instead.
    fn build_custom(&self, input_file: FileData, output_path: PathBuf) -> BuildResult;
}

/// Holds the result of calling [`build`](Target::build) or
/// [`build_custom`](Target::build_custom). May print out cargo
/// instructions and/or write files when dropped.
///
/// Typically you can just call `.build()` on a target and not use the return
/// value. But the return value is available if you need to inspect or modify
/// the build results.
///
/// The result returned from [`build`](Target::build) has `finish_on_drop` set
/// to true which means it will print out cargo instructions and write output
/// files when dropped. If you don't want this behavior (perhaps you need
/// something else to happen instead), then you should set `finish_on_drop` to
/// false before dropping the build result.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BuildResult {
    pub input_path: PathBuf,
    pub output_files: Vec<FileData>,
    pub errors: Vec<String>,
    pub warnings: Vec<Warning>,
    pub finish_on_drop: bool,
}

impl BuildResult {
    /// Certain Rust features are not supported by miniffi. Using those
    /// features will generate a warning and cause the relevant code to be
    /// omitted from the FFI bindings. If you would like for these warnings
    /// to be errors instead (perhaps you want CI to fail when this happens),
    /// you can chain this method off of [`build`](Target::build):
    ///
    /// ```no_run
    /// use miniffi::*;
    ///
    /// fn main() {
    ///     CppTarget::new()
    ///         .build()
    ///         .convert_warnings_to_errors();
    /// }
    /// ```
    ///
    /// Doing this can have undesirable side effects. Because cargo build
    /// scripts run before your crate builds, a build script error stops the
    /// build before your crate is built. This can cause IDE features to stop
    /// working without an obvious cause since some Rust IDE plugins don't
    /// surface build script errors.
    pub fn convert_warnings_to_errors(mut self) -> Self {
        self.errors
            .extend(self.warnings.drain(..).map(|w| w.to_human_string()));
        self
    }

    /// This does the following:
    ///
    /// - Write all output files to the file system
    /// - Print `cargo::rerun-if-changed` lines for all files relevant to the build
    /// - Print `cargo::error` lines for everything in `errors`
    /// - Print `cargo::warning` lines for everything in `warnings`
    /// - Set `self.finish_on_drop` to `false` to avoid finishing on [`drop`](BuildResult::drop)
    pub fn finish(&mut self) {
        println!("cargo::rerun-if-changed={}", self.input_path.display());

        for file in &mut self.output_files {
            println!("cargo::rerun-if-changed={}", file.path.display());
            write_file(&file.path, &file.contents, &mut self.errors);
        }

        for error in &self.errors {
            println!(
                "cargo::error=[miniffi] {}",
                error
                    .split('\n')
                    .collect::<Vec<_>>()
                    .join("\ncargo::error=")
            );
        }

        for warning in &self.warnings {
            println!(
                "cargo::warning=[miniffi] {}",
                warning
                    .to_human_string()
                    .split('\n')
                    .collect::<Vec<_>>()
                    .join("\ncargo::warning=")
            );
        }

        self.finish_on_drop = false;
    }
}

impl Drop for BuildResult {
    /// If `finish_on_drop` is true, dropping a `BuildResult` runs `finish()`
    /// before the drop. If `finish_on_drop` is false, then dropping a
    /// `BuildResult` does nothing.
    fn drop(&mut self) {
        if self.finish_on_drop {
            self.finish();
        }
    }
}

/// Part of a [`BuildResult`].
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Warning {
    pub path: PathBuf,
    pub line: usize,
    pub column: usize,
    pub len: usize,
    pub message: String,
    pub code: String,
    pub note: String,
}

impl Warning {
    /// Returns a single-line string containing the file location and message.
    /// Similar to Rust's "short" message format. For example:
    ///
    /// ```text
    /// /home/user/foo/src/lib.rs:42:11: unsupported type `AtomicBool` for field `flag`
    /// ```
    pub fn to_short_string(&self) -> String {
        format!(
            "{}:{}:{}: {}{}",
            self.path.display(),
            self.line,
            self.column,
            self.message,
            match self.note.as_str() {
                "" => String::new(),
                note => format!(" ({note})"),
            }
        )
    }

    /// Returns a multi-line string containing the file location, message, and
    /// the relevant line of code. Similar to Rust's "human" message format.
    /// For example:
    ///
    /// ```text
    /// unsupported type `AtomicBool` for field `flag`
    ///   --> /home/user/foo/src/lib.rs:42:11
    ///    |
    /// 42 |     flag: AtomicBool,
    ///    |           ^^^^^^^^^^
    /// ```
    pub fn to_human_string(&self) -> String {
        let line = self.line.to_string();
        let indent = " ".repeat(line.len());
        format!(
            "{}\n{indent}--> {}:{}:{}\n{indent} |\n{line} | {}\n{indent} |{}{}{}{}\n",
            self.message,
            self.path.display(),
            self.line,
            self.column,
            self.code,
            " ".repeat(self.column),
            "^".repeat(self.len.max(1)),
            if self.note.is_empty() { "" } else { " " },
            self.note
        )
    }
}

/// Part of a [`BuildResult`].
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FileData {
    pub path: PathBuf,
    pub contents: String,
}

trait Compile {
    fn compile(&self, ast: AST, rust_path: PathBuf) -> Vec<FileData>;
}

impl<T: Compile> Target for T {
    fn build_custom(&self, input_file: FileData, output_path: PathBuf) -> BuildResult {
        let mut output_files = Vec::new();
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        if !input_file.contents.contains("miniffi.rs") {
            let code = r#"include!(concat!(env!("OUT_DIR"), "/miniffi.rs"));"#;
            let file = input_file
                .path
                .file_name()
                .unwrap_or(input_file.path.as_os_str())
                .display();
            errors.push(format!("Please add this to the end of {file:?}: {code}"));
        }

        match syn::parse_file(&input_file.contents) {
            Err(err) => {
                let message = format!("{err}");
                warnings.push(make_warning(&input_file, message, "", err.span()));
            }
            Ok(ast) => {
                let ast = scan::scan_ast(&input_file, &ast, &mut warnings);
                output_files = self.compile(ast, output_path);
            }
        }

        BuildResult {
            input_path: input_file.path,
            output_files,
            errors,
            warnings,
            finish_on_drop: false,
        }
    }
}

/// Use this target when there is no host language.
///
/// The null target creates an empty `miniffi.rs` file. That can be useful if
/// you want to build FFI support for some configurations and not others.
///
/// For example, the following `build.rs` script only builds FFI support when
/// targeting WASM (such as with `cargo build --target=wasm32-unknown-unknown`)
/// and not otherwise (such as running tests with `cargo test`):
///
/// ```no_run
/// use miniffi::*;
///
/// fn main() {
///     let target = std::env::var("TARGET").unwrap();
///     if target == "wasm32-unknown-unknown" {
///         WasmTarget::new().build();
///     } else {
///         NullTarget::new().build();
///     }
/// }
/// ```
pub struct NullTarget {
    _force_new: (),
}

impl NullTarget {
    pub fn new() -> NullTarget {
        NullTarget { _force_new: () }
    }
}

impl Compile for NullTarget {
    fn compile(&self, _ast: AST, rust_path: PathBuf) -> Vec<FileData> {
        vec![FileData {
            path: rust_path,
            contents: String::new(),
        }]
    }
}

fn write_file(path: &Path, contents: &str, errors: &mut Vec<String>) {
    if let Some(parent) = path.parent() {
        if let Err(err) = std::fs::create_dir_all(parent) {
            errors.push(format!("Failed to create directory {parent:?}: {err}"));
        }
    }

    if let Ok(existing) = std::fs::read(&path) {
        if existing == contents.as_bytes() {
            return; // Avoid unnecessary rebuilds
        }
    }

    if let Err(err) = std::fs::write(&path, contents) {
        errors.push(format!("Failed to write to {path:?}: {err}"));
    }
}