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
pub use crate::{
config::{Config, ConfigMap},
sdk::{SdkPath, SdkPathError},
};
#[derive(Debug)]
pub struct Builder {
framework: String,
sdk: SdkPath,
target: Option<String>,
config: Config,
}
impl Builder {
pub fn new(
framework: &str,
sdk: impl TryInto<SdkPath, Error = SdkPathError>,
config: Config,
) -> Result<Self, SdkPathError> {
Ok(Self {
framework: framework.to_owned(),
sdk: sdk.try_into()?,
target: None,
config,
})
}
pub fn with_builtin_config(
framework: &str,
sdk: impl TryInto<SdkPath, Error = SdkPathError>,
) -> Result<Self, SdkPathError> {
Self::new(
framework,
sdk,
ConfigMap::with_builtin_config().framework_config(framework),
)
}
pub fn target(mut self, target: impl AsRef<str>) -> Self {
assert!(self.target.is_none());
self.target = Some(target.as_ref().to_owned());
self
}
pub fn bindgen_builder(&self) -> bindgen::Builder {
// Begin building the bindgen params.
let mut builder = bindgen::Builder::default();
let mut clang_args = vec!["-x", "objective-c", "-fblocks", "-fmodules"];
let target_arg;
if let Some(target) = self.target.as_ref() {
target_arg = format!("--target={}", target);
clang_args.push(&target_arg);
}
clang_args.extend(&[
"-isysroot",
self.sdk
.path()
.to_str()
.expect("sdk path is not utf-8 representable"),
]);
builder = builder
.clang_args(&clang_args)
.layout_tests(self.config.layout_tests)
.formatter(bindgen::Formatter::Prettyplease);
for opaque_type in &self.config.opaque_types {
builder = builder.opaque_type(opaque_type);
}
for blocklist_item in &self.config.blocklist_items {
builder = builder.blocklist_item(blocklist_item);
}
builder = builder.header_contents(
&format!("{}.h", self.framework),
&format!("@import {};", self.framework),
);
// Only generate bindings for items defined in framework headers, the ObjC runtime,
// and MacTypes.h. This excludes irrelevant system types (arm_debug_state32_t, etc.)
// from non-framework paths like <mach/>, <sys/>, <arm/>.
// allowlist_recursively (default true) ensures types referenced by framework APIs
// from system headers (e.g. simd types) are still included.
builder = builder
.allowlist_file(".*\\.framework/.*")
.allowlist_file(".*/usr/include/objc/.*")
.allowlist_file(".*/usr/include/os/.*")
.allowlist_file(".*/usr/include/MacTypes\\.h");
builder
}
pub fn generate(&self) -> Result<String, bindgen::BindgenError> {
let bindgen_builder = self.bindgen_builder();
// Generate the bindings.
let bindings = bindgen_builder.generate()?;
// TODO: find the best way to do this post-processing
let mut out = bindings.to_string();
// remove redundant and malformed definitions of `id`
out = out.replace("pub type id = *mut objc::runtime::Object", "PUB-TYPE-ID");
let re = regex::Regex::new("pub type id = .*;").unwrap();
out = re.replace_all(&mut out, "").into_owned();
out = out.replace("PUB-TYPE-ID", "pub type id = *mut objc::runtime::Object");
// Bindgen.toml `replacements`
for replacement in &self.config.replacements {
let (old, new) = replacement
.split_once(" #=># ")
.expect("Bindgen.toml is malformed");
out = out.replace(old, new);
}
// Fix msg_send! arguments that collide with struct type names.
// e.g. `msg_send!(*self, setPDFView: PDFView)` where `PDFView`
// resolves to the struct constructor instead of the parameter.
out = fix_msg_send_type_collisions(&out);
// Bindgen.toml `impl_debugs`
for ty in &self.config.impl_debugs {
if out.contains(ty) {
out.push_str(&format!(
r#"
impl ::std::fmt::Debug for {ty} {{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {{
f.debug_struct(stringify!({ty}))
.finish()
}}
}}
"#
));
}
}
Ok(out)
}
}
/// Rename msg_send! arguments and fn parameters that collide with top-level item names.
///
/// Bindgen may generate methods where a parameter name matches a `pub struct` or
/// `pub const` defined in the same output. In `msg_send!` macro expansion, these
/// names resolve to the struct constructor or constant value instead of the local
/// parameter. This appends `_` to colliding names in both parameter declarations
/// and `msg_send!` calls.
fn fix_msg_send_type_collisions(source: &str) -> String {
use std::collections::HashSet;
let mut shadow_names: HashSet<&str> = HashSet::new();
for line in source.lines() {
let trimmed = line.trim();
let rest = trimmed
.strip_prefix("pub struct ")
.or_else(|| trimmed.strip_prefix("pub const "));
if let Some(rest) = rest {
if let Some(name) = rest
.split(|c: char| !c.is_alphanumeric() && c != '_')
.next()
{
if !name.is_empty() {
shadow_names.insert(name);
}
}
}
}
if shadow_names.is_empty() {
return source.to_string();
}
let msg_arg_re = regex::Regex::new(r" : (\w+)").unwrap();
let comma_param_re = regex::Regex::new(r", (\w+): ").unwrap();
let paren_param_re = regex::Regex::new(r"\((\w+): ").unwrap();
let mut in_trait = false;
let mut trait_brace_depth: i32 = 0;
let mut in_msg_send = false;
let mut msg_send_depth: i32 = 0;
let mut result = String::with_capacity(source.len());
for line in source.lines() {
let trimmed = line.trim();
// Track ObjC trait blocks to restrict parameter renames
if !in_trait && trimmed.starts_with("pub trait ") {
in_trait = true;
trait_brace_depth = 0;
}
if in_trait {
for c in line.chars() {
match c {
'{' => trait_brace_depth += 1,
'}' => trait_brace_depth -= 1,
_ => {}
}
}
if trait_brace_depth <= 0 {
in_trait = false;
}
}
// Track multi-line msg_send! blocks (save state before updating)
let is_in_msg_send = in_msg_send;
if !in_msg_send && trimmed.contains("msg_send") {
in_msg_send = true;
msg_send_depth = 0;
}
if in_msg_send {
for c in line.chars() {
match c {
'(' => msg_send_depth += 1,
')' => msg_send_depth -= 1,
_ => {}
}
}
if msg_send_depth <= 0 {
in_msg_send = false;
}
}
let mut fixed = line.to_string();
let mut did_fix = false;
// msg_send! arguments: ` : name` where name shadows a top-level item
// Also handle continuation lines of multi-line msg_send! blocks
if fixed.contains("msg_send") || is_in_msg_send {
let new_fixed = msg_arg_re.replace_all(&fixed, |caps: ®ex::Captures| {
let name = caps.get(1).unwrap().as_str();
if shadow_names.contains(name) {
format!(" : {}_", name)
} else {
caps[0].to_string()
}
});
if new_fixed != fixed {
fixed = new_fixed.into_owned();
did_fix = true;
}
}
// Parameter renames only inside trait blocks (extern/free fn params don't collide)
if in_trait {
// Indented parameter: ` name: Type` (skip fn-definition lines)
if !trimmed.starts_with("unsafe fn ") && fixed.starts_with(" ") {
let after_indent = &fixed[8..];
if let Some(colon_pos) = after_indent.find(": ") {
let candidate = &after_indent[..colon_pos];
if !candidate.is_empty()
&& candidate.chars().all(|c| c.is_alphanumeric() || c == '_')
&& shadow_names.contains(candidate)
{
fixed = fixed.replacen(
&format!(" {}: ", candidate),
&format!(" {}_: ", candidate),
1,
);
did_fix = true;
}
}
}
// Inline parameter: `, name: Type`
{
let orig = fixed.clone();
let new_fixed = comma_param_re.replace_all(&orig, |caps: ®ex::Captures| {
let name = caps.get(1).unwrap().as_str();
if shadow_names.contains(name) {
format!(", {}_: ", name)
} else {
caps[0].to_string()
}
});
if new_fixed != orig {
fixed = new_fixed.into_owned();
did_fix = true;
}
}
// Opening-paren parameter: `(name: Type`
{
let orig = fixed.clone();
let new_fixed = paren_param_re.replace_all(&orig, |caps: ®ex::Captures| {
let name = caps.get(1).unwrap().as_str();
if shadow_names.contains(name) {
format!("({}_: ", name)
} else {
caps[0].to_string()
}
});
if new_fixed != orig {
fixed = new_fixed.into_owned();
did_fix = true;
}
}
}
if did_fix {
result.push_str(&fixed);
} else {
result.push_str(line);
}
result.push('\n');
}
result
}