leach 0.3.1

Streamlined FFI and cross-compilation with this powerful build-helper replacement.
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright (c) 2022-2026 Sprite Tong (<spritetong@gmail.com>)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! Build configuration and FFI binding generation for C/C++ projects.
//! Provides `BindgenConfig` for header parsing and code generation via `bindgen`.

use super::*;
use std::{
    borrow::Cow,
    collections::{hash_map::DefaultHasher, BTreeMap, VecDeque},
    hash::{Hash, Hasher},
    io::Read,
};

/// Configuration builder for generating Rust FFI bindings from C/C++ headers.
#[derive(Clone, Default, Hash)]
pub struct Bindgen {
    rs_file: Option<PathBuf>,
    allow_bad_code_styles: bool,
    headers: Vec<String>,
    includes: Vec<String>,
    definitions: Vec<(String, String)>,
    allowlist: Vec<String>,
    blocklist: Vec<String>,
    header_codes: Vec<String>,
    footer_codes: Vec<String>,
    derive: BTreeMap<String, Vec<String>>,
}

/// Callback invoked before bindgen code generation.
///
/// Receives a mutable reference to the `Bindgen` config and the
/// `bindgen::Builder`, allowing last-minute modifications to headers,
/// flags, or builder settings before code generation runs.
pub type BeforeBindgenCb =
    dyn FnOnce(&mut Bindgen, bindgen::Builder) -> io::Result<bindgen::Builder>;

impl Bindgen {
    /// Sets the output Rust file path for the generated bindings.
    ///
    /// # Arguments
    /// * `rs_file` - Path to the output Rust file
    pub fn rs_file<T: Into<PathBuf>>(&mut self, rs_file: T) -> &mut Self {
        self.rs_file = Some(rs_file.into());
        self
    }

    /// Enables generation of code that may not follow Rust style guidelines.
    pub fn allow_bad_code_styles(&mut self) -> &mut Self {
        self.allow_bad_code_styles = true;
        self
    }

    /// Enforces Rust style guidelines in generated code.
    pub fn deny_bad_code_styles(&mut self) -> &mut Self {
        self.allow_bad_code_styles = false;
        self
    }

    /// Adds a header file to be processed for FFI binding generation.
    ///
    /// # Arguments
    /// * `header` - Path to the C/C++ header file
    pub fn header<T: AsRef<Path>>(&mut self, header: T) -> &mut Self {
        self.headers.push(Self::norm_path(realpath(header)));
        self
    }

    /// Adds multiple header files to be processed for FFI binding generation.
    ///
    /// # Arguments
    /// * `headers` - Iterator of paths to C/C++ header files
    pub fn headers<T>(&mut self, headers: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: AsRef<Path>,
    {
        self.headers
            .extend(headers.into_iter().map(|x| Self::norm_path(realpath(x))));
        self
    }

    /// Adds an include directory for header file resolution.
    ///
    /// # Arguments
    /// * `include` - Path to include directory
    pub fn include<T: AsRef<Path>>(&mut self, include: T) -> &mut Self {
        self.includes.push(Self::norm_path(include));
        self
    }

    /// Adds multiple include directories for header file resolution.
    ///
    /// # Arguments
    /// * `includes` - Iterator of paths to include directories
    pub fn includes<T>(&mut self, includes: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: AsRef<Path>,
    {
        self.includes
            .extend(includes.into_iter().map(Self::norm_path));
        self
    }

    /// Sets the include directories from cmkabe's configuration.
    pub fn cmake_includes(&mut self) -> &mut Self {
        for dir in cmkabe::cmake_include_dirs() {
            self.includes.push(dir.display().to_string());
        }
        self
    }

    /// Adds a preprocessor definition.
    ///
    /// # Arguments
    /// * `name` - Name of the macro to define
    /// * `value` - Value to define the macro as
    pub fn definition<K, V>(&mut self, name: K, value: V) -> &mut Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.definitions.push((name.into(), value.into()));
        self
    }

    /// Adds multiple preprocessor definitions.
    ///
    /// # Arguments
    /// * `definitions` - Iterator of (name, value) pairs for macro definitions
    pub fn definitions<T, K, V>(&mut self, definitions: T) -> &mut Self
    where
        T: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.definitions
            .extend(definitions.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Specifies items to include in the bindings (whitelist).
    ///
    /// # Arguments
    /// * `allowlist` - Iterator of item names to include
    pub fn allowlist<T>(&mut self, allowlist: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: Into<String>,
    {
        self.allowlist
            .extend(allowlist.into_iter().map(|x| x.into()));
        self
    }

    /// Specifies items to exclude from the bindings (blacklist).
    ///
    /// # Arguments
    /// * `blocklist` - Iterator of item names to exclude
    pub fn blocklist<T>(&mut self, blocklist: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: Into<String>,
    {
        self.blocklist
            .extend(blocklist.into_iter().map(|x| x.into()));
        self
    }

    /// Adds a raw line of Rust code at the beginning of the generated bindings.
    ///
    /// # Arguments
    /// * `line` - Line of Rust code to add
    pub fn raw_line<T: Into<String>>(&mut self, line: T) -> &mut Self {
        self.header_codes.push(line.into());
        self
    }

    /// Adds multiple raw lines of Rust code at the beginning of the generated bindings.
    ///
    /// # Arguments
    /// * `lines` - Iterator of Rust code lines to add
    pub fn raw_lines<T>(&mut self, lines: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: Into<String>,
    {
        self.header_codes
            .extend(lines.into_iter().map(|x| x.into()));
        self
    }

    /// Adds a raw line of Rust code at the end of the generated bindings.
    ///
    /// # Arguments
    /// * `line` - Line of Rust code to add
    pub fn tail_raw_line<T: Into<String>>(&mut self, line: T) -> &mut Self {
        self.footer_codes.push(line.into());
        self
    }

    /// Adds multiple raw lines of Rust code at the end of the generated bindings.
    ///
    /// # Arguments
    /// * `lines` - Iterator of Rust code lines to add
    pub fn tail_raw_lines<T>(&mut self, lines: T) -> &mut Self
    where
        T: IntoIterator,
        T::Item: Into<String>,
    {
        self.footer_codes
            .extend(lines.into_iter().map(|x| x.into()));
        self
    }

    /// Specifies trait derivations for generated types.
    ///
    /// # Arguments
    /// * `types` - Types to apply the derivations to
    /// * `traits` - Traits to derive
    pub fn derive<N, T>(&mut self, types: T, traits: N) -> &mut Self
    where
        T: IntoIterator,
        T::Item: Into<String>,
        N: IntoIterator,
        N::Item: Into<String>,
    {
        let mut types = types.into_iter().map(|x| x.into()).collect::<Vec<String>>();
        let traits = traits
            .into_iter()
            .map(|x| x.into())
            .collect::<Vec<String>>();
        if types.is_empty() {
            types.push(String::new())
        }
        for ty in types.iter() {
            if !self.derive.contains_key(ty) {
                self.derive.insert(ty.clone(), Vec::new());
            }
            let lst = self.derive.get_mut(ty).unwrap();
            for tr in traits.iter() {
                if !lst.contains(tr) {
                    lst.push(tr.clone());
                }
            }
        }
        self
    }

    /// Generates the Rust FFI bindings based on the configured settings.
    ///
    /// # Arguments
    /// * `f` - Optional callback for additional builder configuration
    ///
    /// # Returns
    /// * `io::Result<()>` - Success or error status
    pub fn generate(&mut self, f: Option<Box<BeforeBindgenCb>>) -> io::Result<()> {
        use bindgen::callbacks::ParseCallbacks;
        #[derive(Debug)]
        struct DependCallbacks {
            root: String,
            cell: RefCell<(fs::File, HashSet<String>)>,
        }
        impl ParseCallbacks for DependCallbacks {
            fn include_file(&self, filename: &str) {
                let filename = Bindgen::norm_path(filename);
                if filename.starts_with(&self.root) {
                    let mut cell = self.cell.borrow_mut();
                    if !cell.1.contains(&filename) {
                        let _ = writeln!(cell.0, "{}", &filename);
                        rerun_if_changed(&filename);
                        cell.1.insert(filename);
                    }
                }
            }
        }
        impl DependCallbacks {
            fn new(root: &Path, dep_file: &Path, headers: &[String]) -> io::Result<Self> {
                let cb = Self {
                    root: Bindgen::norm_path(root),
                    cell: RefCell::new((
                        fs::OpenOptions::new()
                            .write(true)
                            .truncate(true)
                            .create(true)
                            .open(dep_file)?,
                        HashSet::new(),
                    )),
                };

                for header in headers.iter() {
                    cb.include_file(header);
                }
                // Write an empty line to seperate the original headers from parsed dependencies.
                writeln!(cb.cell.borrow_mut().0)?;

                Ok(cb)
            }

            fn is_rebuild_required(rs_file: &Path, dep_file: &Path, headers: &[String]) -> bool {
                if let Ok(metadata) = fs::metadata(rs_file) {
                    let rs_mtime = FileTime::from_last_modification_time(&metadata);
                    if let Ok(f) = fs::File::open(dep_file) {
                        #[allow(clippy::lines_filter_map_ok)]
                        let lines: Vec<String> = io::BufReader::new(f)
                            .lines()
                            .map_while(Result::ok)
                            .collect();

                        // Compare the current headers to the previous headers.
                        let old: Vec<&String> =
                            lines.iter().take_while(|&x| !x.is_empty()).collect();
                        let matching = headers
                            .iter()
                            .zip(old.iter())
                            .filter(|&(a, &b)| a == b)
                            .count();
                        if matching == headers.len() && matching == old.len() {
                            let mut skip = true;
                            for dep in lines.iter().filter(|&x| !x.is_empty()) {
                                match fs::metadata(dep)
                                    .map(|x| FileTime::from_last_modification_time(&x))
                                {
                                    Ok(mtime) => {
                                        // Check <rs_file> and header file's update timestamp.
                                        if rs_mtime < mtime {
                                            skip = false;
                                            break;
                                        }
                                    }
                                    Err(_) => {
                                        skip = false;
                                        break;
                                    }
                                }
                            }
                            if skip {
                                for dep in lines.iter().filter(|&x| !x.is_empty()) {
                                    rerun_if_changed(dep);
                                }
                                return false;
                            }
                        }
                    }
                }
                true
            }
        }

        let root = Self::norm_path(cargo::workspace_dir());
        let rs_file = match self.rs_file.as_ref() {
            Some(x) => Self::norm_path(realpath(x)),
            _ => return Err(io::Error::new(io::ErrorKind::InvalidData, "No <rs_file>")),
        };

        // Sort headers & derive crates.
        self.headers.sort();

        // File to store dependencies.
        let dep_file = out_dir()
            .with_file_name(
                rs_file
                    .strip_prefix(&root)
                    .and_then(|x| x.strip_prefix('/'))
                    .unwrap_or(&rs_file)
                    .replace(':', "_")
                    .replace('/', "__"),
            )
            .with_extension("leach.d");
        let hash_file = dep_file.with_extension("hash");

        // Watch the output file.
        rerun_if_changed(&rs_file);

        // Check timestamp of dependencies.
        let hash = {
            let mut hasher = DefaultHasher::new();
            self.hash(&mut hasher);
            hasher.finish()
        };
        if !self.is_hash_changed(&hash_file, hash)
            && !DependCallbacks::is_rebuild_required(
                Path::new(&rs_file),
                dep_file.as_ref(),
                self.headers.as_slice(),
            )
        {
            return Ok(());
        }
        // Create file to store dependencies.
        let depen_callback = Box::new(DependCallbacks::new(
            Path::new(&root),
            &dep_file,
            self.headers.as_slice(),
        )?);

        // Create builder.
        let mut builder = Self::default_builder();

        // Common derivation.
        if let Some(traits) = self.derive.get("") {
            for tr in traits {
                match tr.as_str() {
                    "Copy" => builder = builder.derive_copy(true),
                    "Debug" => builder = builder.derive_debug(true),
                    "Default" => builder = builder.derive_default(true),
                    "Hash" => builder = builder.derive_hash(true),
                    "PartialOrd" => builder = builder.derive_partialord(true),
                    "Ord" => builder = builder.derive_ord(true),
                    "PartialEq" => builder = builder.derive_partialeq(true),
                    "Eq" => builder = builder.derive_eq(true),
                    _ => (),
                }
            }
        }

        // C headers
        for header in self.headers.iter() {
            builder = builder.header(header);
        }

        // Include directories
        for include in self.includes.iter() {
            builder = builder.clang_arg(format!("-I{include}"))
        }

        // Macro definitions
        for (name, value) in self.definitions.iter() {
            builder = builder.clang_arg(format!("-D{name}={value}"))
        }

        // Header codes
        if self.allow_bad_code_styles {
            builder = builder
                .raw_line("#![allow(dead_code)]")
                .raw_line("#![allow(improper_ctypes)]")
                .raw_line("#![allow(improper_ctypes_definitions)]")
                .raw_line("#![allow(non_camel_case_types)]")
                .raw_line("#![allow(non_snake_case)]")
                .raw_line("#![allow(non_upper_case_globals)]")
                .raw_line("#![allow(clippy::missing_safety_doc)]")
                .raw_line("#![allow(clippy::missing_transmute_annotations)]")
                .raw_line("#![allow(clippy::too_many_arguments)]")
                .raw_line("#![allow(clippy::useless_transmute)]");
            if !self.header_codes.is_empty() {
                builder = builder.raw_line("");
            }
        }
        for line in self.header_codes.iter() {
            builder = builder.raw_line(line);
        }

        // Set allowlist
        for name in self.allowlist.iter() {
            builder = builder
                .allowlist_function(name)
                .allowlist_type(name)
                .allowlist_var(name);
        }

        // Set blocklist
        for name in self.blocklist.iter() {
            builder = builder.blocklist_item(name);
        }

        // Store depenencies.
        builder = builder.parse_callbacks(depen_callback);

        // Apply custom operation on the builder.
        if let Some(f) = f {
            builder = f(self, builder)?;
        }

        // Build the FFI file.
        let bindings = builder.generate().map_err(io::Error::other)?;

        // Write the .rs file.
        let mut buf = Vec::<u8>::new();
        let mut w = io::Cursor::new(&mut buf);
        bindings.write(Box::new(&mut w))?;
        if !self.footer_codes.is_empty() {
            w.write_all(b"\n")?;
            for line in self.footer_codes.iter() {
                w.write_all(line.as_bytes())?;
                w.write_all(b"\n")?;
            }
        }
        w.flush()?;
        let file = fs::OpenOptions::new()
            .truncate(true)
            .create(true)
            .write(true)
            .open(&rs_file)?;
        Self::apply_derive(self, file, buf)?;

        self.write_hash(&hash_file, hash)
    }

    fn is_hash_changed(&self, hash_file: &Path, hash: u64) -> bool {
        if let Ok(mut f) = fs::File::open(hash_file) {
            let mut buf = String::new();
            f.read_to_string(&mut buf).ok();
            if buf.parse::<u64>() == Ok(hash) {
                return false;
            }
        }
        true
    }

    fn write_hash(&self, hash_file: &Path, hash: u64) -> io::Result<()> {
        let mut f = fs::File::create(hash_file)?;
        f.write_all(hash.to_string().as_bytes())
    }

    fn apply_derive(&self, mut file: fs::File, text: Vec<u8>) -> io::Result<()> {
        let mut lines: VecDeque<Cow<'_, str>> = text
            .split(|&x| x == b'\n')
            .map(|x| String::from_utf8_lossy(x.strip_suffix(b"\r").unwrap_or(x)))
            .collect();

        let derive_re = Regex::new(r"^#\[derive\(([[[:word:]], ]+)\)\]$").unwrap();
        let type_re = Regex::new(r"^pub (?:enum|struct) ([[:word:]]+) \{$").unwrap();

        // UTF-8 BOM
        file.write_all(b"\xEF\xBB\xBF")?;

        // Remove all empty lines at the tail.
        while let Some(line) = lines.back() {
            if line.is_empty() {
                lines.pop_back();
            } else {
                break;
            }
        }

        while let Some(line) = lines.pop_front() {
            if let Some(cap) = derive_re.captures(&line) {
                let derived = cap[1].split(',').map(|x| x.trim()).collect::<Vec<&str>>();
                let mut traits = derived.clone();
                for next_line in lines.iter() {
                    if let Some(cap) = type_re.captures(next_line) {
                        for ty in ["", &cap[1]] {
                            if let Some(derive) = self.derive.get(ty) {
                                for pattern in derive {
                                    if let Some(tr) = pattern.strip_prefix('-') {
                                        if let Some(i) = traits.iter().position(|&x| x == tr) {
                                            traits.remove(i);
                                        }
                                    } else {
                                        let tr = pattern.strip_prefix('+').unwrap_or(pattern);
                                        if !traits.contains(&tr)
                                            && (derived.contains(&tr) || !self.is_auto_derive(tr))
                                        {
                                            traits.push(tr);
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
                if !traits.is_empty() {
                    file.write_all(format!("#[derive({})]", traits.join(", ")).as_bytes())?;
                } else {
                    traits.sort();
                    file.write_all(b"// No derivation")?;
                }
            } else {
                file.write_all(line.as_bytes())?;
            }
            file.write_all(b"\n")?;
        }
        Ok(())
    }

    fn is_auto_derive(&self, trait_: &str) -> bool {
        self.derive
            .get("")
            .map(|x| x.iter().any(|x| x == trait_))
            .unwrap_or(false)
            && [
                "Copy",
                "Debug",
                "Default",
                "Hash",
                "PartialOrd",
                "Ord",
                "PartialEq",
                "Eq",
            ]
            .contains(&trait_)
    }

    fn norm_path<P: AsRef<Path>>(path: P) -> String {
        path.as_ref().to_string_lossy().as_ref().replace('\\', "/")
    }

    fn default_builder() -> bindgen::Builder {
        bindgen::Builder::default()
            .disable_header_comment()
            .layout_tests(false)
            .formatter(bindgen::Formatter::Rustfmt)
            .prepend_enum_name(false)
            .size_t_is_usize(true)
    }
}