Skip to content

Commit f7716a5

Browse files
committed
Handle the const struct * and struct * patterns.
Given that C keeps a different namespace for `struct`s and aliases. The following patterns ```c typedef const struct foo { void *inner; } *foo; typedef struct bar { void *inner; } *bar; ``` are valid C code and produces both a `struct` and a pointer called `foo` and `bar` in different namespaces. Given that Rust does not make this distinction, we add the `_ptr` prefix to the pointer type aliases to avoid any name collisions.
1 parent 0631a27 commit f7716a5

File tree

3 files changed

+118
-3
lines changed

3 files changed

+118
-3
lines changed

bindgen-tests/tests/expectations/tests/struct_ptr.rs

+83
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
typedef const struct foo {
2+
char inner;
3+
} *foo;
4+
5+
typedef struct bar {
6+
char inner;
7+
} *bar;
8+
9+
void takes_foo_ptr(foo);
10+
void takes_foo_struct(struct foo);
11+
void takes_bar_ptr(bar);
12+
void takes_bar_struct(struct bar);

bindgen/ir/ty.rs

+23-3
Original file line numberDiff line numberDiff line change
@@ -1094,17 +1094,37 @@ impl Type {
10941094
}
10951095
CXType_Typedef => {
10961096
let inner = cursor.typedef_type().expect("Not valid Type?");
1097-
let inner =
1097+
let inner_id =
10981098
Item::from_ty_or_ref(inner, location, None, ctx);
1099-
if inner == potential_id {
1099+
if inner_id == potential_id {
11001100
warn!(
11011101
"Generating oqaque type instead of self-referential \
11021102
typedef");
11031103
// This can happen if we bail out of recursive situations
11041104
// within the clang parsing.
11051105
TypeKind::Opaque
11061106
} else {
1107-
TypeKind::Alias(inner)
1107+
// Check if this type definition is an alias to a pointer of a `const
1108+
// struct` with the same name and add the `_ptr` suffix to it to avoid name
1109+
// collisions.
1110+
if !ctx.options().c_naming {
1111+
if let Some(pointee_spelling) =
1112+
inner.pointee_type().map(|ty| ty.spelling())
1113+
{
1114+
if let Some(pointee_name) = pointee_spelling
1115+
.strip_prefix("const struct ")
1116+
.or_else(|| {
1117+
pointee_spelling.strip_prefix("struct ")
1118+
})
1119+
{
1120+
if pointee_name == name {
1121+
name += "_ptr";
1122+
}
1123+
}
1124+
}
1125+
}
1126+
1127+
TypeKind::Alias(inner_id)
11081128
}
11091129
}
11101130
CXType_Enum => {

0 commit comments

Comments
 (0)