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

Remove implicit total orderings #107982

Closed
Closed
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
3 changes: 1 addition & 2 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,10 +776,9 @@ pub enum PatKind {
MacCall(P<MacCall>),
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)]
#[derive(HashStable_Generic, Encodable, Decodable)]
pub enum Mutability {
// N.B. Order is deliberate, so that Not < Mut
Copy link
Contributor

Choose a reason for hiding this comment

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

Mutability is perhaps the one case where keeping the order is useful and sensible.

Not,
Mut,
}
Expand Down
13 changes: 8 additions & 5 deletions compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,19 +403,22 @@ fn try_extract_error_from_region_constraints<'tcx>(
mut region_var_origin: impl FnMut(RegionVid) -> RegionVariableOrigin,
mut universe_of_region: impl FnMut(RegionVid) -> UniverseIndex,
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
let (sub_region, cause) =
region_constraints.constraints.iter().find_map(|(constraint, cause)| {
let (_, _, sub_region, cause) = region_constraints
.constraints
.iter()
.filter_map(|(constraint, cause)| {
match *constraint {
Constraint::RegSubReg(sub, sup) if sup == placeholder_region && sup != sub => {
Some((sub, cause.clone()))
Some((1u8, None, sub, cause.clone()))
}
// FIXME: Should this check the universe of the var?
Constraint::VarSubReg(vid, sup) if sup == placeholder_region => {
Some((infcx.tcx.mk_region(ty::ReVar(vid)), cause.clone()))
Some((0u8, Some(vid), infcx.tcx.mk_region(ty::ReVar(vid)), cause.clone()))
}
_ => None,
}
})?;
})
.min_by_key(|(discr, vid, ..)| (*discr, *vid))?;
Copy link
Contributor

Choose a reason for hiding this comment

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

Why doesn't find_map work any more?


debug!(?sub_region, "cause = {:#?}", cause);
let error = match (error_region, *sub_region) {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {

// Check if we can use one of the "nice region errors".
if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
debug!("report_region_error: nice report");
let infer_err = self.infcx.err_ctxt();
let nice = NiceRegionError::new_from_span(&infer_err, cause.span, o, f);
if let Some(diag) = nice.try_report_from_nll() {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/region_infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2173,7 +2173,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
// is in the same SCC or something. In that case, find what
// appears to be the most interesting point to report to the
// user via an even more ad-hoc guess.
categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
categorized_path.sort_by_key(|p| p.category.cmp_discr());
debug!("sorted_path={:#?}", categorized_path);

(categorized_path.remove(0), extra_info)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/coherence/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUn
let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>,
mt_b: ty::TypeAndMut<'tcx>,
mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| {
if mt_a.mutbl < mt_b.mutbl {
if let (hir::Mutability::Not, hir::Mutability::Mut) = (mt_a.mutbl, mt_b.mutbl) {
infcx
.err_ctxt()
.report_mismatched_types(
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/outlives/utils.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use rustc_data_structures::fx::FxHashMap;
use rustc_infer::infer::outlives::components::{push_outlives_components, Component};
use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
use rustc_middle::ty::{self, Region, Ty, TyCtxt};
use rustc_span::Span;
use smallvec::smallvec;
use std::collections::BTreeMap;

/// Tracks the `T: 'a` or `'a: 'a` predicates that we have inferred
/// must be added to the struct header.
pub(crate) type RequiredPredicates<'tcx> =
BTreeMap<ty::OutlivesPredicate<GenericArg<'tcx>, ty::Region<'tcx>>, Span>;
FxHashMap<ty::OutlivesPredicate<GenericArg<'tcx>, ty::Region<'tcx>>, Span>;

/// Given a requirement `T: 'a` or `'b: 'a`, deduce the
/// outlives_component and add it to `required_predicates`
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_hir_typeck/src/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,5 +575,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}

fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max()
arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max_by_key(|m| match m {
hir::Mutability::Not => 0u8,
hir::Mutability::Mut => 1,
})
}
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
m_cast: ty::TypeAndMut<'tcx>,
) -> Result<CastKind, CastError> {
// array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
if m_expr.mutbl >= m_cast.mutbl {
if m_expr.mutbl == m_cast.mutbl || m_expr.mutbl == hir::Mutability::Mut {
if let ty::Array(ety, _) = m_expr.ty.kind() {
// Due to the limitations of LLVM global constants,
// region pointers end up pointing at copies of
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,11 @@ fn coerce_mutbls<'tcx>(
from_mutbl: hir::Mutability,
to_mutbl: hir::Mutability,
) -> RelateResult<'tcx, ()> {
if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
if from_mutbl == to_mutbl || from_mutbl == hir::Mutability::Mut {
Ok(())
} else {
Err(TypeError::Mutability)
}
}

/// Do not require any adjustments, i.e. coerce `x -> x`.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1420,7 +1420,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(
sp,
format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
if mutbl_b == mutbl_a || mutbl_b == hir::Mutability::Not { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
)
});

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1936,7 +1936,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
_ => None,
})
.collect();
preds.sort_by_key(|pred| (pred.def_id(), pred.self_ty()));
preds.sort_by_key(|pred| pred.def_id());
let def_ids = preds
.iter()
.filter_map(|pred| match pred.self_ty().kind() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> {
pub(super) fn try_report_placeholder_conflict(
&self,
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
debug!(?self.error, "try_report_placeholder_conflict");
match &self.error {
///////////////////////////////////////////////////////////////////////////
// NB. The ordering of cases in this match is very
Expand Down
10 changes: 8 additions & 2 deletions compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,14 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
// later use this to expand across vids.
let mut constraints = IndexVec::from_elem_n(Vec::new(), var_values.values.len());
// Tracks the changed region vids.
let mut changes = Vec::new();
for constraint in self.data.constraints.keys() {
let mut changes = vec![];
let mut input_constraints: Vec<_> = self.data.constraints.keys().collect();
input_constraints.sort_by_key(|c| match c {
Constraint::VarSubVar(..) => 0u8,
Constraint::RegSubVar(..) => 1,
Constraint::VarSubReg(..) | Constraint::RegSubReg(..) => 2,
Copy link
Contributor

Choose a reason for hiding this comment

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

This definitely needs a comment.

});
for constraint in input_constraints {
match *constraint {
Constraint::RegSubVar(a_region, b_vid) => {
let b_data = var_values.value_mut(b_vid);
Expand Down
9 changes: 5 additions & 4 deletions compiler/rustc_infer/src/infer/region_constraints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use super::{
InferCtxtUndoLogs, MiscVariable, RegionVariableOrigin, Rollback, Snapshot, SubregionOrigin,
};

use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::fx::FxIndexSet;
use rustc_data_structures::intern::Interned;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::undo_log::UndoLogs;
Expand All @@ -20,7 +22,6 @@ use rustc_middle::ty::{ReLateBound, ReVar};
use rustc_middle::ty::{Region, RegionVid};
use rustc_span::Span;

use std::collections::BTreeMap;
use std::ops::Range;
use std::{cmp, fmt, mem};

Expand Down Expand Up @@ -90,7 +91,7 @@ pub type VarInfos = IndexVec<RegionVid, RegionVariableInfo>;
pub struct RegionConstraintData<'tcx> {
/// Constraints of the form `A <= B`, where either `A` or `B` can
/// be a region variable (or neither, as it happens).
pub constraints: BTreeMap<Constraint<'tcx>, SubregionOrigin<'tcx>>,
pub constraints: FxIndexMap<Constraint<'tcx>, SubregionOrigin<'tcx>>,

/// Constraints of the form `R0 member of [R1, ..., Rn]`, meaning that
/// `R0` must be equal to one of the regions `R1..Rn`. These occur
Expand Down Expand Up @@ -127,7 +128,7 @@ pub struct RegionConstraintData<'tcx> {
}

/// Represents a constraint that influences the inference process.
#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Constraint<'tcx> {
/// A region variable is a subregion of another.
VarSubVar(RegionVid, RegionVid),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1200,7 +1200,7 @@ impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
{
if from_mutbl < to_mutbl {
if let (hir::Mutability::Not, hir::Mutability::Mut) = (from_mutbl, to_mutbl) {
cx.emit_spanned_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2580,7 +2580,7 @@ impl<'tcx> ConstantKind<'tcx> {
}

/// An unevaluated (potentially generic) constant used in MIR.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Lift)]
#[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
pub struct UnevaluatedConst<'tcx> {
pub def: ty::WithOptConstParam<DefId>,
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_middle/src/mir/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use std::fmt::{self, Debug};

use super::{Field, SourceInfo};

mod order;

#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
pub enum UnsafetyViolationKind {
/// Unsafe operation outside `unsafe`.
Expand Down Expand Up @@ -336,7 +338,7 @@ rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
/// order of the category, thereby influencing diagnostic output.
///
/// See also `rustc_const_eval::borrow_check::constraints`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[derive(TyEncodable, TyDecodable, HashStable, Lift, TypeVisitable, TypeFoldable)]
pub enum ConstraintCategory<'tcx> {
Return(ReturnConstraint),
Expand Down
27 changes: 27 additions & 0 deletions compiler/rustc_middle/src/mir/query/order.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use super::ConstraintCategory;

impl<'tcx> ConstraintCategory<'tcx> {
Copy link
Contributor

Choose a reason for hiding this comment

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

This does not need to be in a separate file.

pub fn cmp_discr(&self) -> u8 {
use ConstraintCategory::*;
match self {
Return(_) => 0,
Yield => 1,
UseAsConst => 2,
UseAsStatic => 3,
TypeAnnotation => 4,
Cast => 5,
ClosureBounds => 6,
CallArgument(_) => 7,
CopyBound => 8,
SizedBound => 9,
Assignment => 10,
Usage => 11,
OpaqueType => 12,
ClosureUpvar(_) => 13,
Predicate(_) => 14,
Boring => 15,
BoringNoLocation => 16,
Internal => 17,
}
}
}
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub use kind::*;
pub use valtree::*;

/// Use this rather than `ConstData, whenever possible.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
#[rustc_pass_by_value]
pub struct Const<'tcx>(pub(super) Interned<'tcx, ConstData<'tcx>>);

Expand All @@ -29,7 +29,7 @@ impl<'tcx> fmt::Debug for Const<'tcx> {
}

/// Typed constant value.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, TyEncodable, TyDecodable)]
#[derive(PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
pub struct ConstData<'tcx> {
pub ty: Ty<'tcx>,
pub kind: ConstKind<'tcx>,
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_middle/src/ty/consts/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_target::abi::Size;
use super::ScalarInt;

/// An unevaluated (potentially generic) constant used in the type-system.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Lift)]
#[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
pub struct UnevaluatedConst<'tcx> {
pub def: ty::WithOptConstParam<DefId>,
Expand Down Expand Up @@ -45,7 +45,7 @@ impl<'tcx> UnevaluatedConst<'tcx> {
}

/// Represents a constant in Rust.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable)]
#[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
#[derive(derive_more::From)]
pub enum ConstKind<'tcx> {
Expand Down Expand Up @@ -83,7 +83,7 @@ impl<'tcx> From<ty::ConstVid<'tcx>> for ConstKind<'tcx> {
}
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[derive(HashStable, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
pub enum Expr<'tcx> {
Binop(mir::BinOp, Const<'tcx>, Const<'tcx>),
Expand Down Expand Up @@ -131,7 +131,7 @@ impl<'tcx> ConstKind<'tcx> {
}

/// An inference variable for a const, for use in const generics.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash)]
pub enum InferConst<'tcx> {
/// Infer the value of the const.
Var(ty::ConstVid<'tcx>),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub struct Instance<'tcx> {
pub substs: SubstsRef<'tcx>,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
pub enum InstanceDef<'tcx> {
/// A user-defined callable item.
Expand Down
27 changes: 0 additions & 27 deletions compiler/rustc_middle/src/ty/list.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::arena::Arena;
use rustc_serialize::{Encodable, Encoder};
use std::alloc::Layout;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter;
Expand Down Expand Up @@ -137,32 +136,6 @@ impl<T: PartialEq> PartialEq for List<T> {

impl<T: Eq> Eq for List<T> {}

impl<T> Ord for List<T>
where
T: Ord,
{
fn cmp(&self, other: &List<T>) -> Ordering {
// Pointer equality implies list equality (due to the unique contents
// assumption), but the contents must be compared otherwise.
if self == other { Ordering::Equal } else { <[T] as Ord>::cmp(&**self, &**other) }
}
}

impl<T> PartialOrd for List<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> {
// Pointer equality implies list equality (due to the unique contents
// assumption), but the contents must be compared otherwise.
if self == other {
Some(Ordering::Equal)
} else {
<[T] as PartialOrd>::partial_cmp(&**self, &**other)
}
}
}

impl<T> Hash for List<T> {
#[inline]
fn hash<H: Hasher>(&self, s: &mut H) {
Expand Down
Loading