Skip to content

Diagnostics in FFI use recommend users to cast to i/u8 instead of the appropriate c_char #89325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
skade opened this issue Sep 28, 2021 · 0 comments
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@skade
Copy link
Contributor

skade commented Sep 28, 2021

Note: related to the lint described in #79089

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e4aed9f0b25f39886e30db193cf508e2

use libc::c_char;

fn fun(c: c_char) {
    
}

fn main() {
    let x: u8 = 3;
    
    fun(x)
}

The current output is:

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |     fun(x)
   |         ^ expected `i8`, found `u8`
   |
help: you can convert a `u8` to an `i8` and panic if the converted value doesn't fit
   |
10 |     fun(x.try_into().unwrap())
   |         ^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

Ideally the output should look like:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |     fun(x)
   |         ^ expected `i8`, found `u8`
   |
help: you can convert a `u8` to an `c_char` and panic if the converted value doesn't fit
   |
10 |     fun(x.try_into().unwrap())
   |         ^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

c_char is different on platforms, it may be u8 or i8. The correct cast here in FFI use is towards a c_char, keeping casts correct in all situations. There's also an argument to be made that i8 -> c_char should be using an as cast.

@skade skade added A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Sep 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

1 participant