aboutsummaryrefslogtreecommitdiff
path: root/rustables-sys/generate_bindings.sh
blob: dc1455ccb45bb0057c66eba2fb6188d0a4233e9f (plain) (blame)
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
#!/usr/bin/env bash

# give libnftnl C library dir as first argument and output binding as second.
# Example:
#  $ ./generate_bindings.sh ../../libnftnl-1.0.8 src/nftnl_1_0_8.rs

set -ue

LIBNFTNL_PATH=$1
BINDING_PATH=$2

echo "Writing the result to $BINDING_PATH"

bindgen \
    --no-doc-comments \
    --use-core \
    --no-prepend-enum-name \
    --whitelist-function '^nftnl_.+$' \
    --whitelist-type '^nftnl_.+$' \
    --whitelist-var '^nftnl_.+$' \
    --whitelist-var '^NFTNL_.+$' \
    --blacklist-type '(FILE|iovec)' \
    --blacklist-type '^_IO_.+$' \
    --blacklist-type '^__.+$' \
    --blacklist-type 'nlmsghdr' \
    --raw-line 'use libc::{c_char, c_int, c_void, iovec, nlmsghdr, FILE};' \
    --raw-line 'use core::option::Option;' \
    --ctypes-prefix 'libc' \
    -o $BINDING_PATH \
    libnftnl.h --\
    -I$LIBNFTNL_PATH/include

# Tidy up and correct things I could not manage to configure bindgen to do for me
sed -i 's/libc::\(c_[a-z]*\)/\1/g'  $BINDING_PATH
sed -i 's/::core::option::Option/Option/g' $BINDING_PATH
sed -i 's/_bindgen_ty_[0-9]\+/u32/g' $BINDING_PATH
sed -i 's/pub type u32 = u32;//g' $BINDING_PATH
sed -i '/#\[derive(Debug, Copy, Clone)\]/d' $BINDING_PATH

# Change struct bodies to (c_void);
#   Search regex: {\n +_unused: \[u8; 0],\n}
#   Replace string: (c_void);\n
sed -i -e '/^pub struct .* {$/ {
    N;N
    s/ {\n *_unused: \[u8; 0\],\n}/(c_void);\n/
}' "$BINDING_PATH"


# Remove all }\nextern "C" { to condense code a bit
#   Search regex: }\nextern "C" {
#   Replace string: 
sed -i -e '/^extern "C" {$/ {
    :loop
    n
    /^}$/! b loop
    /^}$/ {
        N
        t reset_condition_flags
        :reset_condition_flags
        s/}\nextern "C" {//
        t loop
    }
}' "$BINDING_PATH"

# Add bindgen version to comment at start of file
sed -i "1s/bindgen/$(bindgen --version)/" $BINDING_PATH

rustfmt $BINDING_PATH