seesaw 0.1.7

generate traits from C header files
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
use std::{
    borrow::Cow,
    env,
    error::Error,
    fmt,
    io::{self, Write as _},
    ops::BitAnd,
    path::PathBuf,
    process::{Command, Stdio},
    str,
    sync::Arc,
};

use proc_macro2::Span;
use quote::ToTokens as _;
use regex::RegexSet;
use syn::{
    parse_quote, punctuated::Punctuated, token, visit::Visit, Abi, Attribute, Expr, ExprLit,
    ForeignItemFn, Generics, Item, ItemTrait, Lit, LitStr, Meta, MetaNameValue, Token, TraitItem,
    TraitItemFn, Visibility,
};

/// Generate a trait from a `C` header that's passed through [`bindgen`](https://docs.rs/bindgen).
///
/// Returns an error if:
/// - Invalid names or regexes were passed to the constituent [`Trait`]s.
/// - The `bindings` couldn't be parsed as a Rust file.
/// - There was an error writing to `dest`.
///
/// See [crate documentation](crate) for more.
pub fn seesaw<'a>(
    traits: impl Into<TraitSet>,
    bindings: impl fmt::Display,
    dest: impl Into<Destination<'a>>,
) -> io::Result<()> {
    let items = _seesaw(traits.into(), bindings.to_string())?;
    let file = syn::File {
        shebang: None,
        attrs: vec![],
        items: items.into_iter().map(Item::Trait).collect(),
    };

    let mut rustfmt = match env::var_os("RUSTFMT") {
        Some(it) => Command::new(it),
        None => Command::new("rustfmt"),
    };

    let rustfmt = match rustfmt
        .stdin(Stdio::piped())
        .stderr(Stdio::null())
        .stdout(Stdio::piped())
        .spawn()
    {
        Ok(mut child) => {
            let mut stdin = child.stdin.take().unwrap();
            let ts = file.to_token_stream();
            match fmt::write(&mut Write2Write(&mut stdin), format_args!("{ts}")).is_err()
                || stdin.flush().is_err()
            {
                true => None,
                false => {
                    drop(stdin);
                    match child.wait_with_output() {
                        Ok(out) if out.status.success() => Some(out.stdout),
                        _ => None,
                    }
                }
            }
        }
        Err(_) => None,
    };
    let formatted = rustfmt.unwrap_or_else(|| Vec::from(prettyplease::unparse(&file)));

    let mut writer = match dest.into() {
        Destination::Writer(write) => write,
        Destination::Path(it) => Box::new(std::fs::File::create(it)?),
    };
    match option_env!("CARGO_PKG_VERSION") {
        Some(v) => writeln!(writer, "/* this file is @generated by seesaw {v} */\n"),
        None => writeln!(writer, "/* this file is @generated by seesaw */\n"),
    }?;
    io::copy(&mut &formatted[..], &mut writer)?;
    writer.flush()
}

/// Utility struct for where bindings are written.
///
/// Implements [`From<Path>`](std::path::Path) etc.
pub enum Destination<'a> {
    Path(Cow<'a, std::path::Path>),
    Writer(Box<dyn io::Write + 'a>),
}
impl<'a> From<&'a std::path::Path> for Destination<'a> {
    fn from(value: &'a std::path::Path) -> Self {
        Self::Path(Cow::Borrowed(value))
    }
}
impl From<PathBuf> for Destination<'_> {
    fn from(value: PathBuf) -> Self {
        Self::Path(Cow::Owned(value))
    }
}
impl<'a> From<&'a str> for Destination<'a> {
    fn from(value: &'a str) -> Self {
        Self::from(std::path::Path::new(value))
    }
}
impl From<String> for Destination<'_> {
    fn from(value: String) -> Self {
        Self::from(PathBuf::from(value))
    }
}
impl<'a> From<&'a mut Vec<u8>> for Destination<'a> {
    fn from(value: &'a mut Vec<u8>) -> Self {
        Self::Writer(Box::new(value))
    }
}

impl<'a> From<&'a mut String> for Destination<'a> {
    fn from(value: &'a mut String) -> Self {
        Self::Writer(Box::new(Write2Write(value)))
    }
}

macro_rules! ref_writer {
    ($($ty:ty),* $(,)?) => {
        $(
            impl<'a> From<&'a $ty> for Destination<'a> {
                fn from(value: &'a $ty) -> Self {
                    Self::Writer(Box::new(value))
                }
            }
        )*
    };
}
macro_rules! own_writer {
    ($($ty:ty),* $(,)?) => {
        $(
            impl From<$ty> for Destination<'_> {
                fn from(value: $ty) -> Self {
                    Self::Writer(Box::new(value))
                }
            }
        )*
    };
}

ref_writer! {
    io::Empty,
    io::Sink,
    io::Stderr,
    io::Stdout,
    std::fs::File,
    std::net::TcpStream,
    std::process::ChildStdin,
}

own_writer! {
    Arc<std::fs::File>,
    io::Empty,
    io::Sink,
    io::Stderr,
    io::Stdout,
    std::fs::File,
    std::io::StderrLock<'static>,
    std::io::StdoutLock<'static>,
    std::net::TcpStream,
    std::process::ChildStdin,
}

fn _seesaw(TraitSet(traits): TraitSet, bindings: String) -> io::Result<Vec<ItemTrait>> {
    let bindings = err(
        io::ErrorKind::InvalidData,
        syn::parse_file(&bindings.to_string()),
    )?;

    let span = Span::call_site();

    traits
        .into_iter()
        .map(
            |Trait {
                 name,
                 allowlist,
                 blocklist,
                 public,
             }| {
                Ok(ItemTrait {
                    attrs: vec![parse_quote!(#[allow(unused)])],
                    vis: match public {
                        true => Visibility::Public(Token![pub](Span::call_site())),
                        false => Visibility::Inherited,
                    },
                    unsafety: None,
                    auto_token: None,
                    restriction: None,
                    trait_token: Token![trait](span),
                    ident: err(io::ErrorKind::InvalidInput, syn::parse_str(&name))?,
                    generics: Generics::default(),
                    colon_token: None,
                    supertraits: Punctuated::new(),
                    brace_token: token::Brace(span),
                    items: extract(
                        &err(io::ErrorKind::InvalidInput, RegexSet::new(allowlist))?,
                        &err(io::ErrorKind::InvalidInput, RegexSet::new(blocklist))?,
                        &bindings,
                    )
                    .into_iter()
                    .map(|it| {
                        let mut sig = it.sig.clone();
                        sig.unsafety = Some(Token![unsafe](span));
                        sig.abi = Some(Abi {
                            extern_token: Token![extern](span),
                            name: Some(LitStr::new("C", span)),
                        });
                        TraitItem::Fn(TraitItemFn {
                            attrs: it
                                .attrs
                                .clone()
                                .into_iter()
                                .flat_map(break_comments)
                                .collect(),
                            sig,
                            default: None,
                            semi_token: Some(it.semi_token),
                        })
                    })
                    .collect(),
                })
            },
        )
        .collect()
}

/// A specification of a `trait` generated from a `C` header.
///
/// You can [`allow`](Self::allow) and [`block`](Self::block) functions for inclusion.
#[derive(Debug, Clone)]
pub struct Trait {
    public: bool,
    name: String,
    allowlist: Vec<String>,
    blocklist: Vec<String>,
}

impl Trait {
    /// The name of the trait.
    ///
    /// This SHOULD be a valid Rust identifier.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            public: true,
            name: name.into(),
            allowlist: vec![],
            blocklist: vec![],
        }
    }
    /// Change the visibility of the generated trait to private.
    pub fn private(mut self) -> Self {
        self.public = false;
        self
    }
    /// Include functions that match this regex in the trait.
    ///
    /// If this is never called, all functions are included by default.
    pub fn allow(self, s: impl Into<String>) -> Self {
        self.allow_all([s])
    }
    /// Equivalent to calling [`allow`](Self::allow) multiple times.
    pub fn allow_all<S: Into<String>>(mut self, i: impl IntoIterator<Item = S>) -> Self {
        self.allowlist.extend(i.into_iter().map(Into::into));
        self
    }

    /// Exclude functions that match this regex from the trait.
    pub fn block(self, s: impl Into<String>) -> Self {
        self.block_all([s])
    }
    /// Equivalent to calling [`block`](Self::block) multiple times.
    pub fn block_all<S: Into<String>>(mut self, i: impl IntoIterator<Item = S>) -> Self {
        self.blocklist.extend(i.into_iter().map(Into::into));
        self
    }
}

impl BitAnd<Self> for Trait {
    type Output = TraitSet;
    fn bitand(self, rhs: Self) -> Self::Output {
        TraitSet(vec![self, rhs])
    }
}

impl BitAnd<TraitSet> for Trait {
    type Output = TraitSet;
    fn bitand(self, rhs: TraitSet) -> Self::Output {
        rhs & self
    }
}

/// A combination of multiple [`Trait`] definitions.
#[derive(Debug, Default, Clone)]
pub struct TraitSet(Vec<Trait>);

impl TraitSet {
    pub fn new() -> Self {
        Self::default()
    }
}

impl From<Trait> for TraitSet {
    fn from(value: Trait) -> Self {
        Self(vec![value])
    }
}

impl From<String> for TraitSet {
    fn from(value: String) -> Self {
        Trait::new(value).into()
    }
}
impl From<&str> for TraitSet {
    fn from(value: &str) -> Self {
        Self::from(String::from(value))
    }
}

impl BitAnd<Trait> for TraitSet {
    type Output = Self;
    fn bitand(mut self, rhs: Trait) -> Self::Output {
        self.0.push(rhs);
        self
    }
}

impl BitAnd<Self> for TraitSet {
    type Output = Self;
    fn bitand(mut self, mut rhs: Self) -> Self::Output {
        self.0.append(&mut rhs.0);
        self
    }
}

impl Extend<Trait> for TraitSet {
    fn extend<T: IntoIterator<Item = Trait>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

impl FromIterator<Trait> for TraitSet {
    fn from_iter<T: IntoIterator<Item = Trait>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

fn extract<'ast>(
    allowlist: &RegexSet,
    blocklist: &RegexSet,
    file: &'ast syn::File,
) -> Vec<&'ast ForeignItemFn> {
    struct Visitor<'a, 'ast> {
        allowlist: &'a RegexSet,
        blocklist: &'a RegexSet,
        selected: Vec<&'ast ForeignItemFn>,
    }
    impl<'ast> Visit<'ast> for Visitor<'_, 'ast> {
        fn visit_foreign_item_fn(&mut self, i: &'ast ForeignItemFn) {
            if allowed(self.allowlist, self.blocklist, &i.sig.ident.to_string()) {
                self.selected.push(i)
            };
        }
    }
    let mut visitor = Visitor {
        allowlist,
        blocklist,
        selected: vec![],
    };

    visitor.visit_file(file);

    visitor.selected
}

fn allowed(allowlist: &RegexSet, blocklist: &RegexSet, s: &str) -> bool {
    match (
        allowlist.is_empty(),
        allowlist.is_match(s),
        blocklist.is_empty(),
        blocklist.is_match(s),
    ) {
        (_, _, false, true) => false,  // explicit block
        (false, true, _, _) => true,   // explicit allow
        (false, false, _, _) => false, // not allowed
        (true, _, _, _) => true,       // allow by default
    }
}

#[test]
fn test_allowed() {
    #[track_caller]
    fn t(allow: &[&str], block: &[&str], s: &str, expected: bool) {
        let allow = &RegexSet::new(allow).unwrap();
        let block = &RegexSet::new(block).unwrap();
        assert_eq!(
            allowed(allow, block, s),
            expected,
            "allow={allow:?}, block={block:?} on {s}"
        )
    }
    t(&[], &[], "hello", true);
    t(&[], &["hello"], "hello", false);
    t(&["hello"], &["goodbye"], "hello", true);
}

fn err<T>(
    kind: io::ErrorKind,
    res: Result<T, impl Error + Send + Sync + 'static>,
) -> io::Result<T> {
    match res {
        Ok(it) => Ok(it),
        Err(e) => Err(io::Error::new(kind, e)),
    }
}

struct Write2Write<T>(T);

/// You must remember to call [`io::Write::flush`] appropriately.
impl<T: io::Write> fmt::Write for Write2Write<T> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error)
    }
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
        self.0.write_fmt(args).map_err(|_| fmt::Error)
    }
}

impl<T: fmt::Write> io::Write for Write2Write<T> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self
            .0
            .write_str(err(io::ErrorKind::InvalidData, str::from_utf8(buf))?)
        {
            Ok(()) => Ok(buf.len()),
            Err(fmt::Error) => Err(io::ErrorKind::Other)?,
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn break_comments(i: Attribute) -> impl Iterator<Item = Attribute> {
    match i.meta {
        Meta::NameValue(MetaNameValue {
            path,
            eq_token,
            value:
                Expr::Lit(ExprLit {
                    attrs,
                    lit: Lit::Str(doc),
                }),
        }) if path.is_ident("doc") && attrs.is_empty() => doc
            .value()
            .lines()
            .map(|line| Attribute {
                pound_token: Token![#](i.pound_token.span),
                style: match &i.style {
                    syn::AttrStyle::Outer => syn::AttrStyle::Outer,
                    syn::AttrStyle::Inner(not) => syn::AttrStyle::Inner(Token![!](not.span)),
                },
                bracket_token: token::Bracket(i.bracket_token.span),
                meta: Meta::NameValue(MetaNameValue {
                    path: syn::Path::from(path.get_ident().unwrap().clone()),
                    eq_token: Token![=](eq_token.span),
                    value: Expr::Lit(ExprLit {
                        attrs: vec![],
                        lit: Lit::Str(LitStr::new(line, doc.span())),
                    }),
                }),
            })
            .collect::<Vec<_>>()
            .into_iter(),
        _ => vec![i].into_iter(),
    }
}