Skip to content
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

Use subtyping for UnsafeFnPointer coercion, too #129288

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2043,9 +2043,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {

let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);

if let Err(terr) = self.eq_types(
*ty,
if let Err(terr) = self.sub_types(
ty_fn_ptr_from,
*ty,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you flip the args and check whether there's an existing test which goes from fail to pass to make sure we check for that potential unsoundness?

r=me after that

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, tests/ui/nll/mir_check_cast_unsafe_fn.rs checks this, which was added 7 years ago:

#![allow(dead_code)]

fn bar<'a>(input: &'a u32, f: fn(&'a u32) -> &'a u32) -> &'static u32 {
    // Here the NLL checker must relate the types in `f` to the types
    // in `g`. These are related via the `UnsafeFnPointer` cast.
    let g: unsafe fn(_) -> _ = f;
    unsafe { g(input) }
    //~^ ERROR lifetime may not live long enough
}

fn main() {}

location.to_locations(),
ConstraintCategory::Cast { unsize_to: None },
) {
Expand Down
14 changes: 14 additions & 0 deletions tests/ui/coercion/cast-higher-ranked-unsafe-fn-ptr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//@ check-pass

fn higher_ranked_fndef(ctx: &mut ()) {}

fn test(higher_ranked_fnptr: fn(&mut ())) {
fn as_unsafe<T>(_: unsafe fn(T)) {}

// Make sure that we can cast higher-ranked fn items and pointers to
// a non-higher-ranked target.
as_unsafe(higher_ranked_fndef);
as_unsafe(higher_ranked_fnptr);
}

fn main() {}
Loading