mozilla / cbindgen

A project for generating C bindings from Rust code
Mozilla Public License 2.0
2.29k stars 294 forks source link

ParseSyntaxError: "at least one trait is required for an object type" #898

Closed d-e-s-o closed 3 months ago

d-e-s-o commented 8 months ago

Let's say I have the following Rust code:

pub fn add(left: usize, right: usize) -> &'static str {
    unsafe { &*("hallihallo" as *const str).as_ref::<'static>().unwrap() }
}

And the following build.rs (using cbindgen 0.26.0):

fn main() {
    let _x = cbindgen::Builder::new()
        .with_crate(".")
        .generate()
        .expect("Unable to generate bindings");
}

When I attempt compilation it fails with:

$ cargo build
>    Compiling foobar v0.1.0 (/tmp/foobar)
> error: failed to run custom build command for `foobar v0.1.0 (/tmp/foobar)`
> 
> Caused by:
>   process didn't exit successfully: `/tmp/rust-build-artifacts/tmp/foobar/target/debug/build/foobar-eed8272c83fe0ebc/build-script-build` (exit status: 101)
>   --- stderr
>   thread 'main' panicked at build.rs:5:10:
>   Unable to generate bindings: ParseSyntaxError { crate_name: "foobar", src_path: "/tmp/foobar/src/lib.rs", error: Error("at least one trait is required for an object type") }
>   note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

If I apply:

--- lib.rs
+++ lib.rs
@@ -1,3 +1,3 @@
 pub fn add(left: usize, right: usize) -> &'static str {
-    unsafe { &*("hallihallo" as *const str).as_ref::<'static>().unwrap() }
+    unsafe { &*("hallihallo" as *const str) }
 }

everything builds fine.

Somehow, the as_ref::<'static>() part appears to trigger https://doc.rust-lang.org/error_codes/E0224.html ? This seems to be valid Rust code to the degree I can tell, so I'd think that cbindgen shouldn't choke on it like that. Am I missing something?

emilio commented 3 months ago

This seems like a syn bug, at a glance. We don't look inside function bodies ourselves. Can you file in https://github.com/dtolnay/syn/issues/new if it repros with an updated syn?

d-e-s-o commented 3 months ago

Thanks. Seems to reproduce until syn 1.0.109 and is fixed in syn 2.0.