-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcallback.rs
More file actions
61 lines (56 loc) · 2.12 KB
/
callback.rs
File metadata and controls
61 lines (56 loc) · 2.12 KB
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
//! This file contains some custom callbacks for bindgen.
use bindgen::callbacks::{Token, TokenKind};
use std::collections::HashSet;
/// This callback will be used to remove the type casts.
/// bindgen has a hard time parsing constants with type casts like
/// ```rust
/// #define SCIP_INVALID (double)1e99
/// ```
///
/// ### Note;
/// Maybe we should be careful on which macros we use this? I can see a situation where Rust and C
/// would have different opinions on what the macro should look like.
#[derive(Debug)]
pub struct DeriveCastedConstant {
/// Set of macros to target for removing type casts
targets: HashSet<String>,
}
impl DeriveCastedConstant {
pub fn new() -> Self {
DeriveCastedConstant {
targets: HashSet::new(),
}
}
pub fn target(mut self, name: &str) -> Self {
self.targets.insert(name.to_string());
self
}
}
/// Implement the ParseCallbacks trait for DeriveCastedConstant
impl bindgen::callbacks::ParseCallbacks for DeriveCastedConstant {
fn modify_macro(&self, _name: &str, _tokens: &mut Vec<Token>) {
// modify SCIP_INVALID
if self.targets.contains(_name) {
// So here we are looking for a pattern like ['(', type, ')']
let position_cast = _tokens.windows(3).position(|window| match window {
[Token {
kind: TokenKind::Punctuation,
raw: left_parenthesis,
}, Token {
// this will not go off on a cast like (SCIP_Real) as SCIP_Real is not a
// Clang-keyword
kind: TokenKind::Keyword,
..
}, Token {
kind: TokenKind::Punctuation,
raw: right_parenthesis,
}] => **left_parenthesis == *b"(" && **right_parenthesis == *b")",
_ => false,
});
if let Some(pos) = position_cast {
// position found! So a macro with a type cast exists. We remove the typecast.
*_tokens = [&_tokens[..pos], &_tokens[pos + 3..]].concat();
}
}
}
}