Auto merge of #122454 - matthiaskrgr:rollup-xbmufdc, r=matthiaskrgr

Rollup of 11 pull requests

Successful merges:

 - #122422 (compiletest: Allow `only-unix` in test headers)
 - #122424 (fix: typos)
 - #122425 (Increase timeout for new bors bot)
 - #122426 (Fix StableMIR `WrappingRange::is_full` computation)
 - #122429 (Add Exploit Mitigations PG to triagebot.toml)
 - #122430 (Generate link to `Local` in `hir::Let` documentation)
 - #122434 (pattern analysis: rename a few types)
 - #122437 (pattern analysis: remove `MaybeInfiniteInt::JustAfterMax`)
 - #122438 (Safe Transmute: Require that source referent is smaller than destination)
 - #122442 (extend docs of -Zprint-mono-items)
 - #122449 (Delay a bug for stranded opaques)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2024-03-14 04:54:37 +00:00
commit 6f3eb1ce3d
31 changed files with 374 additions and 174 deletions

View file

@ -1253,11 +1253,11 @@ pub struct Arm<'hir> {
pub body: &'hir Expr<'hir>,
}
/// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
/// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
/// Represents a `let <pat>[: <ty>] = <expr>` expression (not a [`Local`]), occurring in an `if-let`
/// or `let-else`, evaluating to a boolean. Typically the pattern is refutable.
///
/// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
/// desugaring to if-let. Only let-else supports the type annotation at present.
/// In an `if let`, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of
/// the desugaring to if-let. Only let-else supports the type annotation at present.
#[derive(Debug, Clone, Copy, HashStable_Generic)]
pub struct Let<'hir> {
pub span: Span,

View file

@ -381,11 +381,17 @@ fn check_opaque_meets_bounds<'tcx>(
match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
Ok(()) => {}
Err(ty_err) => {
// Some types may be left "stranded" if they can't be reached
// from an astconv'd bound but they're mentioned in the HIR. This
// will happen, e.g., when a nested opaque is inside of a non-
// existent associated type, like `impl Trait<Missing = impl Trait>`.
// See <tests/ui/impl-trait/stranded-opaque.rs>.
let ty_err = ty_err.to_string(tcx);
tcx.dcx().span_bug(
let guar = tcx.dcx().span_delayed_bug(
span,
format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
);
return Err(guar);
}
}

View file

@ -6,7 +6,7 @@
};
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::{self, Ty};
use rustc_pattern_analysis::{errors::Uncovered, rustc::RustcMatchCheckCtxt};
use rustc_pattern_analysis::{errors::Uncovered, rustc::RustcPatCtxt};
use rustc_span::symbol::Symbol;
use rustc_span::Span;
@ -455,7 +455,7 @@ pub enum UnusedUnsafeEnclosing {
}
pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'p, 'tcx, 'm> {
pub cx: &'m RustcMatchCheckCtxt<'p, 'tcx>,
pub cx: &'m RustcPatCtxt<'p, 'tcx>,
pub expr_span: Span,
pub span: Span,
pub ty: Ty<'tcx>,

View file

@ -1,7 +1,7 @@
use rustc_pattern_analysis::errors::Uncovered;
use rustc_pattern_analysis::rustc::{
Constructor, DeconstructedPat, MatchArm, RustcMatchCheckCtxt as MatchCheckCtxt, Usefulness,
UsefulnessReport, WitnessPat,
Constructor, DeconstructedPat, MatchArm, RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport,
WitnessPat,
};
use crate::errors::*;
@ -276,7 +276,7 @@ fn visit_land_rhs(
fn lower_pattern(
&mut self,
cx: &MatchCheckCtxt<'p, 'tcx>,
cx: &PatCtxt<'p, 'tcx>,
pat: &'p Pat<'tcx>,
) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
if let Err(err) = pat.pat_error_reported() {
@ -375,7 +375,7 @@ fn new_cx(
whole_match_span: Option<Span>,
scrutinee: Option<&Expr<'tcx>>,
scrut_span: Span,
) -> MatchCheckCtxt<'p, 'tcx> {
) -> PatCtxt<'p, 'tcx> {
let refutable = match refutability {
Irrefutable => false,
Refutable => true,
@ -384,7 +384,7 @@ fn new_cx(
// require validity.
let known_valid_scrutinee =
scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
MatchCheckCtxt {
PatCtxt {
tcx: self.tcx,
typeck_results: self.typeck_results,
param_env: self.param_env,
@ -400,7 +400,7 @@ fn new_cx(
fn analyze_patterns(
&mut self,
cx: &MatchCheckCtxt<'p, 'tcx>,
cx: &PatCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
@ -584,7 +584,7 @@ fn analyze_binding(
pat: &'p Pat<'tcx>,
refutability: RefutableFlag,
scrut: Option<&Expr<'tcx>>,
) -> Result<(MatchCheckCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
let cx = self.new_cx(refutability, None, scrut, pat.span);
let pat = self.lower_pattern(&cx, pat)?;
let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
@ -849,7 +849,7 @@ fn check_for_bindings_named_same_as_variants(
/// Check that never patterns are only used on inhabited types.
fn check_never_pattern<'tcx>(
cx: &MatchCheckCtxt<'_, 'tcx>,
cx: &PatCtxt<'_, 'tcx>,
pat: &Pat<'tcx>,
) -> Result<(), ErrorGuaranteed> {
if let PatKind::Never = pat.kind {
@ -884,7 +884,7 @@ macro_rules! emit_diag {
/// Report unreachable arms, if any.
fn report_unreachable_pattern<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>,
cx: &PatCtxt<'p, 'tcx>,
hir_id: HirId,
span: Span,
catchall: Option<Span>,
@ -898,10 +898,7 @@ fn report_unreachable_pattern<'p, 'tcx>(
}
/// Report unreachable arms, if any.
fn report_arm_reachability<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>,
report: &UsefulnessReport<'p, 'tcx>,
) {
fn report_arm_reachability<'p, 'tcx>(cx: &PatCtxt<'p, 'tcx>, report: &UsefulnessReport<'p, 'tcx>) {
let mut catchall = None;
for (arm, is_useful) in report.arm_usefulness.iter() {
if matches!(is_useful, Usefulness::Redundant) {
@ -926,7 +923,7 @@ fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
/// Report that a match is not exhaustive.
fn report_non_exhaustive_match<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>,
cx: &PatCtxt<'p, 'tcx>,
thir: &Thir<'tcx>,
scrut_ty: Ty<'tcx>,
sp: Span,
@ -1126,7 +1123,7 @@ fn report_non_exhaustive_match<'p, 'tcx>(
}
fn joined_uncovered_patterns<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>,
cx: &PatCtxt<'p, 'tcx>,
witnesses: &[WitnessPat<'p, 'tcx>],
) -> String {
const LIMIT: usize = 3;
@ -1147,7 +1144,7 @@ fn joined_uncovered_patterns<'p, 'tcx>(
}
fn collect_non_exhaustive_tys<'tcx>(
cx: &MatchCheckCtxt<'_, 'tcx>,
cx: &PatCtxt<'_, 'tcx>,
pat: &WitnessPat<'_, 'tcx>,
non_exhaustive_tys: &mut FxIndexSet<Ty<'tcx>>,
) {

View file

@ -40,7 +40,7 @@
//! - That have no non-trivial intersection with any of the constructors in the column (i.e. they're
//! each either disjoint with or covered by any given column constructor).
//!
//! We compute this in two steps: first [`TypeCx::ctors_for_ty`] determines the
//! We compute this in two steps: first [`PatCx::ctors_for_ty`] determines the
//! set of all possible constructors for the type. Then [`ConstructorSet::split`] looks at the
//! column of constructors and splits the set into groups accordingly. The precise invariants of
//! [`ConstructorSet::split`] is described in [`SplitConstructorSet`].
@ -136,7 +136,7 @@
//! the algorithm can't distinguish them from a nonempty constructor. The only known case where this
//! could happen is the `[..]` pattern on `[!; N]` with `N > 0` so we must take care to not emit it.
//!
//! This is all handled by [`TypeCx::ctors_for_ty`] and
//! This is all handled by [`PatCx::ctors_for_ty`] and
//! [`ConstructorSet::split`]. The invariants of [`SplitConstructorSet`] are also of interest.
//!
//!
@ -162,7 +162,7 @@
use self::SliceKind::*;
use crate::index;
use crate::TypeCx;
use crate::PatCx;
/// Whether we have seen a constructor in the column or not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@ -195,8 +195,6 @@ pub enum MaybeInfiniteInt {
/// Encoded value. DO NOT CONSTRUCT BY HAND; use `new_finite_{int,uint}`.
#[non_exhaustive]
Finite(u128),
/// The integer after `u128::MAX`. We need it to represent `x..=u128::MAX` as an exclusive range.
JustAfterMax,
PosInfinity,
}
@ -232,18 +230,18 @@ pub fn as_finite_int(self, size: u64) -> Option<u128> {
pub fn minus_one(self) -> Option<Self> {
match self {
Finite(n) => n.checked_sub(1).map(Finite),
JustAfterMax => Some(Finite(u128::MAX)),
x => Some(x),
}
}
/// Note: this will not turn a finite value into an infinite one or vice-versa.
/// Note: this will turn `u128::MAX` into `PosInfinity`. This means `plus_one` and `minus_one`
/// are not strictly inverses, but that poses no problem in our use of them.
/// this will not turn a finite value into an infinite one or vice-versa.
pub fn plus_one(self) -> Option<Self> {
match self {
Finite(n) => match n.checked_add(1) {
Some(m) => Some(Finite(m)),
None => Some(JustAfterMax),
None => Some(PosInfinity),
},
JustAfterMax => None,
x => Some(x),
}
}
@ -277,8 +275,7 @@ pub fn from_singleton(x: MaybeInfiniteInt) -> IntRange {
}
/// Construct a range with these boundaries.
/// `lo` must not be `PosInfinity` or `JustAfterMax`. `hi` must not be `NegInfinity`.
/// If `end` is `Included`, `hi` must also not be `JustAfterMax`.
/// `lo` must not be `PosInfinity`. `hi` must not be `NegInfinity`.
#[inline]
pub fn from_range(lo: MaybeInfiniteInt, mut hi: MaybeInfiniteInt, end: RangeEnd) -> IntRange {
if end == RangeEnd::Included {
@ -651,7 +648,7 @@ pub fn new() -> Self {
/// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
/// `Fields`.
#[derive(Debug)]
pub enum Constructor<Cx: TypeCx> {
pub enum Constructor<Cx: PatCx> {
/// Tuples and structs.
Struct,
/// Enum variants.
@ -696,7 +693,7 @@ pub enum Constructor<Cx: TypeCx> {
PrivateUninhabited,
}
impl<Cx: TypeCx> Clone for Constructor<Cx> {
impl<Cx: PatCx> Clone for Constructor<Cx> {
fn clone(&self) -> Self {
match self {
Constructor::Struct => Constructor::Struct,
@ -720,7 +717,7 @@ fn clone(&self) -> Self {
}
}
impl<Cx: TypeCx> Constructor<Cx> {
impl<Cx: PatCx> Constructor<Cx> {
pub(crate) fn is_non_exhaustive(&self) -> bool {
matches!(self, NonExhaustive)
}
@ -838,7 +835,7 @@ pub enum VariantVisibility {
/// In terms of division of responsibility, [`ConstructorSet::split`] handles all of the
/// `exhaustive_patterns` feature.
#[derive(Debug)]
pub enum ConstructorSet<Cx: TypeCx> {
pub enum ConstructorSet<Cx: PatCx> {
/// The type is a tuple or struct. `empty` tracks whether the type is empty.
Struct { empty: bool },
/// This type has the following list of constructors. If `variants` is empty and
@ -889,13 +886,13 @@ pub enum ConstructorSet<Cx: TypeCx> {
/// of the `ConstructorSet` for the type, yet if we forgot to include them in `present` we would be
/// ignoring any row with `Opaque`s in the algorithm. Hence the importance of point 4.
#[derive(Debug)]
pub struct SplitConstructorSet<Cx: TypeCx> {
pub struct SplitConstructorSet<Cx: PatCx> {
pub present: SmallVec<[Constructor<Cx>; 1]>,
pub missing: Vec<Constructor<Cx>>,
pub missing_empty: Vec<Constructor<Cx>>,
}
impl<Cx: TypeCx> ConstructorSet<Cx> {
impl<Cx: PatCx> ConstructorSet<Cx> {
/// This analyzes a column of constructors to 1/ determine which constructors of the type (if
/// any) are missing; 2/ split constructors to handle non-trivial intersections e.g. on ranges
/// or slices. This can get subtle; see [`SplitConstructorSet`] for details of this operation

View file

@ -4,7 +4,7 @@
use rustc_middle::ty::Ty;
use rustc_span::Span;
use crate::rustc::{RustcMatchCheckCtxt, WitnessPat};
use crate::rustc::{RustcPatCtxt, WitnessPat};
#[derive(Subdiagnostic)]
#[label(pattern_analysis_uncovered)]
@ -21,7 +21,7 @@ pub struct Uncovered<'tcx> {
impl<'tcx> Uncovered<'tcx> {
pub fn new<'p>(
span: Span,
cx: &RustcMatchCheckCtxt<'p, 'tcx>,
cx: &RustcPatCtxt<'p, 'tcx>,
witnesses: Vec<WitnessPat<'p, 'tcx>>,
) -> Self
where

View file

@ -84,7 +84,7 @@ impl<'a, T: ?Sized> Captures<'a> for T {}
/// Context that provides type information about constructors.
///
/// Most of the crate is parameterized on a type that implements this trait.
pub trait TypeCx: Sized + fmt::Debug {
pub trait PatCx: Sized + fmt::Debug {
/// The type of a pattern.
type Ty: Clone + fmt::Debug;
/// Errors that can abort analysis.
@ -155,34 +155,34 @@ fn lint_non_contiguous_range_endpoints(
/// The arm of a match expression.
#[derive(Debug)]
pub struct MatchArm<'p, Cx: TypeCx> {
pub struct MatchArm<'p, Cx: PatCx> {
pub pat: &'p DeconstructedPat<Cx>,
pub has_guard: bool,
pub arm_data: Cx::ArmData,
}
impl<'p, Cx: TypeCx> Clone for MatchArm<'p, Cx> {
impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> {
fn clone(&self) -> Self {
Self { pat: self.pat, has_guard: self.has_guard, arm_data: self.arm_data }
}
}
impl<'p, Cx: TypeCx> Copy for MatchArm<'p, Cx> {}
impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {}
/// The entrypoint for this crate. Computes whether a match is exhaustive and which of its arms are
/// useful, and runs some lints.
#[cfg(feature = "rustc")]
pub fn analyze_match<'p, 'tcx>(
tycx: &rustc::RustcMatchCheckCtxt<'p, 'tcx>,
tycx: &rustc::RustcPatCtxt<'p, 'tcx>,
arms: &[rustc::MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
pattern_complexity_limit: Option<usize>,
) -> Result<rustc::UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
use lints::lint_nonexhaustive_missing_variants;
use usefulness::{compute_match_usefulness, ValidityConstraint};
use usefulness::{compute_match_usefulness, PlaceValidity};
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
let scrut_validity = ValidityConstraint::from_bool(tycx.known_valid_scrutinee);
let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee);
let report =
compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity, pattern_complexity_limit)?;

View file

@ -4,15 +4,15 @@
use crate::constructor::Constructor;
use crate::errors::{NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered};
use crate::pat_column::PatternColumn;
use crate::rustc::{RevealedTy, RustcMatchCheckCtxt, WitnessPat};
use crate::rustc::{RevealedTy, RustcPatCtxt, WitnessPat};
use crate::MatchArm;
/// Traverse the patterns to collect any variants of a non_exhaustive enum that fail to be mentioned
/// in a given column.
#[instrument(level = "debug", skip(cx), ret)]
fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
cx: &RustcMatchCheckCtxt<'p, 'tcx>,
column: &PatternColumn<'p, RustcMatchCheckCtxt<'p, 'tcx>>,
cx: &RustcPatCtxt<'p, 'tcx>,
column: &PatternColumn<'p, RustcPatCtxt<'p, 'tcx>>,
) -> Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> {
let Some(&ty) = column.head_ty() else {
return Ok(Vec::new());
@ -57,9 +57,9 @@ fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
}
pub(crate) fn lint_nonexhaustive_missing_variants<'p, 'tcx>(
rcx: &RustcMatchCheckCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, RustcMatchCheckCtxt<'p, 'tcx>>],
pat_column: &PatternColumn<'p, RustcMatchCheckCtxt<'p, 'tcx>>,
rcx: &RustcPatCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, RustcPatCtxt<'p, 'tcx>>],
pat_column: &PatternColumn<'p, RustcPatCtxt<'p, 'tcx>>,
scrut_ty: RevealedTy<'tcx>,
) -> Result<(), ErrorGuaranteed> {
if !matches!(

View file

@ -5,7 +5,7 @@
use smallvec::{smallvec, SmallVec};
use crate::constructor::{Constructor, Slice, SliceKind};
use crate::{PrivateUninhabitedField, TypeCx};
use crate::{PatCx, PrivateUninhabitedField};
use self::Constructor::*;
@ -21,7 +21,7 @@ fn new() -> Self {
}
/// A pattern with an index denoting which field it corresponds to.
pub struct IndexedPat<Cx: TypeCx> {
pub struct IndexedPat<Cx: PatCx> {
pub idx: usize,
pub pat: DeconstructedPat<Cx>,
}
@ -29,7 +29,7 @@ pub struct IndexedPat<Cx: TypeCx> {
/// Values and patterns can be represented as a constructor applied to some fields. This represents
/// a pattern in this form. A `DeconstructedPat` will almost always come from user input; the only
/// exception are some `Wildcard`s introduced during pattern lowering.
pub struct DeconstructedPat<Cx: TypeCx> {
pub struct DeconstructedPat<Cx: PatCx> {
ctor: Constructor<Cx>,
fields: Vec<IndexedPat<Cx>>,
/// The number of fields in this pattern. E.g. if the pattern is `SomeStruct { field12: true, ..
@ -43,7 +43,7 @@ pub struct DeconstructedPat<Cx: TypeCx> {
pub(crate) uid: PatId,
}
impl<Cx: TypeCx> DeconstructedPat<Cx> {
impl<Cx: PatCx> DeconstructedPat<Cx> {
pub fn new(
ctor: Constructor<Cx>,
fields: Vec<IndexedPat<Cx>>,
@ -136,7 +136,7 @@ pub fn walk<'a>(&'a self, it: &mut impl FnMut(&'a Self) -> bool) {
}
/// This is best effort and not good enough for a `Display` impl.
impl<Cx: TypeCx> fmt::Debug for DeconstructedPat<Cx> {
impl<Cx: PatCx> fmt::Debug for DeconstructedPat<Cx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let pat = self;
let mut first = true;
@ -219,14 +219,14 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// algorithm. Do not use `Wild` to represent a wildcard pattern comping from user input.
///
/// This is morally `Option<&'p DeconstructedPat>` where `None` is interpreted as a wildcard.
pub(crate) enum PatOrWild<'p, Cx: TypeCx> {
pub(crate) enum PatOrWild<'p, Cx: PatCx> {
/// A non-user-provided wildcard, created during specialization.
Wild,
/// A user-provided pattern.
Pat(&'p DeconstructedPat<Cx>),
}
impl<'p, Cx: TypeCx> Clone for PatOrWild<'p, Cx> {
impl<'p, Cx: PatCx> Clone for PatOrWild<'p, Cx> {
fn clone(&self) -> Self {
match self {
PatOrWild::Wild => PatOrWild::Wild,
@ -235,9 +235,9 @@ fn clone(&self) -> Self {
}
}
impl<'p, Cx: TypeCx> Copy for PatOrWild<'p, Cx> {}
impl<'p, Cx: PatCx> Copy for PatOrWild<'p, Cx> {}
impl<'p, Cx: TypeCx> PatOrWild<'p, Cx> {
impl<'p, Cx: PatCx> PatOrWild<'p, Cx> {
pub(crate) fn as_pat(&self) -> Option<&'p DeconstructedPat<Cx>> {
match self {
PatOrWild::Wild => None,
@ -283,7 +283,7 @@ pub(crate) fn specialize(
}
}
impl<'p, Cx: TypeCx> fmt::Debug for PatOrWild<'p, Cx> {
impl<'p, Cx: PatCx> fmt::Debug for PatOrWild<'p, Cx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PatOrWild::Wild => write!(f, "_"),
@ -295,19 +295,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// Same idea as `DeconstructedPat`, except this is a fictitious pattern built up for diagnostics
/// purposes. As such they don't use interning and can be cloned.
#[derive(Debug)]
pub struct WitnessPat<Cx: TypeCx> {
pub struct WitnessPat<Cx: PatCx> {
ctor: Constructor<Cx>,
pub(crate) fields: Vec<WitnessPat<Cx>>,
ty: Cx::Ty,
}
impl<Cx: TypeCx> Clone for WitnessPat<Cx> {
impl<Cx: PatCx> Clone for WitnessPat<Cx> {
fn clone(&self) -> Self {
Self { ctor: self.ctor.clone(), fields: self.fields.clone(), ty: self.ty.clone() }
}
}
impl<Cx: TypeCx> WitnessPat<Cx> {
impl<Cx: PatCx> WitnessPat<Cx> {
pub(crate) fn new(ctor: Constructor<Cx>, fields: Vec<Self>, ty: Cx::Ty) -> Self {
Self { ctor, fields, ty }
}

View file

@ -1,6 +1,6 @@
use crate::constructor::{Constructor, SplitConstructorSet};
use crate::pat::{DeconstructedPat, PatOrWild};
use crate::{Captures, MatchArm, TypeCx};
use crate::{Captures, MatchArm, PatCx};
/// A column of patterns in a match, where a column is the intuitive notion of "subpatterns that
/// inspect the same subvalue/place".
@ -11,12 +11,12 @@
///
/// This is not used in the usefulness algorithm; only in lints.
#[derive(Debug)]
pub struct PatternColumn<'p, Cx: TypeCx> {
pub struct PatternColumn<'p, Cx: PatCx> {
/// This must not contain an or-pattern. `expand_and_push` takes care to expand them.
patterns: Vec<&'p DeconstructedPat<Cx>>,
}
impl<'p, Cx: TypeCx> PatternColumn<'p, Cx> {
impl<'p, Cx: PatCx> PatternColumn<'p, Cx> {
pub fn new(arms: &[MatchArm<'p, Cx>]) -> Self {
let patterns = Vec::with_capacity(arms.len());
let mut column = PatternColumn { patterns };

View file

@ -18,20 +18,19 @@
use crate::constructor::{
IntRange, MaybeInfiniteInt, OpaqueId, RangeEnd, Slice, SliceKind, VariantVisibility,
};
use crate::{errors, Captures, PrivateUninhabitedField, TypeCx};
use crate::{errors, Captures, PatCx, PrivateUninhabitedField};
use crate::constructor::Constructor::*;
// Re-export rustc-specific versions of all these types.
pub type Constructor<'p, 'tcx> = crate::constructor::Constructor<RustcMatchCheckCtxt<'p, 'tcx>>;
pub type ConstructorSet<'p, 'tcx> =
crate::constructor::ConstructorSet<RustcMatchCheckCtxt<'p, 'tcx>>;
pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat<RustcMatchCheckCtxt<'p, 'tcx>>;
pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcMatchCheckCtxt<'p, 'tcx>>;
pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcMatchCheckCtxt<'p, 'tcx>>;
pub type Constructor<'p, 'tcx> = crate::constructor::Constructor<RustcPatCtxt<'p, 'tcx>>;
pub type ConstructorSet<'p, 'tcx> = crate::constructor::ConstructorSet<RustcPatCtxt<'p, 'tcx>>;
pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat<RustcPatCtxt<'p, 'tcx>>;
pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcPatCtxt<'p, 'tcx>>;
pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcPatCtxt<'p, 'tcx>>;
pub type UsefulnessReport<'p, 'tcx> =
crate::usefulness::UsefulnessReport<'p, RustcMatchCheckCtxt<'p, 'tcx>>;
pub type WitnessPat<'p, 'tcx> = crate::pat::WitnessPat<RustcMatchCheckCtxt<'p, 'tcx>>;
crate::usefulness::UsefulnessReport<'p, RustcPatCtxt<'p, 'tcx>>;
pub type WitnessPat<'p, 'tcx> = crate::pat::WitnessPat<RustcPatCtxt<'p, 'tcx>>;
/// A type which has gone through `cx.reveal_opaque_ty`, i.e. if it was opaque it was replaced by
/// the hidden type if allowed in the current body. This ensures we consistently inspect the hidden
@ -62,7 +61,7 @@ pub fn inner(self) -> Ty<'tcx> {
}
#[derive(Clone)]
pub struct RustcMatchCheckCtxt<'p, 'tcx: 'p> {
pub struct RustcPatCtxt<'p, 'tcx: 'p> {
pub tcx: TyCtxt<'tcx>,
pub typeck_results: &'tcx ty::TypeckResults<'tcx>,
/// The module in which the match occurs. This is necessary for
@ -87,22 +86,19 @@ pub struct RustcMatchCheckCtxt<'p, 'tcx: 'p> {
pub known_valid_scrutinee: bool,
}
impl<'p, 'tcx: 'p> fmt::Debug for RustcMatchCheckCtxt<'p, 'tcx> {
impl<'p, 'tcx: 'p> fmt::Debug for RustcPatCtxt<'p, 'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RustcMatchCheckCtxt").finish()
f.debug_struct("RustcPatCtxt").finish()
}
}
impl<'p, 'tcx: 'p> RustcMatchCheckCtxt<'p, 'tcx> {
impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> {
/// Type inference occasionally gives us opaque types in places where corresponding patterns
/// have more specific types. To avoid inconsistencies as well as detect opaque uninhabited
/// types, we use the corresponding concrete type if possible.
#[inline]
pub fn reveal_opaque_ty(&self, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
fn reveal_inner<'tcx>(
cx: &RustcMatchCheckCtxt<'_, 'tcx>,
ty: Ty<'tcx>,
) -> RevealedTy<'tcx> {
fn reveal_inner<'tcx>(cx: &RustcPatCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
let ty::Alias(ty::Opaque, alias_ty) = *ty.kind() else { bug!() };
if let Some(local_def_id) = alias_ty.def_id.as_local() {
let key = ty::OpaqueTypeKey { def_id: local_def_id, args: alias_ty.args };
@ -199,7 +195,7 @@ pub(crate) fn ctor_sub_tys<'a>(
+ ExactSizeIterator
+ Captures<'a> {
fn reveal_and_alloc<'a, 'tcx>(
cx: &'a RustcMatchCheckCtxt<'_, 'tcx>,
cx: &'a RustcPatCtxt<'_, 'tcx>,
iter: impl Iterator<Item = Ty<'tcx>>,
) -> &'a [(RevealedTy<'tcx>, PrivateUninhabitedField)] {
cx.dropless_arena.alloc_from_iter(
@ -218,7 +214,7 @@ fn reveal_and_alloc<'a, 'tcx>(
reveal_and_alloc(cx, once(args.type_at(0)))
} else {
let variant =
&adt.variant(RustcMatchCheckCtxt::variant_index_for_adt(&ctor, *adt));
&adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
// In the cases of either a `#[non_exhaustive]` field list or a non-public
// field, we skip uninhabited fields in order not to reveal the
@ -270,7 +266,7 @@ pub(crate) fn ctor_arity(&self, ctor: &Constructor<'p, 'tcx>, ty: RevealedTy<'tc
// patterns. If we're here we can assume this is a box pattern.
1
} else {
let variant_idx = RustcMatchCheckCtxt::variant_index_for_adt(&ctor, *adt);
let variant_idx = RustcPatCtxt::variant_index_for_adt(&ctor, *adt);
adt.variant(variant_idx).fields.len()
}
}
@ -506,7 +502,7 @@ pub fn lower_pat(&self, pat: &'p Pat<'tcx>) -> DeconstructedPat<'p, 'tcx> {
_ => bug!(),
};
let variant =
&adt.variant(RustcMatchCheckCtxt::variant_index_for_adt(&ctor, *adt));
&adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
arity = variant.fields.len();
fields = subpatterns
.iter()
@ -710,7 +706,7 @@ pub(crate) fn hoist_pat_range_bdy(
None => PatRangeBoundary::PosInfinity,
}
}
JustAfterMax | PosInfinity => PatRangeBoundary::PosInfinity,
PosInfinity => PatRangeBoundary::PosInfinity,
}
}
@ -774,8 +770,7 @@ pub fn hoist_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> Pat<'tcx> {
PatKind::Deref { subpattern: subpatterns.next().unwrap() }
}
ty::Adt(adt_def, args) => {
let variant_index =
RustcMatchCheckCtxt::variant_index_for_adt(&pat.ctor(), *adt_def);
let variant_index = RustcPatCtxt::variant_index_for_adt(&pat.ctor(), *adt_def);
let subpatterns = subpatterns
.enumerate()
.map(|(i, pattern)| FieldPat { field: FieldIdx::new(i), pattern })
@ -843,7 +838,7 @@ pub fn hoist_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> Pat<'tcx> {
}
}
impl<'p, 'tcx: 'p> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> {
type Ty = RevealedTy<'tcx>;
type Error = ErrorGuaranteed;
type VariantIdx = VariantIdx;

View file

@ -242,7 +242,7 @@
//! Therefore `usefulness(tp_1, tp_2, tq)` returns the single witness-tuple `[Variant2(Some(true), 0)]`.
//!
//!
//! Computing the set of constructors for a type is done in [`TypeCx::ctors_for_ty`]. See
//! Computing the set of constructors for a type is done in [`PatCx::ctors_for_ty`]. See
//! the following sections for more accurate versions of the algorithm and corresponding links.
//!
//!
@ -540,8 +540,8 @@
//! We track in the algorithm whether a given place is known to contain valid data. This is done
//! first by inspecting the scrutinee syntactically (which gives us `cx.known_valid_scrutinee`), and
//! then by tracking validity of each column of the matrix (which correspond to places) as we
//! recurse into subpatterns. That second part is done through [`ValidityConstraint`], most notably
//! [`ValidityConstraint::specialize`].
//! recurse into subpatterns. That second part is done through [`PlaceValidity`], most notably
//! [`PlaceValidity::specialize`].
//!
//! Having said all that, in practice we don't fully follow what's been presented in this section.
//! Let's call "toplevel exception" the case where the match scrutinee itself has type `!` or
@ -716,9 +716,9 @@
use crate::constructor::{Constructor, ConstructorSet, IntRange};
use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat};
use crate::{Captures, MatchArm, PrivateUninhabitedField, TypeCx};
use crate::{Captures, MatchArm, PatCx, PrivateUninhabitedField};
use self::ValidityConstraint::*;
use self::PlaceValidity::*;
#[cfg(feature = "rustc")]
use rustc_data_structures::stack::ensure_sufficient_stack;
@ -728,7 +728,7 @@ pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
}
/// Context that provides information for usefulness checking.
struct UsefulnessCtxt<'a, Cx: TypeCx> {
struct UsefulnessCtxt<'a, Cx: PatCx> {
/// The context for type information.
tycx: &'a Cx,
/// Collect the patterns found useful during usefulness checking. This is used to lint
@ -738,7 +738,7 @@ struct UsefulnessCtxt<'a, Cx: TypeCx> {
complexity_level: usize,
}
impl<'a, Cx: TypeCx> UsefulnessCtxt<'a, Cx> {
impl<'a, Cx: PatCx> UsefulnessCtxt<'a, Cx> {
fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> {
self.complexity_level += complexity_add;
if self
@ -752,26 +752,26 @@ fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx:
}
/// Context that provides information local to a place under investigation.
struct PlaceCtxt<'a, Cx: TypeCx> {
struct PlaceCtxt<'a, Cx: PatCx> {
cx: &'a Cx,
/// Type of the place under investigation.
ty: &'a Cx::Ty,
}
impl<'a, Cx: TypeCx> Copy for PlaceCtxt<'a, Cx> {}
impl<'a, Cx: TypeCx> Clone for PlaceCtxt<'a, Cx> {
impl<'a, Cx: PatCx> Copy for PlaceCtxt<'a, Cx> {}
impl<'a, Cx: PatCx> Clone for PlaceCtxt<'a, Cx> {
fn clone(&self) -> Self {
Self { cx: self.cx, ty: self.ty }
}
}
impl<'a, Cx: TypeCx> fmt::Debug for PlaceCtxt<'a, Cx> {
impl<'a, Cx: PatCx> fmt::Debug for PlaceCtxt<'a, Cx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("PlaceCtxt").field("ty", self.ty).finish()
}
}
impl<'a, Cx: TypeCx> PlaceCtxt<'a, Cx> {
impl<'a, Cx: PatCx> PlaceCtxt<'a, Cx> {
fn ctor_arity(&self, ctor: &Constructor<Cx>) -> usize {
self.cx.ctor_arity(ctor, self.ty)
}
@ -780,18 +780,14 @@ fn wild_from_ctor(&self, ctor: Constructor<Cx>) -> WitnessPat<Cx> {
}
}
/// Serves two purposes:
/// - in a wildcard, tracks whether the wildcard matches only valid values (i.e. is a binding `_a`)
/// or also invalid values (i.e. is a true `_` pattern).
/// - in the matrix, track whether a given place (aka column) is known to contain a valid value or
/// not.
/// Track whether a given place (aka column) is known to contain a valid value or not.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ValidityConstraint {
pub enum PlaceValidity {
ValidOnly,
MaybeInvalid,
}
impl ValidityConstraint {
impl PlaceValidity {
pub fn from_bool(is_valid_only: bool) -> Self {
if is_valid_only { ValidOnly } else { MaybeInvalid }
}
@ -806,7 +802,7 @@ fn is_known_valid(self) -> bool {
///
/// Pending further opsem decisions, the current behavior is: validity is preserved, except
/// inside `&` and union fields where validity is reset to `MaybeInvalid`.
fn specialize<Cx: TypeCx>(self, ctor: &Constructor<Cx>) -> Self {
fn specialize<Cx: PatCx>(self, ctor: &Constructor<Cx>) -> Self {
// We preserve validity except when we go inside a reference or a union field.
if matches!(ctor, Constructor::Ref | Constructor::UnionField) {
// Validity of `x: &T` does not imply validity of `*x: T`.
@ -817,7 +813,7 @@ fn specialize<Cx: TypeCx>(self, ctor: &Constructor<Cx>) -> Self {
}
}
impl fmt::Display for ValidityConstraint {
impl fmt::Display for PlaceValidity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
ValidOnly => "",
@ -829,19 +825,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// Data about a place under investigation. Its methods contain a lot of the logic used to analyze
/// the constructors in the matrix.
struct PlaceInfo<Cx: TypeCx> {
struct PlaceInfo<Cx: PatCx> {
/// The type of the place.
ty: Cx::Ty,
/// Whether the place is a private uninhabited field. If so we skip this field during analysis
/// so that we don't observe its emptiness.
private_uninhabited: bool,
/// Whether the place is known to contain valid data.
validity: ValidityConstraint,
validity: PlaceValidity,
/// Whether the place is the scrutinee itself or a subplace of it.
is_scrutinee: bool,
}
impl<Cx: TypeCx> PlaceInfo<Cx> {
impl<Cx: PatCx> PlaceInfo<Cx> {
/// Given a constructor for the current place, we return one `PlaceInfo` for each field of the
/// constructor.
fn specialize<'a>(
@ -936,7 +932,7 @@ fn split_column_ctors<'a>(
}
}
impl<Cx: TypeCx> Clone for PlaceInfo<Cx> {
impl<Cx: PatCx> Clone for PlaceInfo<Cx> {
fn clone(&self) -> Self {
Self {
ty: self.ty.clone(),
@ -951,7 +947,7 @@ fn clone(&self) -> Self {
// The three lifetimes are:
// - 'p coming from the input
// - Cx global compilation context
struct PatStack<'p, Cx: TypeCx> {
struct PatStack<'p, Cx: PatCx> {
// Rows of len 1 are very common, which is why `SmallVec[_; 2]` works well.
pats: SmallVec<[PatOrWild<'p, Cx>; 2]>,
/// Sometimes we know that as far as this row is concerned, the current case is already handled
@ -960,13 +956,13 @@ struct PatStack<'p, Cx: TypeCx> {
relevant: bool,
}
impl<'p, Cx: TypeCx> Clone for PatStack<'p, Cx> {
impl<'p, Cx: PatCx> Clone for PatStack<'p, Cx> {
fn clone(&self) -> Self {
Self { pats: self.pats.clone(), relevant: self.relevant }
}
}
impl<'p, Cx: TypeCx> PatStack<'p, Cx> {
impl<'p, Cx: PatCx> PatStack<'p, Cx> {
fn from_pattern(pat: &'p DeconstructedPat<Cx>) -> Self {
PatStack { pats: smallvec![PatOrWild::Pat(pat)], relevant: true }
}
@ -1026,7 +1022,7 @@ fn pop_head_constructor(
}
}
impl<'p, Cx: TypeCx> fmt::Debug for PatStack<'p, Cx> {
impl<'p, Cx: PatCx> fmt::Debug for PatStack<'p, Cx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// We pretty-print similarly to the `Debug` impl of `Matrix`.
write!(f, "+")?;
@ -1039,7 +1035,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// A row of the matrix.
#[derive(Clone)]
struct MatrixRow<'p, Cx: TypeCx> {
struct MatrixRow<'p, Cx: PatCx> {
// The patterns in the row.
pats: PatStack<'p, Cx>,
/// Whether the original arm had a guard. This is inherited when specializing.
@ -1059,7 +1055,7 @@ struct MatrixRow<'p, Cx: TypeCx> {
intersects: BitSet<usize>,
}
impl<'p, Cx: TypeCx> MatrixRow<'p, Cx> {
impl<'p, Cx: PatCx> MatrixRow<'p, Cx> {
fn is_empty(&self) -> bool {
self.pats.is_empty()
}
@ -1108,7 +1104,7 @@ fn pop_head_constructor(
}
}
impl<'p, Cx: TypeCx> fmt::Debug for MatrixRow<'p, Cx> {
impl<'p, Cx: PatCx> fmt::Debug for MatrixRow<'p, Cx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.pats.fmt(f)
}
@ -1125,7 +1121,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// specializing `(,)` and `Some` on a pattern of type `(Option<u32>, bool)`, the first column of
/// the matrix will correspond to `scrutinee.0.Some.0` and the second column to `scrutinee.1`.
#[derive(Clone)]
struct Matrix<'p, Cx: TypeCx> {
struct Matrix<'p, Cx: PatCx> {
/// Vector of rows. The rows must form a rectangular 2D array. Moreover, all the patterns of
/// each column must have the same type. Each column corresponds to a place within the
/// scrutinee.
@ -1138,7 +1134,7 @@ struct Matrix<'p, Cx: TypeCx> {
wildcard_row_is_relevant: bool,
}
impl<'p, Cx: TypeCx> Matrix<'p, Cx> {
impl<'p, Cx: PatCx> Matrix<'p, Cx> {
/// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
/// expands it. Internal method, prefer [`Matrix::new`].
fn expand_and_push(&mut self, mut row: MatrixRow<'p, Cx>) {
@ -1155,11 +1151,7 @@ fn expand_and_push(&mut self, mut row: MatrixRow<'p, Cx>) {
}
/// Build a new matrix from an iterator of `MatchArm`s.
fn new(
arms: &[MatchArm<'p, Cx>],
scrut_ty: Cx::Ty,
scrut_validity: ValidityConstraint,
) -> Self {
fn new(arms: &[MatchArm<'p, Cx>], scrut_ty: Cx::Ty, scrut_validity: PlaceValidity) -> Self {
let place_info = PlaceInfo {
ty: scrut_ty,
private_uninhabited: false,
@ -1264,7 +1256,7 @@ fn unspecialize(&mut self, specialized: Self) {
/// + _ + [_, _, tail @ ..] +
/// | ✓ | ? | // column validity
/// ```
impl<'p, Cx: TypeCx> fmt::Debug for Matrix<'p, Cx> {
impl<'p, Cx: PatCx> fmt::Debug for Matrix<'p, Cx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\n")?;
@ -1355,15 +1347,15 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///
/// See the top of the file for more detailed explanations and examples.
#[derive(Debug)]
struct WitnessStack<Cx: TypeCx>(Vec<WitnessPat<Cx>>);
struct WitnessStack<Cx: PatCx>(Vec<WitnessPat<Cx>>);
impl<Cx: TypeCx> Clone for WitnessStack<Cx> {
impl<Cx: PatCx> Clone for WitnessStack<Cx> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<Cx: TypeCx> WitnessStack<Cx> {
impl<Cx: PatCx> WitnessStack<Cx> {
/// Asserts that the witness contains a single pattern, and returns it.
fn single_pattern(self) -> WitnessPat<Cx> {
assert_eq!(self.0.len(), 1);
@ -1408,15 +1400,15 @@ fn apply_constructor(&mut self, pcx: &PlaceCtxt<'_, Cx>, ctor: &Constructor<Cx>)
/// Just as the `Matrix` starts with a single column, by the end of the algorithm, this has a single
/// column, which contains the patterns that are missing for the match to be exhaustive.
#[derive(Debug)]
struct WitnessMatrix<Cx: TypeCx>(Vec<WitnessStack<Cx>>);
struct WitnessMatrix<Cx: PatCx>(Vec<WitnessStack<Cx>>);
impl<Cx: TypeCx> Clone for WitnessMatrix<Cx> {
impl<Cx: PatCx> Clone for WitnessMatrix<Cx> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<Cx: TypeCx> WitnessMatrix<Cx> {
impl<Cx: PatCx> WitnessMatrix<Cx> {
/// New matrix with no witnesses.
fn empty() -> Self {
WitnessMatrix(Vec::new())
@ -1490,7 +1482,7 @@ fn extend(&mut self, other: Self) {
///
/// We can however get false negatives because exhaustiveness does not explore all cases. See the
/// section on relevancy at the top of the file.
fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
fn collect_overlapping_range_endpoints<'p, Cx: PatCx>(
cx: &Cx,
overlap_range: IntRange,
matrix: &Matrix<'p, Cx>,
@ -1549,7 +1541,7 @@ fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
}
/// Collect ranges that have a singleton gap between them.
fn collect_non_contiguous_range_endpoints<'p, Cx: TypeCx>(
fn collect_non_contiguous_range_endpoints<'p, Cx: PatCx>(
cx: &Cx,
gap_range: &IntRange,
matrix: &Matrix<'p, Cx>,
@ -1590,7 +1582,7 @@ fn collect_non_contiguous_range_endpoints<'p, Cx: TypeCx>(
/// (using `apply_constructor` and by updating `row.useful` for each parent row).
/// This is all explained at the top of the file.
#[instrument(level = "debug", skip(mcx), ret)]
fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>(
mcx: &mut UsefulnessCtxt<'a, Cx>,
matrix: &mut Matrix<'p, Cx>,
) -> Result<WitnessMatrix<Cx>, Cx::Error> {
@ -1687,7 +1679,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
/// Indicates whether or not a given arm is useful.
#[derive(Clone, Debug)]
pub enum Usefulness<'p, Cx: TypeCx> {
pub enum Usefulness<'p, Cx: PatCx> {
/// The arm is useful. This additionally carries a set of or-pattern branches that have been
/// found to be redundant despite the overall arm being useful. Used only in the presence of
/// or-patterns, otherwise it stays empty.
@ -1698,11 +1690,11 @@ pub enum Usefulness<'p, Cx: TypeCx> {
}
/// Report whether this pattern was found useful, and its subpatterns that were not useful if any.
fn collect_pattern_usefulness<'p, Cx: TypeCx>(
fn collect_pattern_usefulness<'p, Cx: PatCx>(
useful_subpatterns: &FxHashSet<PatId>,
pat: &'p DeconstructedPat<Cx>,
) -> Usefulness<'p, Cx> {
fn pat_is_useful<'p, Cx: TypeCx>(
fn pat_is_useful<'p, Cx: PatCx>(
useful_subpatterns: &FxHashSet<PatId>,
pat: &'p DeconstructedPat<Cx>,
) -> bool {
@ -1740,7 +1732,7 @@ fn pat_is_useful<'p, Cx: TypeCx>(
}
/// The output of checking a match for exhaustiveness and arm usefulness.
pub struct UsefulnessReport<'p, Cx: TypeCx> {
pub struct UsefulnessReport<'p, Cx: PatCx> {
/// For each arm of the input, whether that arm is useful after the arms above it.
pub arm_usefulness: Vec<(MatchArm<'p, Cx>, Usefulness<'p, Cx>)>,
/// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
@ -1750,11 +1742,11 @@ pub struct UsefulnessReport<'p, Cx: TypeCx> {
/// Computes whether a match is exhaustive and which of its arms are useful.
#[instrument(skip(tycx, arms), level = "debug")]
pub fn compute_match_usefulness<'p, Cx: TypeCx>(
pub fn compute_match_usefulness<'p, Cx: PatCx>(
tycx: &Cx,
arms: &[MatchArm<'p, Cx>],
scrut_ty: Cx::Ty,
scrut_validity: ValidityConstraint,
scrut_validity: PlaceValidity,
complexity_limit: Option<usize>,
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
let mut cx = UsefulnessCtxt {

View file

@ -1831,7 +1831,9 @@ pub(crate) fn parse_function_return(slot: &mut FunctionReturn, v: Option<&str>)
print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
"print the LLVM optimization passes being run (default: no)"),
print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
"print the result of the monomorphization collection pass"),
"print the result of the monomorphization collection pass. \
Value `lazy` means to use normal collection; `eager` means to collect all items.
Note that this overwrites the effect `-Clink-dead-code` has on collection!"),
print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
"print layout information for each type encountered (default: no)"),
print_vtable_sizes: bool = (false, parse_bool, [UNTRACKED],

View file

@ -211,7 +211,7 @@ fn to_json(&self) -> Json {
impl LinkerFlavor {
/// At this point the target's reference linker flavor doesn't yet exist and we need to infer
/// it. The inference always succeds and gives some result, and we don't report any flavor
/// it. The inference always succeeds and gives some result, and we don't report any flavor
/// incompatibility errors for json target specs. The CLI flavor is used as the main source
/// of truth, other flags are used in case of ambiguities.
fn from_cli_json(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
@ -581,7 +581,7 @@ pub fn is_disabled(self) -> bool {
self == LinkSelfContainedDefault::False
}
/// Returns whether the target spec explictly requests self-contained linking, i.e. not via
/// Returns whether the target spec explicitly requests self-contained linking, i.e. not via
/// inference.
pub fn is_linker_enabled(self) -> bool {
match self {
@ -2090,7 +2090,7 @@ pub struct TargetOptions {
/// If `None`, then `CFG_DEFAULT_CODEGEN_BACKEND` environmental variable captured when
/// compiling `rustc` will be used instead (or llvm if it is not set).
///
/// N.B. when *using* the compiler, backend can always be overriden with `-Zcodegen-backend`.
/// N.B. when *using* the compiler, backend can always be overridden with `-Zcodegen-backend`.
pub default_codegen_backend: Option<StaticCow<str>>,
/// Whether to generate trap instructions in places where optimization would

View file

@ -3091,6 +3091,13 @@ fn get_safe_transmute_error_and_reason(
rustc_transmute::Reason::DstIsTooBig => {
format!("The size of `{src}` is smaller than the size of `{dst}`")
}
rustc_transmute::Reason::DstRefIsTooBig { src, dst } => {
let src_size = src.size;
let dst_size = dst.size;
format!(
"The referent size of `{src}` ({src_size} bytes) is smaller than that of `{dst}` ({dst_size} bytes)"
)
}
rustc_transmute::Reason::SrcSizeOverflow => {
format!(
"values of the type `{src}` are too big for the current architecture"

View file

@ -35,6 +35,8 @@ pub(crate) trait Def: Debug + Hash + Eq + PartialEq + Copy + Clone {
pub trait Ref: Debug + Hash + Eq + PartialEq + Copy + Clone {
fn min_align(&self) -> usize;
fn size(&self) -> usize;
fn is_mutable(&self) -> bool;
}
@ -48,6 +50,9 @@ impl Ref for ! {
fn min_align(&self) -> usize {
unreachable!()
}
fn size(&self) -> usize {
unreachable!()
}
fn is_mutable(&self) -> bool {
unreachable!()
}
@ -57,6 +62,7 @@ fn is_mutable(&self) -> bool {
pub mod rustc {
use rustc_middle::mir::Mutability;
use rustc_middle::ty::{self, Ty};
use std::fmt::{self, Write};
/// A reference in the layout.
#[derive(Debug, Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Copy)]
@ -65,6 +71,7 @@ pub struct Ref<'tcx> {
pub ty: Ty<'tcx>,
pub mutability: Mutability,
pub align: usize,
pub size: usize,
}
impl<'tcx> super::Ref for Ref<'tcx> {
@ -72,6 +79,10 @@ fn min_align(&self) -> usize {
self.align
}
fn size(&self) -> usize {
self.size
}
fn is_mutable(&self) -> bool {
match self.mutability {
Mutability::Mut => true,
@ -81,6 +92,16 @@ fn is_mutable(&self) -> bool {
}
impl<'tcx> Ref<'tcx> {}
impl<'tcx> fmt::Display for Ref<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_char('&')?;
if self.mutability == Mutability::Mut {
f.write_str("mut ")?;
}
self.ty.fmt(f)
}
}
/// A visibility node in the layout.
#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)]
pub enum Def<'tcx> {

View file

@ -372,12 +372,15 @@ pub fn from_ty(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Result<Self, Err> {
}
ty::Ref(lifetime, ty, mutability) => {
let align = layout_of(tcx, *ty)?.align();
let layout = layout_of(tcx, *ty)?;
let align = layout.align();
let size = layout.size();
Ok(Tree::Ref(Ref {
lifetime: *lifetime,
ty: *ty,
mutability: *mutability,
align,
size,
}))
}

View file

@ -23,7 +23,7 @@ pub struct Assume {
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub enum Answer<R> {
Yes,
No(Reason),
No(Reason<R>),
If(Condition<R>),
}
@ -42,7 +42,7 @@ pub enum Condition<R> {
/// Answers "why wasn't the source type transmutable into the destination type?"
#[derive(Debug, Hash, Eq, PartialEq, PartialOrd, Ord, Clone)]
pub enum Reason {
pub enum Reason<T> {
/// The layout of the source type is unspecified.
SrcIsUnspecified,
/// The layout of the destination type is unspecified.
@ -53,6 +53,13 @@ pub enum Reason {
DstMayHaveSafetyInvariants,
/// `Dst` is larger than `Src`, and the excess bytes were not exclusively uninitialized.
DstIsTooBig,
/// A referent of `Dst` is larger than a referent in `Src`.
DstRefIsTooBig {
/// The referent of the source type.
src: T,
/// The too-large referent of the destination type.
dst: T,
},
/// Src should have a stricter alignment than Dst, but it does not.
DstHasStricterAlignment { src_min_align: usize, dst_min_align: usize },
/// Can't go from shared pointer to unique pointer

View file

@ -266,6 +266,11 @@ fn answer_memo(
src_min_align: src_ref.min_align(),
dst_min_align: dst_ref.min_align(),
})
} else if dst_ref.size() > src_ref.size() {
Answer::No(Reason::DstRefIsTooBig {
src: src_ref,
dst: dst_ref,
})
} else {
// ...such that `src` is transmutable into `dst`, if
// `src_ref` is transmutability into `dst_ref`.

View file

@ -383,7 +383,7 @@ pub fn is_full(&self, size: Size) -> Result<bool, Error> {
return Err(error!("Expected size <= 128 bits, but found {} instead", size.bits()));
};
if self.start <= max_value && self.end <= max_value {
Ok(self.start == 0 && max_value == self.end)
Ok(self.start == (self.end.wrapping_add(1) & max_value))
} else {
Err(error!("Range `{self:?}` out of bounds for size `{}` bits.", size.bits()))
}

View file

@ -1 +1 @@
timeout = 7200
timeout = 14400

View file

@ -852,6 +852,7 @@ pub fn line_directive<'line>(
"only-sparc64",
"only-stable",
"only-thumb",
"only-unix",
"only-wasm32",
"only-wasm32-bare",
"only-windows",

View file

@ -285,6 +285,7 @@ fn ignore_target() {
assert!(check_ignore(&config, "//@ ignore-x86_64-unknown-linux-gnu"));
assert!(check_ignore(&config, "//@ ignore-x86_64"));
assert!(check_ignore(&config, "//@ ignore-linux"));
assert!(check_ignore(&config, "//@ ignore-unix"));
assert!(check_ignore(&config, "//@ ignore-gnu"));
assert!(check_ignore(&config, "//@ ignore-64bit"));
@ -300,6 +301,7 @@ fn only_target() {
assert!(check_ignore(&config, "//@ only-x86"));
assert!(check_ignore(&config, "//@ only-linux"));
assert!(check_ignore(&config, "//@ only-unix"));
assert!(check_ignore(&config, "//@ only-msvc"));
assert!(check_ignore(&config, "//@ only-32bit"));

View file

@ -394,17 +394,17 @@ help: ensure that all possible cases are being handled by adding a match arm wit
LL | match $s { $($t)+ => {}, u128::MAX => todo!() }
| ++++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `340282366920938463463374607431768211454_u128..=u128::MAX` not covered
error[E0004]: non-exhaustive patterns: `340282366920938463463374607431768211454_u128..` not covered
--> $DIR/half-open-range-pats-exhaustive-fail.rs:93:12
|
LL | m!(0, ..ALMOST_MAX);
| ^ pattern `340282366920938463463374607431768211454_u128..=u128::MAX` not covered
| ^ pattern `340282366920938463463374607431768211454_u128..` not covered
|
= note: the matched value is of type `u128`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
LL | match $s { $($t)+ => {}, 340282366920938463463374607431768211454_u128..=u128::MAX => todo!() }
| +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
LL | match $s { $($t)+ => {}, 340282366920938463463374607431768211454_u128.. => todo!() }
| +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `0_u128` not covered
--> $DIR/half-open-range-pats-exhaustive-fail.rs:94:12
@ -754,17 +754,17 @@ help: ensure that all possible cases are being handled by adding a match arm wit
LL | match $s { $($t)+ => {}, i128::MAX => todo!() }
| ++++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `170141183460469231731687303715884105726_i128..=i128::MAX` not covered
error[E0004]: non-exhaustive patterns: `170141183460469231731687303715884105726_i128..` not covered
--> $DIR/half-open-range-pats-exhaustive-fail.rs:161:12
|
LL | m!(0, ..ALMOST_MAX);
| ^ pattern `170141183460469231731687303715884105726_i128..=i128::MAX` not covered
| ^ pattern `170141183460469231731687303715884105726_i128..` not covered
|
= note: the matched value is of type `i128`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
LL | match $s { $($t)+ => {}, 170141183460469231731687303715884105726_i128..=i128::MAX => todo!() }
| +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
LL | match $s { $($t)+ => {}, 170141183460469231731687303715884105726_i128.. => todo!() }
| +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `i128::MIN` not covered
--> $DIR/half-open-range-pats-exhaustive-fail.rs:162:12

View file

@ -0,0 +1,13 @@
trait Trait {}
impl Trait for i32 {}
// Since `Assoc` doesn't actually exist, it's "stranded", and won't show up in
// the list of opaques that may be defined by the function. Make sure we don't
// ICE in this case.
fn produce<T>() -> impl Trait<Assoc = impl Trait> {
//~^ ERROR associated type `Assoc` not found for `Trait`
16
}
fn main () {}

View file

@ -0,0 +1,9 @@
error[E0220]: associated type `Assoc` not found for `Trait`
--> $DIR/stranded-opaque.rs:8:31
|
LL | fn produce<T>() -> impl Trait<Assoc = impl Trait> {
| ^^^^^ associated type `Assoc` not found
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0220`.

View file

@ -107,17 +107,17 @@ help: ensure that all possible cases are being handled by adding a match arm wit
LL | match $s { $($t)+ => {}, u128::MAX => todo!() }
| ++++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `5_u128..=u128::MAX` not covered
error[E0004]: non-exhaustive patterns: `5_u128..` not covered
--> $DIR/exhaustiveness.rs:61:8
|
LL | m!(0u128, 0..=4);
| ^^^^^ pattern `5_u128..=u128::MAX` not covered
| ^^^^^ pattern `5_u128..` not covered
|
= note: the matched value is of type `u128`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
LL | match $s { $($t)+ => {}, 5_u128..=u128::MAX => todo!() }
| +++++++++++++++++++++++++++++++
LL | match $s { $($t)+ => {}, 5_u128.. => todo!() }
| +++++++++++++++++++++
error[E0004]: non-exhaustive patterns: `0_u128` not covered
--> $DIR/exhaustiveness.rs:62:8

View file

@ -0,0 +1,49 @@
//@ check-fail
//! Reject extensions behind references.
#![crate_type = "lib"]
#![feature(transmutability)]
mod assert {
use std::mem::{Assume, BikeshedIntrinsicFrom};
pub fn is_transmutable<Src, Dst>()
where
Dst: BikeshedIntrinsicFrom<
Src,
{
Assume {
alignment: true,
lifetimes: true,
safety: true,
validity: true,
}
},
>,
{
}
}
#[repr(C, packed)]
struct Packed<T>(T);
fn reject_extension() {
#[repr(C, align(2))]
struct Two(u8);
#[repr(C, align(4))]
struct Four(u8);
// These two types differ in the number of trailing padding bytes they have.
type Src = Packed<Two>;
type Dst = Packed<Four>;
const _: () = {
use std::mem::size_of;
assert!(size_of::<Src>() == 2);
assert!(size_of::<Dst>() == 4);
};
assert::is_transmutable::<&Src, &Dst>(); //~ ERROR cannot be safely transmuted
}

View file

@ -0,0 +1,25 @@
error[E0277]: `&Packed<Two>` cannot be safely transmuted into `&Packed<Four>`
--> $DIR/reject_extension.rs:48:37
|
LL | assert::is_transmutable::<&Src, &Dst>();
| ^^^^ The referent size of `&Packed<Two>` (2 bytes) is smaller than that of `&Packed<Four>` (4 bytes)
|
note: required by a bound in `is_transmutable`
--> $DIR/reject_extension.rs:13:14
|
LL | pub fn is_transmutable<Src, Dst>()
| --------------- required by a bound in this function
LL | where
LL | Dst: BikeshedIntrinsicFrom<
| ______________^
LL | | Src,
LL | | {
LL | | Assume {
... |
LL | | },
LL | | >,
| |_________^ required by this bound in `is_transmutable`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0277`.

View file

@ -1,8 +1,8 @@
error[E0277]: `Unit` cannot be safely transmuted into `u8`
error[E0277]: `&Unit` cannot be safely transmuted into `&u8`
--> $DIR/unit-to-u8.rs:22:52
|
LL | assert::is_maybe_transmutable::<&'static Unit, &'static u8>();
| ^^^^^^^^^^^ The size of `Unit` is smaller than the size of `u8`
| ^^^^^^^^^^^ The referent size of `&Unit` (0 bytes) is smaller than that of `&u8` (1 bytes)
|
note: required by a bound in `is_maybe_transmutable`
--> $DIR/unit-to-u8.rs:9:14

View file

@ -377,6 +377,25 @@ trigger_files = [
"compiler/rustc_middle/src/traits/solve"
]
[autolabel."PG-exploit-mitigations"]
trigger_files = [
"compiler/rustc_symbol_mangling/src/typeid",
"src/doc/rustc/src/exploit-mitigations.md",
"src/doc/unstable-book/src/compiler-flags/branch-protection.md",
"src/doc/unstable-book/src/compiler-flags/cf-protection.md",
"src/doc/unstable-book/src/compiler-flags/control-flow-guard.md",
"src/doc/unstable-book/src/compiler-flags/sanitizer.md",
"src/doc/unstable-book/src/language-features/cfg-sanitize.md",
"src/doc/unstable-book/src/language-features/cfi-encoding.md",
"src/doc/unstable-book/src/language-features/no-sanitize.md",
"tests/codegen/sanitizer",
"tests/codegen/split-lto-unit.rs",
"tests/codegen/stack-probes-inline.rs",
"tests/codegen/stack-protector.rs",
"tests/ui/sanitizer",
"tests/ui/stack-protector"
]
[notify-zulip."I-prioritize"]
zulip_stream = 245100 # #t-compiler/wg-prioritization/alerts
topic = "#{number} {title}"
@ -642,6 +661,51 @@ cc = ["@nnethercote"]
message = "Changes to the size of AST and/or HIR nodes."
cc = ["@nnethercote"]
[mentions."compiler/rustc_symbol_mangling/src/typeid"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/rustc/src/exploit-mitigations.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/compiler-flags/branch-protection.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/compiler-flags/cf-protection.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/compiler-flags/control-flow-guard.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/compiler-flags/sanitizer.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/language-features/cfg-sanitize.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/language-features/cfi-encoding.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."src/doc/unstable-book/src/language-features/no-sanitize.md"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/codegen/sanitizer"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/codegen/split-lto-unit.rs"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/codegen/stack-probes-inline.rs"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/codegen/stack-protector.rs"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/ui/sanitizer"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[mentions."tests/ui/stack-protector"]
cc = ["@rust-lang/project-exploit-mitigations", "@rcvalle"]
[assign]
warn_non_default_branch = true
contributing_url = "https://rustc-dev-guide.rust-lang.org/getting-started.html"
@ -783,6 +847,11 @@ project-stable-mir = [
"@ouz-a",
]
project-exploit-mitigations = [
"@cuviper",
"@rcvalle",
]
[assign.owners]
"/.github/workflows" = ["infra-ci"]
"/Cargo.lock" = ["@Mark-Simulacrum"]