Skip to main content

rsphp_build_tools/
build_id.rs

1use bindgen::callbacks::{ParseCallbacks, Token, TokenKind};
2use std::cell::RefCell;
3
4/// Actual implementation of the `BuildIdCallbacks` callbacks.
5#[derive(Debug)]
6struct BuildIdCallbacksImpl {
7    /// The API number to use, from the `ZEND_MODULE_API_NO` macro.
8    ///
9    /// `None` until the macro is processed.
10    api_no: Option<String>,
11    /// Either `ZTS` or `NTS`, from the `ZEND_BUILD_TS` macro.
12    ///
13    /// `None` until the macro is processed.
14    build_ts: Option<&'static str>,
15    /// Either an empty string or `,debug`, from the `ZEND_BUILD_DEBUG` macro.
16    ///
17    /// `None` until the macro is processed.
18    build_debug: Option<&'static str>,
19    /// Whether the build ID was actually updated, if this is still
20    /// false when the object is `drop`ed it will panic.
21    updated_build_id: bool,
22}
23
24/// Helper to create a token for the given kind and content for comparison.
25macro_rules! make_token {
26    ( $kind:ident, $str:literal ) => {
27        Token {
28            kind: TokenKind::$kind,
29            raw: $str.to_string().into_bytes().into_boxed_slice(),
30        }
31    };
32}
33
34impl BuildIdCallbacksImpl {
35    /// Create a new instance that has not processed anything yet.
36    fn new() -> Self {
37        BuildIdCallbacksImpl {
38            api_no: None,
39            build_ts: None,
40            build_debug: None,
41            updated_build_id: false,
42        }
43    }
44
45    /// Process the declaration of the `ZEND_MODULE_API_NO` macro.
46    fn read_api_no(&mut self, tokens: &Vec<Token>) {
47        assert_eq!(
48            None, self.api_no,
49            "ZEND_MODULE_API_NO should not have been read yet"
50        );
51        assert_eq!(
52            2,
53            tokens.len(),
54            "ZEND_MODULE_API_NO should have 2 tokens, the name and the number, got: {tokens:?}"
55        );
56        assert_eq!(
57            make_token!(Identifier, "ZEND_MODULE_API_NO"),
58            tokens[0],
59            "ZEND_MODULE_API_NO is being declared"
60        );
61        assert_eq!(
62            TokenKind::Literal,
63            tokens[1].kind,
64            "ZEND_MODULE_API_NO should be a literal"
65        );
66        self.api_no = Some(
67            std::str::from_utf8(&tokens[1].raw)
68                .expect("Should be valid UTF8")
69                .to_owned(),
70        );
71    }
72
73    /// Process the declaration of the `ZEND_BUILD_TS` macro.
74    fn read_build_ts(&mut self, tokens: &Vec<Token>) {
75        assert_eq!(
76            None, self.build_ts,
77            "ZEND_BUILD_TS should not have been read yet"
78        );
79        assert_eq!(
80            2,
81            tokens.len(),
82            "ZEND_BUILD_TS should have 2 tokens, the name and the timestamp, got: {tokens:?}"
83        );
84        assert_eq!(
85            make_token!(Identifier, "ZEND_BUILD_TS"),
86            tokens[0],
87            "ZEND_BUILD_TS is being declared"
88        );
89        if tokens[1] == make_token!(Literal, "\",TS\"") {
90            self.build_ts = Some("TS");
91        } else {
92            assert_eq!(
93                make_token!(Literal, "\",NTS\""),
94                tokens[1],
95                "ZEND_BUILD_TS is either TS or NTS"
96            );
97            self.build_ts = Some("NTS");
98        }
99    }
100
101    /// Process the declaration of the `ZEND_BUILD_DEBUG` macro.
102    fn read_build_debug(&mut self, tokens: &Vec<Token>) {
103        assert_eq!(
104            None, self.build_debug,
105            "ZEND_BUILD_DEBUG should not have been read yet"
106        );
107        assert!(
108            !tokens.is_empty(),
109            "ZEND_BUILD_DEBUG should have 1 or 2 tokens, the name either '1' or no second token, got: {tokens:?}"
110        );
111        assert_eq!(
112            make_token!(Identifier, "ZEND_BUILD_DEBUG"),
113            tokens[0],
114            "ZEND_BUILD_DEBUG is being declared"
115        );
116        if tokens.len() == 1 {
117            self.build_debug = Some("");
118        } else {
119            assert_eq!(
120                2,
121                tokens.len(),
122                "ZEND_BUILD_DEBUG cannot have more than 2 tokens"
123            );
124            assert_eq!(
125                make_token!(Literal, "\",debug\""),
126                tokens[1],
127                "ZEND_BUILD_DEBUG can only be \",debug\" if set"
128            );
129            self.build_debug = Some(",debug");
130        }
131    }
132
133    /// Given the tokens for the `ZEND_MODULE_BUILD_ID` macro, replace them with
134    /// a generated version that bindgen can use.
135    fn replace_build_id(&mut self, tokens: &mut Vec<Token>) {
136        assert!(
137            !self.updated_build_id,
138            "ZEND_MODULE_BUILD_ID should not have been updated yet"
139        );
140        macro_rules! make_tokens {
141            ( $( ( $kind:ident, $str:literal ) ),+ ) => { vec![ $( make_token!( $kind, $str ) ),+ ] }
142        }
143        assert_eq!(
144            &make_tokens!(
145                (Identifier, "ZEND_MODULE_BUILD_ID"),
146                (Literal, "\"API\""),
147                (Identifier, "ZEND_TOSTR"),
148                (Punctuation, "("),
149                (Identifier, "ZEND_MODULE_API_NO"),
150                (Punctuation, ")"),
151                (Identifier, "ZEND_BUILD_TS"),
152                (Identifier, "ZEND_BUILD_DEBUG"),
153                (Identifier, "ZEND_BUILD_SYSTEM"),
154                (Identifier, "ZEND_BUILD_EXTRA")
155            ),
156            tokens,
157            "ZEND_MODULE_BUILD_ID is being declared",
158        );
159        assert!(self.api_no.is_some(), "API number should be read already");
160        assert!(self.build_ts.is_some(), "Build ts should be read already");
161        assert!(
162            self.build_debug.is_some(),
163            "Build debug should be read already"
164        );
165        tokens.truncate(1);
166        tokens.push(Token {
167            kind: TokenKind::Literal,
168            raw: format!(
169                "\"API{},{}{}\"",
170                self.api_no.as_ref().expect("Confirmed to not be none"),
171                self.build_ts.as_ref().expect("Confirmed to not be none"),
172                self.build_debug.as_ref().expect("Confirmed to not be none"),
173            )
174            .into_bytes()
175            .into_boxed_slice(),
176        });
177        self.updated_build_id = true;
178    }
179}
180
181impl Drop for BuildIdCallbacksImpl {
182    #[expect(clippy::print_stderr, reason = "Better to print than to double panic")]
183    fn drop(&mut self) {
184        // Avoid double panics if we didn't get through reading all of the tokens
185        if !self.updated_build_id
186            && (self.api_no.is_none() || self.build_ts.is_none() || self.build_debug.is_none())
187            && std::thread::panicking()
188        {
189            eprintln!(
190                "BuildIdCallbacks: Build ID was not updated, but thread is already panicking"
191            );
192            return;
193        }
194        // Chck the preconditions so that failures are clearer
195        assert!(self.api_no.is_some(), "Drop: missing API number");
196        assert!(self.build_ts.is_some(), "Drop: missing build ts");
197        assert!(self.build_debug.is_some(), "Drop: missing build debug");
198        assert!(self.updated_build_id, "Drop: build ID not updated");
199    }
200}
201
202/// Callbacks to modify the `ZEND_MODULE_BUILD_ID` C macro to make it usable
203/// by bindgen.
204#[derive(Debug)]
205pub struct BuildIdCallbacks {
206    /// The actual implementation, wrapped in a `RefCell` because it needs to
207    /// allow mutability.
208    inner: RefCell<BuildIdCallbacksImpl>,
209}
210
211#[expect(
212    clippy::new_without_default,
213    reason = "Default isn't really applicable"
214)]
215impl BuildIdCallbacks {
216    #[must_use]
217    /// Create a new callbacks instance to process macro definitions.
218    pub fn new() -> Self {
219        BuildIdCallbacks {
220            inner: RefCell::new(BuildIdCallbacksImpl::new()),
221        }
222    }
223}
224
225impl ParseCallbacks for BuildIdCallbacks {
226    fn modify_macro(&self, name: &str, tokens: &mut Vec<Token>) {
227        let mut inner = self.inner.borrow_mut();
228        match name {
229            "ZEND_MODULE_API_NO" => inner.read_api_no(tokens),
230            "ZEND_BUILD_TS" => inner.read_build_ts(tokens),
231            "ZEND_BUILD_DEBUG" => inner.read_build_debug(tokens),
232            "ZEND_MODULE_BUILD_ID" => inner.replace_build_id(tokens),
233            _ => (),
234        }
235    }
236}