Skip to content

Commit eb57bc5

Browse files
committed
fix(cust_raw): Use string macro expansion to record function renames
`cl.exe` macro expansion does not do any token validation when using token pasting (##), but `cc` does validate token pasting results in a valid token. This change switches from token pasting to stringify (#), which expands all the macro function variables as strings. Rename lines now expand to `"RUST_RENAME" "_someDefine" "expandedFuncName"`. This prevents `cc` from erroring during expanding in cases where the expanded macro would have resulted in an invalid token, i.e: `RUST_RENAME_someDefine_(not_valid)` which is invalid because the `(` is not a valid token character.
1 parent 032361a commit eb57bc5

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

crates/cust_raw/build/callbacks.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use std::fs;
33
use std::path;
44
use std::sync;
55

6-
use bimap;
76
use bindgen::callbacks::{ItemInfo, ItemKind, MacroParsingBehavior, ParseCallbacks};
87

98
/// Struct to handle renaming of functions through macro expansion.
@@ -40,18 +39,24 @@ impl FunctionRenames {
4039

4140
fn expand(&self) -> &bimap::BiHashMap<String, String> {
4241
self.func_remaps.get_or_init(|| {
42+
if self.macro_names.borrow().is_empty() {
43+
return bimap::BiHashMap::new();
44+
}
45+
4346
let expand_me = self.out_dir.join("expand_macros.c");
4447
let includes = fs::read_to_string(&self.includes)
4548
.expect("Failed to read includes for function renames");
4649

4750
let mut template = format!(
4851
r#"{includes}
49-
#define RENAMED2(from, to) RUST_RENAMED##from##_TO_##to
50-
#define RENAMED(from, to) RENAMED2(from, to)
52+
#define STRINGIFY(x) #x
53+
#define TOSTRING(x) STRINGIFY(x)
54+
#define RENAMED(from, to) "RUST_RENAMED" TOSTRING(from) TOSTRING(to)
5155
"#
5256
);
5357

5458
for name in self.macro_names.borrow().iter() {
59+
// Add an underscore to the left so that it won't get expanded.
5560
template.push_str(&format!("RENAMED(_{name}, {name})\n"));
5661
}
5762

@@ -74,11 +79,15 @@ impl FunctionRenames {
7479

7580
let mut remaps = bimap::BiHashMap::new();
7681
for line in expanded.lines().rev() {
77-
let rename_prefix = "RUST_RENAMED_";
82+
let rename_prefix = "\"RUST_RENAMED\" ";
7883

7984
if let Some((original, expanded)) = line
8085
.strip_prefix(rename_prefix)
81-
.and_then(|s| s.split_once("_TO_"))
86+
.map(|s| s.replace("\"", ""))
87+
.and_then(|s| {
88+
s.split_once(' ')
89+
.map(|(l, r)| (l[1..].to_string(), r.to_string()))
90+
})
8291
.filter(|(l, r)| l != r && !r.is_empty())
8392
{
8493
remaps.insert(original.to_string(), expanded.to_string());

0 commit comments

Comments
 (0)