Skip to content

Commit 3490ee7

Browse files
committed
Add a lint against never type fallback affecting unsafe code
1 parent 0f705bd commit 3490ee7

File tree

7 files changed

+241
-10
lines changed

7 files changed

+241
-10
lines changed

compiler/rustc_hir_typeck/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ hir_typeck_lossy_provenance_ptr2int =
9999
100100
hir_typeck_missing_parentheses_in_range = can't call method `{$method_name}` on type `{$ty_str}`
101101
102+
hir_typeck_never_type_fallback_flowing_into_unsafe =
103+
never type fallback affects this call to an `unsafe` function
104+
.help = specify the type explicitly
105+
102106
hir_typeck_no_associated_item = no {$item_kind} named `{$item_name}` found for {$ty_prefix} `{$ty_str}`{$trait_missing_method ->
103107
[true] {""}
104108
*[other] {" "}in the current scope

compiler/rustc_hir_typeck/src/errors.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ pub struct MissingParenthesesInRange {
164164
pub add_missing_parentheses: Option<AddMissingParenthesesInRange>,
165165
}
166166

167+
#[derive(LintDiagnostic)]
168+
#[diag(hir_typeck_never_type_fallback_flowing_into_unsafe)]
169+
#[help]
170+
pub struct NeverTypeFallbackFlowingIntoUnsafe {}
171+
167172
#[derive(Subdiagnostic)]
168173
#[multipart_suggestion(
169174
hir_typeck_add_missing_parentheses_in_range,
@@ -632,7 +637,6 @@ pub enum SuggestBoxingForReturnImplTrait {
632637
ends: Vec<Span>,
633638
},
634639
}
635-
636640
#[derive(LintDiagnostic)]
637641
#[diag(hir_typeck_dereferencing_mut_binding)]
638642
pub struct DereferencingMutBinding {

compiler/rustc_hir_typeck/src/fallback.rs

+127-8
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1-
use crate::FnCtxt;
1+
use std::cell::OnceCell;
2+
3+
use crate::{errors, FnCtxt};
24
use rustc_data_structures::{
35
graph::{self, iterate::DepthFirstSearch, vec_graph::VecGraph},
46
unord::{UnordBag, UnordMap, UnordSet},
57
};
8+
use rustc_hir::HirId;
69
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
7-
use rustc_middle::ty::{self, Ty};
10+
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
11+
use rustc_session::lint;
12+
use rustc_span::Span;
813
use rustc_span::DUMMY_SP;
914

1015
#[derive(Copy, Clone)]
@@ -335,6 +340,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
335340
// reach a member of N. If so, it falls back to `()`. Else
336341
// `!`.
337342
let mut diverging_fallback = UnordMap::with_capacity(diverging_vids.len());
343+
let unsafe_infer_vars = OnceCell::new();
338344
for &diverging_vid in &diverging_vids {
339345
let diverging_ty = Ty::new_var(self.tcx, diverging_vid);
340346
let root_vid = self.root_var(diverging_vid);
@@ -354,11 +360,35 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
354360
output: infer_var_infos.items().any(|info| info.output),
355361
};
356362

363+
let mut fallback_to = |ty| {
364+
let unsafe_infer_vars = unsafe_infer_vars.get_or_init(|| {
365+
let unsafe_infer_vars = compute_unsafe_infer_vars(self.root_ctxt, self.body_id);
366+
debug!(?unsafe_infer_vars);
367+
unsafe_infer_vars
368+
});
369+
370+
let affected_unsafe_infer_vars =
371+
graph::depth_first_search_as_undirected(&coercion_graph, root_vid)
372+
.filter_map(|x| unsafe_infer_vars.get(&x).copied())
373+
.collect::<Vec<_>>();
374+
375+
for (hir_id, span) in affected_unsafe_infer_vars {
376+
self.tcx.emit_node_span_lint(
377+
lint::builtin::NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE,
378+
hir_id,
379+
span,
380+
errors::NeverTypeFallbackFlowingIntoUnsafe {},
381+
);
382+
}
383+
384+
diverging_fallback.insert(diverging_ty, ty);
385+
};
386+
357387
use DivergingFallbackBehavior::*;
358388
match behavior {
359389
FallbackToUnit => {
360390
debug!("fallback to () - legacy: {:?}", diverging_vid);
361-
diverging_fallback.insert(diverging_ty, self.tcx.types.unit);
391+
fallback_to(self.tcx.types.unit);
362392
}
363393
FallbackToNiko => {
364394
if found_infer_var_info.self_in_trait && found_infer_var_info.output {
@@ -387,21 +417,21 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
387417
// set, see the relationship finding module in
388418
// compiler/rustc_trait_selection/src/traits/relationships.rs.
389419
debug!("fallback to () - found trait and projection: {:?}", diverging_vid);
390-
diverging_fallback.insert(diverging_ty, self.tcx.types.unit);
420+
fallback_to(self.tcx.types.unit);
391421
} else if can_reach_non_diverging {
392422
debug!("fallback to () - reached non-diverging: {:?}", diverging_vid);
393-
diverging_fallback.insert(diverging_ty, self.tcx.types.unit);
423+
fallback_to(self.tcx.types.unit);
394424
} else {
395425
debug!("fallback to ! - all diverging: {:?}", diverging_vid);
396-
diverging_fallback.insert(diverging_ty, self.tcx.types.never);
426+
fallback_to(self.tcx.types.never);
397427
}
398428
}
399429
FallbackToNever => {
400430
debug!(
401431
"fallback to ! - `rustc_never_type_mode = \"fallback_to_never\")`: {:?}",
402432
diverging_vid
403433
);
404-
diverging_fallback.insert(diverging_ty, self.tcx.types.never);
434+
fallback_to(self.tcx.types.never);
405435
}
406436
NoFallback => {
407437
debug!(
@@ -417,7 +447,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
417447

418448
/// Returns a graph whose nodes are (unresolved) inference variables and where
419449
/// an edge `?A -> ?B` indicates that the variable `?A` is coerced to `?B`.
420-
fn create_coercion_graph(&self) -> VecGraph<ty::TyVid> {
450+
fn create_coercion_graph(&self) -> VecGraph<ty::TyVid, true> {
421451
let pending_obligations = self.fulfillment_cx.borrow_mut().pending_obligations();
422452
debug!("create_coercion_graph: pending_obligations={:?}", pending_obligations);
423453
let coercion_edges: Vec<(ty::TyVid, ty::TyVid)> = pending_obligations
@@ -451,6 +481,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
451481
.collect();
452482
debug!("create_coercion_graph: coercion_edges={:?}", coercion_edges);
453483
let num_ty_vars = self.num_ty_vars();
484+
454485
VecGraph::new(num_ty_vars, coercion_edges)
455486
}
456487

@@ -459,3 +490,91 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
459490
Some(self.root_var(self.shallow_resolve(ty).ty_vid()?))
460491
}
461492
}
493+
494+
/// Finds all type variables which are passed to an `unsafe` function.
495+
///
496+
/// For example, for this function `f`:
497+
/// ```ignore (demonstrative)
498+
/// fn f() {
499+
/// unsafe {
500+
/// let x /* ?X */ = core::mem::zeroed();
501+
/// // ^^^^^^^^^^^^^^^^^^^ -- hir_id, span
502+
///
503+
/// let y = core::mem::zeroed::<Option<_ /* ?Y */>>();
504+
/// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- hir_id, span
505+
/// }
506+
/// }
507+
/// ```
508+
///
509+
/// Will return `{ id(?X) -> (hir_id, span) }`
510+
fn compute_unsafe_infer_vars<'a, 'tcx>(
511+
root_ctxt: &'a crate::TypeckRootCtxt<'tcx>,
512+
body_id: rustc_span::def_id::LocalDefId,
513+
) -> UnordMap<ty::TyVid, (HirId, Span)> {
514+
use rustc_hir as hir;
515+
516+
let tcx = root_ctxt.infcx.tcx;
517+
let body_id = tcx.hir().maybe_body_owned_by(body_id).unwrap();
518+
let body = tcx.hir().body(body_id);
519+
let mut res = <_>::default();
520+
521+
struct UnsafeInferVarsVisitor<'a, 'tcx, 'r> {
522+
root_ctxt: &'a crate::TypeckRootCtxt<'tcx>,
523+
res: &'r mut UnordMap<ty::TyVid, (HirId, Span)>,
524+
}
525+
526+
use hir::intravisit::Visitor;
527+
impl hir::intravisit::Visitor<'_> for UnsafeInferVarsVisitor<'_, '_, '_> {
528+
fn visit_expr(&mut self, ex: &'_ hir::Expr<'_>) {
529+
// FIXME: method calls
530+
if let hir::ExprKind::Call(func, ..) = ex.kind {
531+
let typeck_results = self.root_ctxt.typeck_results.borrow();
532+
533+
let func_ty = typeck_results.expr_ty(func);
534+
535+
// `is_fn` is required to ignore closures (which can't be unsafe)
536+
if func_ty.is_fn()
537+
&& let sig = func_ty.fn_sig(self.root_ctxt.infcx.tcx)
538+
&& let hir::Unsafety::Unsafe = sig.unsafety()
539+
{
540+
let mut collector =
541+
InferVarCollector { hir_id: ex.hir_id, call_span: ex.span, res: self.res };
542+
543+
// Collect generic arguments of the function which are inference variables
544+
typeck_results
545+
.node_args(ex.hir_id)
546+
.types()
547+
.for_each(|t| t.visit_with(&mut collector));
548+
549+
// Also check the return type, for cases like `(unsafe_fn::<_> as unsafe fn() -> _)()`
550+
sig.output().visit_with(&mut collector);
551+
}
552+
}
553+
554+
hir::intravisit::walk_expr(self, ex);
555+
}
556+
}
557+
558+
struct InferVarCollector<'r> {
559+
hir_id: HirId,
560+
call_span: Span,
561+
res: &'r mut UnordMap<ty::TyVid, (HirId, Span)>,
562+
}
563+
564+
impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for InferVarCollector<'_> {
565+
fn visit_ty(&mut self, t: Ty<'tcx>) {
566+
if let Some(vid) = t.ty_vid() {
567+
self.res.insert(vid, (self.hir_id, self.call_span));
568+
} else {
569+
use ty::TypeSuperVisitable as _;
570+
t.super_visit_with(self)
571+
}
572+
}
573+
}
574+
575+
UnsafeInferVarsVisitor { root_ctxt, res: &mut res }.visit_expr(&body.value);
576+
577+
debug!(?res, "collected the following unsafe vars for {body_id:?}");
578+
579+
res
580+
}

compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ mod arg_matrix;
44
mod checks;
55
mod suggestions;
66

7+
use rustc_errors::ErrorGuaranteed;
8+
79
use crate::coercion::DynamicCoerceMany;
810
use crate::fallback::DivergingFallbackBehavior;
911
use crate::fn_ctxt::checks::DivergingBlockBehavior;
1012
use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
1113
use hir::def_id::CRATE_DEF_ID;
12-
use rustc_errors::{DiagCtxt, ErrorGuaranteed};
14+
use rustc_errors::DiagCtxt;
1315
use rustc_hir as hir;
1416
use rustc_hir::def_id::{DefId, LocalDefId};
1517
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;

compiler/rustc_lint_defs/src/builtin.rs

+44
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ declare_lint_pass! {
6969
MISSING_FRAGMENT_SPECIFIER,
7070
MUST_NOT_SUSPEND,
7171
NAMED_ARGUMENTS_USED_POSITIONALLY,
72+
NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE,
7273
NON_CONTIGUOUS_RANGE_ENDPOINTS,
7374
NON_EXHAUSTIVE_OMITTED_PATTERNS,
7475
ORDER_DEPENDENT_TRAIT_OBJECTS,
@@ -4244,6 +4245,49 @@ declare_lint! {
42444245
"named arguments in format used positionally"
42454246
}
42464247

4248+
declare_lint! {
4249+
/// The `never_type_fallback_flowing_into_unsafe` lint detects cases where never type fallback
4250+
/// affects unsafe function calls.
4251+
///
4252+
/// ### Example
4253+
///
4254+
/// ```rust,compile_fail
4255+
/// #![deny(never_type_fallback_flowing_into_unsafe)]
4256+
/// fn main() {
4257+
/// if true {
4258+
/// // return has type `!` (never) which, is some cases, causes never type fallback
4259+
/// return
4260+
/// } else {
4261+
/// // `zeroed` is an unsafe function, which returns an unbounded type
4262+
/// unsafe { std::mem::zeroed() }
4263+
/// };
4264+
/// // depending on the fallback, `zeroed` may create `()` (which is completely sound),
4265+
/// // or `!` (which is instant undefined behavior)
4266+
/// }
4267+
/// ```
4268+
///
4269+
/// {{produces}}
4270+
///
4271+
/// ### Explanation
4272+
///
4273+
/// Due to historic reasons never type fallback were `()`, meaning that `!` got spontaneously
4274+
/// coerced to `()`. There are plans to change that, but they may make the code such as above
4275+
/// unsound. Instead of depending on the fallback, you should specify the type explicitly:
4276+
/// ```
4277+
/// if true {
4278+
/// return
4279+
/// } else {
4280+
/// // type is explicitly specified, fallback can't hurt us no more
4281+
/// unsafe { std::mem::zeroed::<()>() }
4282+
/// };
4283+
/// ```
4284+
///
4285+
/// See [Tracking Issue for making `!` fall back to `!`](https://github.com/rust-lang/rust/issues/123748).
4286+
pub NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE,
4287+
Warn,
4288+
"never type fallback affecting unsafe function calls"
4289+
}
4290+
42474291
declare_lint! {
42484292
/// The `byte_slice_in_packed_struct_with_derive` lint detects cases where a byte slice field
42494293
/// (`[u8]`) or string slice field (`str`) is used in a `packed` struct that derives one or
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//@ check-pass
2+
use std::mem;
3+
4+
fn main() {
5+
if false {
6+
unsafe { mem::zeroed() }
7+
//~^ warn: never type fallback affects this call to an `unsafe` function
8+
} else {
9+
return;
10+
};
11+
12+
// no ; -> type is inferred without fallback
13+
if true { unsafe { mem::zeroed() } } else { return }
14+
}
15+
16+
// Minimization of the famous `objc` crate issue
17+
fn _objc() {
18+
pub unsafe fn send_message<R>() -> Result<R, ()> {
19+
Ok(unsafe { core::mem::zeroed() })
20+
}
21+
22+
macro_rules! msg_send {
23+
() => {
24+
match send_message::<_ /* ?0 */>() {
25+
//~^ warn: never type fallback affects this call to an `unsafe` function
26+
Ok(x) => x,
27+
Err(_) => loop {},
28+
}
29+
};
30+
}
31+
32+
unsafe {
33+
msg_send!();
34+
}
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
warning: never type fallback affects this call to an `unsafe` function
2+
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:6:18
3+
|
4+
LL | unsafe { mem::zeroed() }
5+
| ^^^^^^^^^^^^^
6+
|
7+
= help: specify the type explicitly
8+
= note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default
9+
10+
warning: never type fallback affects this call to an `unsafe` function
11+
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:24:19
12+
|
13+
LL | match send_message::<_ /* ?0 */>() {
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15+
...
16+
LL | msg_send!();
17+
| ----------- in this macro invocation
18+
|
19+
= help: specify the type explicitly
20+
= note: this warning originates in the macro `msg_send` (in Nightly builds, run with -Z macro-backtrace for more info)
21+
22+
warning: 2 warnings emitted
23+

0 commit comments

Comments
 (0)