Skip to content

Commit 97e29b4

Browse files
authored
Fix escaping for objective-C identifiers (#2587)
* Escape keywords that cannot be raw identifiers * Update tests * Update changelog
1 parent 2df02c2 commit 97e29b4

File tree

4 files changed

+19
-3
lines changed

4 files changed

+19
-3
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,9 @@
176176
the `incorrect_clone_impl_on_copy_type` Clippy lint.
177177
## Removed
178178
## Fixed
179+
- Bindgen no longer panics when parsing an objective-C header that includes a
180+
Rust keyword that cannot be a raw identifier, such as: `self`, `crate`,
181+
`super` or `Self`.
179182
## Security
180183

181184
# 0.66.1

bindgen-tests/tests/expectations/tests/objc_escape.rs

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bindgen-tests/tests/headers/objc_escape.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33

44
@interface A
55
-(void)f:(int)arg1 as:(int)arg2;
6+
-(void)crate:(int)self;
67
@end

bindgen/ir/objc.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,15 +257,21 @@ impl ObjCMethod {
257257
if name.is_empty() {
258258
None
259259
} else {
260-
// Try to parse the current name as an identifier. This might fail if the
261-
// name is a keyword so we try to prepend "r#" to it and parse again. If
262-
// this also fails, we panic with the first error.
260+
// Try to parse the current name as an identifier. This might fail if the name
261+
// is a keyword, so we try to "r#" to it and parse again, this could also fail
262+
// if the name is `crate`, `self`, `super` or `Self`, so we try to add the `_`
263+
// suffix to it and parse again. If this also fails, we panic with the first
264+
// error.
263265
Some(
264266
syn::parse_str::<Ident>(name)
265267
.or_else(|err| {
266268
syn::parse_str::<Ident>(&format!("r#{}", name))
267269
.map_err(|_| err)
268270
})
271+
.or_else(|err| {
272+
syn::parse_str::<Ident>(&format!("{}_", name))
273+
.map_err(|_| err)
274+
})
269275
.expect("Invalid identifier"),
270276
)
271277
}

0 commit comments

Comments
 (0)