Skip to main content

rsphp_build_tools/
int_casts.rs

1use bindgen::callbacks::{IntKind, ParseCallbacks, Token, TokenKind};
2use std::cell::RefCell;
3use std::collections::HashMap;
4use std::str;
5
6/// Actual implementation of the `IntTypeCastCallbacks` callbacks.
7#[derive(Debug)]
8struct IntTypeCastCallbacksImpl {
9    /// Map of macros that have been redefined for a specific type, and still
10    /// need to have their type overridden.
11    pending: HashMap<String, IntKind>,
12}
13
14/// Nicer version of [`bindgen::callbacks::Token`] that stores the values as
15/// readable strings.
16#[derive(Debug, Clone, PartialEq, Eq)]
17struct ParsedToken<'tok> {
18    /// Token kind, from bindgen.
19    kind: TokenKind,
20    /// Token content, from parsing the bindgen value.
21    value: &'tok str,
22}
23
24impl<'tok> ParsedToken<'tok> {
25    /// Try to create a `ParsedToken` from a [`bindgen::callbacks::Token`].
26    fn from_raw(token: &'tok Token) -> Result<Self, str::Utf8Error> {
27        str::from_utf8(&token.raw).map(|parsed_value| ParsedToken {
28            kind: token.kind,
29            value: parsed_value,
30        })
31    }
32
33    /// If the overall tokens start with an opening parenthesis and end with
34    /// the closing parenthesis that matches that opening, remove both the
35    /// opening and the closing.
36    fn trim_wrapping_parens(tokens: &mut Vec<ParsedToken<'tok>>) {
37        let Some(ParsedToken {
38            kind: TokenKind::Punctuation,
39            value: "(",
40        }) = tokens.first()
41        else {
42            return;
43        };
44        let Some(ParsedToken {
45            kind: TokenKind::Punctuation,
46            value: ")",
47        }) = tokens.last()
48        else {
49            return;
50        };
51        // Starts and ends with parentheses, see if they match
52        let last = tokens.len() - 1;
53        let mut nesting_level: usize = 0;
54        for (index, tok) in tokens.iter().enumerate() {
55            match tok {
56                ParsedToken {
57                    kind: TokenKind::Punctuation,
58                    value: "(",
59                } => nesting_level += 1,
60                ParsedToken {
61                    kind: TokenKind::Punctuation,
62                    value: ")",
63                } => nesting_level -= 1,
64                _ => (),
65            }
66            if nesting_level == 0 {
67                if index != last {
68                    return;
69                }
70                break;
71            }
72        }
73        // If we got here, the parens should be trimmed
74        assert_eq!(
75            Some(ParsedToken {
76                kind: TokenKind::Punctuation,
77                value: ")"
78            }),
79            tokens.pop(),
80            "Tokens were checked to end with a parenthesis",
81        );
82        assert_eq!(
83            ParsedToken {
84                kind: TokenKind::Punctuation,
85                value: "("
86            },
87            tokens.remove(0),
88            "Tokens were checked to start with a parenthesis",
89        );
90    }
91}
92
93impl IntTypeCastCallbacksImpl {
94    /// Create a new instance that has not processed anything yet.
95    fn new() -> Self {
96        IntTypeCastCallbacksImpl {
97            pending: HashMap::new(),
98        }
99    }
100
101    /// Implementation of parser callback to specify an integer macro type,
102    /// applying any pending override from a modification.
103    fn int_macro(&mut self, name: &str) -> Option<IntKind> {
104        self.pending.remove(name)
105    }
106
107    /// Implementation of parser callback to modify a macro, replacing C casts
108    /// with the resulting value if applicable.
109    fn modify_macro(&mut self, name: &str, tokens: &mut Vec<Token>) {
110        let Ok(mut parsed) = tokens
111            .iter()
112            .map(ParsedToken::from_raw)
113            .collect::<Result<Vec<_>, _>>()
114        else {
115            return;
116        };
117        // Double check that the macro starts with the name
118        if parsed.is_empty() {
119            return;
120        }
121        let first = parsed.remove(0);
122        if first.kind != TokenKind::Identifier || first.value != name {
123            return;
124        }
125        ParsedToken::trim_wrapping_parens(&mut parsed);
126
127        let [
128            ParsedToken {
129                kind: TokenKind::Punctuation,
130                value: "(",
131            },
132            ParsedToken {
133                kind: TokenKind::Identifier,
134                value: cast_target_type,
135            },
136            ParsedToken {
137                kind: TokenKind::Punctuation,
138                value: ")",
139            },
140            ParsedToken {
141                kind: TokenKind::Punctuation,
142                value: "-",
143            },
144            ParsedToken {
145                kind: TokenKind::Literal,
146                value: cast_target_value,
147            },
148        ] = parsed[..]
149        else {
150            return;
151        };
152
153        match cast_target_type {
154            "uint32_t" => {
155                let Ok(value) = cast_target_value.parse::<u32>() else {
156                    return;
157                };
158                let new_value: u32 = u32::MIN.wrapping_sub(value);
159                #[expect(clippy::panic, reason = "No nicer option in HashMap")]
160                match self.pending.insert(name.to_owned(), IntKind::U32) {
161                    None => (),
162                    Some(old) => panic!("Redefining macro {name}, previously was {old:?}"),
163                }
164                tokens.truncate(1);
165                tokens.push({
166                    Token {
167                        kind: TokenKind::Literal,
168                        raw: new_value.to_string().into_bytes().into_boxed_slice(),
169                    }
170                });
171            }
172            "uint16_t" => {
173                let Ok(value) = cast_target_value.parse::<u16>() else {
174                    return;
175                };
176                let new_value: u16 = u16::MIN.wrapping_sub(value);
177                #[expect(clippy::panic, reason = "No nicer option in HashMap")]
178                match self.pending.insert(name.to_owned(), IntKind::U16) {
179                    None => (),
180                    Some(old) => panic!("Redefining macro {name}, previously was {old:?}"),
181                }
182                tokens.truncate(1);
183                tokens.push({
184                    Token {
185                        kind: TokenKind::Literal,
186                        raw: new_value.to_string().into_bytes().into_boxed_slice(),
187                    }
188                });
189            }
190            _ => (),
191        }
192    }
193}
194
195impl Drop for IntTypeCastCallbacksImpl {
196    #[expect(clippy::print_stderr, reason = "Better to print than to double panic")]
197    fn drop(&mut self) {
198        // Avoid double panics if we didn't get through reading all of the tokens
199        if !self.pending.is_empty() && std::thread::panicking() {
200            eprintln!(
201                "IntTypeCastCallbacks: Not all type overrides were used, but thread is already panicking"
202            );
203            return;
204        }
205        assert!(
206            self.pending.is_empty(),
207            "All type overrides should be used, remaining: {:?}",
208            self.pending
209        );
210    }
211}
212
213/// Callbacks to fix handling of C macros that are defined as integer casts.
214#[derive(Debug)]
215pub struct IntTypeCastCallbacks {
216    /// The actual implementation, wrapped in a `RefCell` because it needs to
217    /// allow mutability.
218    inner: RefCell<IntTypeCastCallbacksImpl>,
219}
220
221#[expect(
222    clippy::new_without_default,
223    reason = "Default isn't really applicable"
224)]
225impl IntTypeCastCallbacks {
226    /// Create a new callbacks instance to handle int macro casts.
227    #[must_use]
228    pub fn new() -> Self {
229        IntTypeCastCallbacks {
230            inner: RefCell::new(IntTypeCastCallbacksImpl::new()),
231        }
232    }
233}
234
235impl ParseCallbacks for IntTypeCastCallbacks {
236    fn int_macro(&self, name: &str, _value: i64) -> Option<IntKind> {
237        self.inner.borrow_mut().int_macro(name)
238    }
239
240    fn modify_macro(&self, name: &str, tokens: &mut Vec<Token>) {
241        self.inner.borrow_mut().modify_macro(name, tokens);
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn trim_parens() {
251        use bindgen::callbacks::TokenKind::*;
252        let mut tokens = vec![
253            ParsedToken {
254                kind: Punctuation,
255                value: "(",
256            },
257            ParsedToken {
258                kind: Literal,
259                value: "5",
260            },
261            ParsedToken {
262                kind: Punctuation,
263                value: ")",
264            },
265        ];
266        ParsedToken::trim_wrapping_parens(&mut tokens);
267        assert_eq!(
268            vec![ParsedToken {
269                kind: Literal,
270                value: "5"
271            }],
272            tokens
273        );
274    }
275}