diff --git a/Cargo.lock b/Cargo.lock index 5f35ce252b7..063ee6b9850 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4819,7 +4819,6 @@ version = "0.0.0" dependencies = [ "bitflags", "blake3", - "derive-where", "indexmap", "itoa", "md-5", diff --git a/compiler/rustc_attr_parsing/src/attributes/repr.rs b/compiler/rustc_attr_parsing/src/attributes/repr.rs index 6115ed207d9..bc4f9d20545 100644 --- a/compiler/rustc_attr_parsing/src/attributes/repr.rs +++ b/compiler/rustc_attr_parsing/src/attributes/repr.rs @@ -4,6 +4,7 @@ use rustc_attr_ir::IntType::{SignedInt, UnsignedInt}; use rustc_attr_ir::ReprAttr; use rustc_feature::AttributeStability; use rustc_session::diagnostics::feature_err; +use rustc_span::OrdSpan; use super::prelude::*; use crate::diagnostics; @@ -272,7 +273,7 @@ fn parse_alignment(node: &LitKind, cx: &AcceptContext<'_, '_>) -> Result); +pub(crate) struct RustcAlignParser(Option<(Align, OrdSpan)>); impl RustcAlignParser { const PATH: &[Symbol] = &[sym::rustc_align]; @@ -293,7 +294,7 @@ impl RustcAlignParser { }; match parse_alignment(&lit.kind, cx) { - Ok(literal) => self.0 = Ord::max(self.0, Some((literal, cx.attr_span))), + Ok(literal) => self.0 = Ord::max(self.0, Some((literal, OrdSpan(cx.attr_span)))), Err(message) => { cx.emit_err(diagnostics::InvalidAlignmentValue { span: lit.span, @@ -318,7 +319,7 @@ impl AttributeParser for RustcAlignParser { fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { let (align, span) = self.0?; - Some(AttributeKind::RustcAlign { align, span }) + Some(AttributeKind::RustcAlign { align, span: span.0 }) } } @@ -342,6 +343,6 @@ impl AttributeParser for RustcAlignStaticParser { fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { let (align, span) = self.0.0?; - Some(AttributeKind::RustcAlign { align, span }) + Some(AttributeKind::RustcAlign { align, span: span.0 }) } } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index f4b2ceb8506..132f074f9e0 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -893,7 +893,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { .errors .iter() .map(|error| error.span) - .any(|sp| span < sp && !sp.contains(span)) + .any(|sp| span.lo_hi() < sp.lo_hi() && !sp.contains(span)) }) { show_assign_sugg = true; if all_init_spans.iter().any(|init_span| !init_span.contains(span)) @@ -929,7 +929,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { let mut shown = false; let mut shown_condition_value = false; for error in visitor.errors { - if error.span < span && !error.span.overlaps(span) { + if error.span.lo_hi() < span.lo_hi() && !error.span.overlaps(span) { // When we have a case like `match-cfg-fake-edges.rs`, we don't want to mention // match arms coming after the primary span because they aren't relevant: // ``` @@ -950,7 +950,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { } if !shown { for sp in &reachable_spans { - if *sp < span && !sp.overlaps(span) { + if sp.lo_hi() < span.lo_hi() && !sp.overlaps(span) { err.span_label(*sp, "binding initialized here in some conditions"); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index f431374de37..7537e2f9f14 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -419,8 +419,8 @@ impl<'tcx> BorrowExplanation<'tcx> { _ => None, }) .collect::>(); - preds.sort(); - preds.dedup(); + preds.sort_by_key(|span| span.lo_hi()); + preds.dedup_by_key(|span| span.lo_hi()); if !preds.is_empty() { let s = if preds.len() == 1 { "" } else { "s" }; err.span_note( diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index c8abc2689ff..523db527d0c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -123,7 +123,7 @@ impl<'diag, 'tcx> BorrowckDiagnosticsBuffer<'diag, 'tcx> { } if !self.buffered_diags.is_empty() { - self.buffered_diags.sort_by_key(|(sort_span, _)| *sort_span); + self.buffered_diags.sort_by_key(|(sort_span, _)| sort_span.lo_hi()); for (_, diag) in self.buffered_diags.drain(..) { diag.emit(); } diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index aa62d6aaa07..4d654104551 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -1206,8 +1206,8 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { suggestions.push((binding_span.shrink_to_lo(), msg, "ref ".to_string())); } } - suggestions.sort_unstable_by_key(|&(span, _, _)| span); - suggestions.dedup_by_key(|&mut (span, _, _)| span); + suggestions.sort_unstable_by_key(|&(span, _, _)| span.lo_hi()); + suggestions.dedup_by_key(|&mut (span, _, _)| span.lo_hi()); for (span, msg, suggestion) in suggestions { err.span_suggestion_verbose(span, msg, suggestion, Applicability::MachineApplicable); } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index a886187783b..b3032662fb3 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -318,7 +318,7 @@ impl<'tcx> MirTypeckRegionConstraints<'tcx> { /// required to hold. Normally, this is at a particular point which /// created the obligation, but for constraints that the user gave, we /// want the constraint to hold at all points. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum Locations { /// Indicates that a type constraint should always be true. This /// is particularly important in the new borrowck analysis for diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index bedcfe998b6..cb3b43aafa1 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -101,7 +101,7 @@ impl MultiSpan { } pub fn from_spans(mut vec: Vec) -> MultiSpan { - vec.sort(); + vec.sort_by_key(|span| span.lo_hi()); MultiSpan { primary_spans: vec, span_labels: vec![], span_context: vec![] } } diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 9688f99abfe..3f879b5f2ef 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -972,7 +972,7 @@ impl<'a> Diag<'a> { .map(|(span, snippet)| SubstitutionPart { snippet, span }) .collect::>(); - parts.sort_unstable_by_key(|part| part.span); + parts.sort_unstable_by_key(|part| part.span.lo_hi()); assert!(!parts.is_empty()); debug_assert_eq!( diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 8f693221b0f..66605e9de6e 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -240,7 +240,7 @@ fn bad_placeholder<'cx, 'tcx>( ) -> Diag<'cx> { let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") }; - spans.sort(); + spans.sort_by_key(|span| span.lo_hi()); cx.dcx().create_err(diagnostics::PlaceholderNotAllowedItemSignatures { spans, kind }) } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index f2cf4743d76..de22c157ee5 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::{ }; use rustc_session::diagnostics::feature_err; use rustc_span::edit_distance::find_best_match_for_name; -use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, bug, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, Ident, OrdSpan, Span, Symbol, bug, kw, sym}; use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility; use rustc_trait_selection::traits::{ FulfillmentError, dyn_compatibility_violations_for_assoc_item, @@ -943,22 +943,22 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return err.emit_err(); } - let mut bound_spans: SortedMap> = Default::default(); + let mut bound_spans: SortedMap> = Default::default(); let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| { let msg = format!("`{}`", if obligation.len() > 50 { quiet } else { obligation }); match self_ty.kind() { // Point at the type that couldn't satisfy the bound. - ty::Adt(def, _) => { - bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg) - } + ty::Adt(def, _) => bound_spans + .get_mut_or_insert_default(OrdSpan(tcx.def_span(def.did()))) + .push(msg), // Point at the trait object that couldn't satisfy the bound. ty::Dynamic(preds, _) => { for pred in preds.iter() { match pred.skip_binder() { ty::ExistentialPredicate::Trait(tr) => { bound_spans - .get_mut_or_insert_default(tcx.def_span(tr.def_id)) + .get_mut_or_insert_default(OrdSpan(tcx.def_span(tr.def_id))) .push(msg.clone()); } ty::ExistentialPredicate::Projection(_) @@ -969,7 +969,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // Point at the closure that couldn't satisfy the bound. ty::Closure(def_id, _) => { bound_spans - .get_mut_or_insert_default(tcx.def_span(*def_id)) + .get_mut_or_insert_default(OrdSpan(tcx.def_span(*def_id))) .push(format!("`{quiet}`")); } _ => {} @@ -1034,7 +1034,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); for (span, mut bounds) in bound_spans { - if !tcx.sess.source_map().is_span_accessible(span) { + if !tcx.sess.source_map().is_span_accessible(span.0) { continue; } bounds.sort(); @@ -1045,7 +1045,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { [bounds @ .., last] => format!("doesn't satisfy {} or {last}", bounds.join(", ")), [] => unreachable!(), }; - err.span_label(span, msg); + err.span_label(span.0, msg); } add_def_label(&mut err); err.emit_err() @@ -1315,7 +1315,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); } } - suggestions.sort_by_key(|&(span, _)| span); + suggestions.sort_by_key(|&(span, _)| span.lo_hi()); // There are cases where one bound points to a span within another bound's span, like when // you have code like the following (#115019), so we skip providing a suggestion in those // cases to avoid having a malformed suggestion. diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index 3ce6c341761..6b1354002c9 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -10,7 +10,7 @@ use rustc_hir::{Destination, Node, find_attr}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::hygiene::DesugaringKind; -use rustc_span::{BytePos, Span, span_bug}; +use rustc_span::{BytePos, OrdSpan, Span, span_bug}; use crate::diagnostics::{ BreakInsideClosure, BreakInsideCoroutine, BreakNonLoop, ConstContinueBadLabel, @@ -79,7 +79,7 @@ struct CheckLoopVisitor<'tcx> { // such as adding a label for an `if`. // e.g. `if 'foo: {}` would be incorrect. cx_stack: Vec, - block_breaks: BTreeMap, + block_breaks: BTreeMap, } pub(crate) fn check<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'tcx hir::Body<'tcx>) { @@ -377,12 +377,13 @@ impl<'hir> CheckLoopVisitor<'hir> { UnlabeledBlock { label_span, wrap_end } if br_cx_kind == BreakContextKind::Break && label_span.eq_ctxt(break_span) => { - let block = self.block_breaks.entry(label_span).or_insert_with(|| BlockInfo { - name: br_cx_kind.to_string(), - spans: vec![], - suggs: vec![], - wrap_end, - }); + let block = + self.block_breaks.entry(OrdSpan(label_span)).or_insert_with(|| BlockInfo { + name: br_cx_kind.to_string(), + spans: vec![], + suggs: vec![], + wrap_end, + }); block.spans.push(span); block.suggs.push(break_span); } @@ -423,7 +424,7 @@ impl<'hir> CheckLoopVisitor<'hir> { name: &block.name, is_break: true, suggestion: Some(OutsideLoopSuggestion { - block_span: *s, + block_span: s.0, break_spans: block.suggs.clone(), block_prefix: if block.wrap_end.is_some() { "{ 'block: " } else { "'block: " }, wrap_end: block.wrap_end, diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index e074ebf01bd..615b755c398 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -33,7 +33,7 @@ use rustc_middle::ty::print::{ use rustc_middle::ty::{self, GenericArgKind, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::DefIdSet; use rustc_span::{ - DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, Ident, MacroKind, Span, Symbol, bug, + DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, Ident, MacroKind, OrdSpan, Span, Symbol, bug, edit_distance, kw, sym, }; use rustc_trait_selection::error_reporting::traits::DefIdOrName; @@ -890,12 +890,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { source: SelfSource<'tcx>, unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>, static_candidates: &[CandidateSource], - ) -> Result<(bool, bool, bool, bool, SortedMap>), ()> { + ) -> Result<(bool, bool, bool, bool, SortedMap>), ()> { let mut restrict_type_params = false; let mut suggested_derive = false; let mut unsatisfied_bounds = false; let mut custom_span_label = !static_candidates.is_empty(); - let mut bound_spans: SortedMap> = Default::default(); + let mut bound_spans: SortedMap> = Default::default(); let tcx = self.tcx; if item_ident.name == sym::count && self.is_slice_ty(rcvr_ty, span) { @@ -1137,7 +1137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, - bound_spans: SortedMap>, + bound_spans: SortedMap>, unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>, ) { let mut ty_span = match rcvr_ty.kind() { @@ -1179,6 +1179,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None }; for (span, mut bounds) in bound_spans { + let span = span.0; if !self.tcx.sess.source_map().is_span_accessible(span) { continue; } @@ -1715,7 +1716,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggested_derive: &mut bool, unsatisfied_bounds: &mut bool, custom_span_label: &mut bool, - bound_spans: &mut SortedMap>, + bound_spans: &mut SortedMap>, ) { let tcx = self.tcx; let rcvr_ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path()); @@ -1800,16 +1801,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let msg = format!("`{}`", if obligation.len() > 50 { quiet } else { obligation }); match self_ty.kind() { // Point at the type that couldn't satisfy the bound. - ty::Adt(def, _) => { - bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg) - } + ty::Adt(def, _) => bound_spans + .get_mut_or_insert_default(OrdSpan(tcx.def_span(def.did()))) + .push(msg), // Point at the trait object that couldn't satisfy the bound. ty::Dynamic(preds, _) => { for pred in preds.iter() { match pred.skip_binder() { ty::ExistentialPredicate::Trait(tr) => { bound_spans - .get_mut_or_insert_default(tcx.def_span(tr.def_id)) + .get_mut_or_insert_default(OrdSpan(tcx.def_span(tr.def_id))) .push(msg.clone()); } ty::ExistentialPredicate::Projection(_) @@ -1820,7 +1821,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Point at the closure that couldn't satisfy the bound. ty::Closure(def_id, _) => { bound_spans - .get_mut_or_insert_default(tcx.def_span(*def_id)) + .get_mut_or_insert_default(OrdSpan(tcx.def_span(*def_id))) .push(format!("`{quiet}`")); } _ => {} @@ -2030,7 +2031,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect(); - spanned_predicates.sort_by_key(|(span, _)| *span); + spanned_predicates.sort_by_key(|(span, _)| span.lo_hi()); for (_, (primary_spans, span_labels, predicates)) in spanned_predicates { let mut tracker = TraitBoundDuplicateTracker::new(); let mut all_trait_bounds_for_rcvr = true; @@ -3572,7 +3573,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, trait_pred: ty::TraitClause<'tcx>, adt: ty::AdtDef<'tcx>, - ) -> Option> { + ) -> Option> { let diagnostic_name = self.tcx.get_diagnostic_name(trait_pred.def_id())?; let can_derive = match diagnostic_name { @@ -3610,7 +3611,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut derives = Vec::new(); let self_name = self_ty.to_string(); - let self_span = self.tcx.def_span(adt.did()); + let self_span = OrdSpan(self.tcx.def_span(adt.did())); for super_trait in supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref)) { if let Some(parent_diagnostic_name) = self.tcx.get_diagnostic_name(super_trait.def_id()) @@ -3628,7 +3629,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>, - ) -> Vec<(String, Span, Symbol)> { + ) -> Vec<(String, OrdSpan, Symbol)> { let mut derives = Vec::new(); let mut traits = Vec::new(); for (pred, _, _) in unsatisfied_predicates { @@ -3692,7 +3693,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } } - derives_grouped.push((self_name, self_span, trait_name.to_string())); + derives_grouped.push((self_name, self_span.0, trait_name.to_string())); } for (self_name, self_span, traits) in &derives_grouped { diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 5ae65ad26f9..c19c25228fb 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -499,7 +499,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } if !errors_buffer.is_empty() { - errors_buffer.sort_by_key(|diag| diag.span.primary_span()); + errors_buffer.sort_by_key(|diag| diag.span.primary_span().map(Span::lo_hi)); for err in errors_buffer { err.emit(); } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 610eb5fd099..f21888b1de5 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -434,7 +434,7 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing. sess.psess.bad_unicode_identifiers.with_lock(|identifiers| { for (ident, mut spans) in identifiers.drain(..) { - spans.sort(); + spans.sort_by_key(|span| span.lo_hi()); if ident == sym::ferris { enum FerrisFix { SnakeCase, diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index bba993ee3f0..0688dcf2fca 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2163,8 +2163,8 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { // Due to macros, there might be several predicates with the same span // and we only want to suggest removing them once. - lint_spans.sort_unstable(); - lint_spans.dedup(); + lint_spans.sort_unstable_by_key(|span| span.lo_hi()); + lint_spans.dedup_by_key(|span| span.lo_hi()); cx.emit_span_lint( EXPLICIT_OUTLIVES_REQUIREMENTS, diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 416b8717a7d..588a9e1130f 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -2,7 +2,7 @@ use rustc_ast as ast; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::UnordMap; use rustc_lint_defs::{declare_lint, declare_lint_pass}; -use rustc_span::Symbol; +use rustc_span::{OrdSpan, Symbol}; use unicode_security::general_security_profile::IdentifierType; use crate::diagnostics::{ @@ -180,7 +180,7 @@ impl EarlyLintPass for NonAsciiIdents { // We will soon sort, so the initial order does not matter. #[allow(rustc::potential_query_instability)] let mut symbols: Vec<_> = symbols.iter().collect(); - symbols.sort_by_key(|k| k.1); + symbols.sort_by_key(|k| k.1.lo_hi()); for &(ref symbol, &sp) in symbols.iter() { let symbol_str = symbol.as_str(); if symbol_str.is_ascii() { @@ -342,7 +342,7 @@ impl EarlyLintPass for NonAsciiIdents { .collect::>(); // we're sorting the output here. - let mut lint_reports: BTreeMap<(Span, Vec), AugmentedScriptSet> = + let mut lint_reports: BTreeMap<(OrdSpan, Vec), AugmentedScriptSet> = BTreeMap::new(); // The end result is put in `lint_reports` which is sorted. @@ -368,7 +368,7 @@ impl EarlyLintPass for NonAsciiIdents { // We sort primitive chars here and can use unstable sort ch_list.sort_unstable(); ch_list.dedup(); - lint_reports.insert((sp, ch_list), augment_script_set); + lint_reports.insert((OrdSpan(sp), ch_list), augment_script_set); } for ((sp, ch_list), script_set) in lint_reports { @@ -382,7 +382,7 @@ impl EarlyLintPass for NonAsciiIdents { } cx.emit_span_lint( MIXED_SCRIPT_CONFUSABLES, - sp, + sp.0, MixedScriptConfusables { set: script_set.to_string(), includes }, ); } diff --git a/compiler/rustc_middle/src/mono.rs b/compiler/rustc_middle/src/mono.rs index a54ca4faf81..cf567fa1c89 100644 --- a/compiler/rustc_middle/src/mono.rs +++ b/compiler/rustc_middle/src/mono.rs @@ -15,7 +15,7 @@ use rustc_hir::ItemId; use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE}; use rustc_macros::{StableHash, TyDecodable, TyEncodable}; use rustc_session::config::OptLevel; -use rustc_span::{Span, Symbol}; +use rustc_span::{OrdSpan, Span, Symbol}; use rustc_target::spec::SymbolVisibility; use tracing::debug; @@ -528,7 +528,7 @@ impl<'tcx> CodegenUnit<'tcx> { // The codegen tests rely on items being process in the same order as // they appear in the file, so for local items, we sort by span first #[derive(PartialEq, Eq, PartialOrd, Ord)] - struct ItemSortKey<'tcx>(Option, SymbolName<'tcx>); + struct ItemSortKey<'tcx>(Option, SymbolName<'tcx>); // We only want to take HirIds of user-defines instances into account. // The others don't matter for the codegen tests and can even make item @@ -560,9 +560,9 @@ impl<'tcx> CodegenUnit<'tcx> { } fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> { ItemSortKey( - local_item_id(item) - .map(|def_id| tcx.def_span(def_id).find_ancestor_not_from_macro()) - .flatten(), + local_item_id(item).and_then(|def_id| { + tcx.def_span(def_id).find_ancestor_not_from_macro().map(OrdSpan) + }), item.symbol_name(tcx), ) } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 5520b059f56..828a1ee79a0 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -21,7 +21,7 @@ use rustc_macros::{ Decodable, Encodable, StableHash, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, }; use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId}; -use rustc_span::{DUMMY_SP, Span, Symbol, sym}; +use rustc_span::{DUMMY_SP, OrdSpan, Span, Symbol, sym}; use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; @@ -863,15 +863,15 @@ impl DynCompatibilityViolation { | Self::SupertraitConst(_) => DynCompatibilityViolationSolution::None, Self::Method( name, - MethodViolation::StaticMethod(Some((add_self_sugg, make_sized_sugg))), + MethodViolation::StaticMethod(Some(((add_s, add_sp), (make_s, make_sp)))), _, ) => DynCompatibilityViolationSolution::AddSelfOrMakeSized { name: *name, - add_self_sugg: add_self_sugg.clone(), - make_sized_sugg: make_sized_sugg.clone(), + add_self_sugg: (add_s.clone(), OrdSpan(*add_sp)), + make_sized_sugg: (make_s.clone(), OrdSpan(*make_sp)), }, Self::Method(name, MethodViolation::UndispatchableReceiver(Some((span, lt))), _) => { - DynCompatibilityViolationSolution::ChangeToRefSelf(*name, *span, *lt) + DynCompatibilityViolationSolution::ChangeToRefSelf(*name, OrdSpan(*span), *lt) } Self::Method(name, ..) | Self::AssocConst(name, ..) | Self::GenericAssocTy(name, _) => { DynCompatibilityViolationSolution::MoveToAnotherTrait(*name) @@ -901,15 +901,15 @@ impl DynCompatibilityViolation { } } -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum DynCompatibilityViolationSolution { None, AddSelfOrMakeSized { name: Symbol, - add_self_sugg: (String, Span), - make_sized_sugg: (String, Span), + add_self_sugg: (String, OrdSpan), + make_sized_sugg: (String, OrdSpan), }, - ChangeToRefSelf(Symbol, Span, Symbol), + ChangeToRefSelf(Symbol, OrdSpan, Symbol), MoveToAnotherTrait(Symbol), } @@ -923,7 +923,7 @@ impl DynCompatibilityViolationSolution { make_sized_sugg, } => { err.span_suggestion_verbose( - add_self_sugg.1, + add_self_sugg.1.0, format!( "consider turning `{name}` into a method by giving it a `&self` argument, \ so that it is accessible through the trait object's vtable", @@ -932,7 +932,7 @@ impl DynCompatibilityViolationSolution { Applicability::MaybeIncorrect, ); err.span_suggestion_verbose( - make_sized_sugg.1, + make_sized_sugg.1.0, format!( "alternatively, consider constraining `{name}` so it is explicitly marked \ as not applying to trait objects", @@ -943,7 +943,7 @@ impl DynCompatibilityViolationSolution { } DynCompatibilityViolationSolution::ChangeToRefSelf(name, span, lt) => { err.span_suggestion_verbose( - span, + span.0, format!("consider changing method `{name}`'s `self` parameter to be `&self`"), format!("&{lt}{}self", if lt != sym::empty { " " } else { "" }), Applicability::MachineApplicable, diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index e8cc5dc0edf..eebdabd4e73 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -1104,7 +1104,7 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { // Visit the body. visitor.visit_expr(&thir[expr]); - warnings.sort_by_key(|w| w.block_span); + warnings.sort_by_key(|w| w.block_span.lo_hi()); for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings { let block_span = tcx.sess.source_map().guess_head_span(block_span); tcx.emit_node_span_lint( diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 381ebdcc150..8fa5a10a910 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -412,7 +412,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { { let mut redundant_subpats = redundant_subpats.clone(); // Emit lints in the order in which they occur in the file. - redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span); + redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span.lo_hi()); for (pat, explanation) in redundant_subpats { report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None) } diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index 9627f8988f2..c90d230a19f 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -79,7 +79,7 @@ fn check_recursion<'tcx>( return; } - vis.reachable_recursive_calls.sort(); + vis.reachable_recursive_calls.sort_by_key(|span| span.lo_hi()); let sp = tcx.def_span(def_id); let hir_id = tcx.local_def_id_to_hir_id(def_id); diff --git a/compiler/rustc_monomorphize/src/graph_checks/statics.rs b/compiler/rustc_monomorphize/src/graph_checks/statics.rs index 4a6416843fd..e954077f279 100644 --- a/compiler/rustc_monomorphize/src/graph_checks/statics.rs +++ b/compiler/rustc_monomorphize/src/graph_checks/statics.rs @@ -100,7 +100,7 @@ pub(super) fn check_static_initializers_are_acyclic<'tcx, 'a, 'b>( // Emit errors for all cycles for nodes in nodes_of_sccs.iter_mut().filter(|nodes| is_cyclic(nodes)) { // We sort the nodes by their Span to have consistent error line numbers - nodes.sort_by_key(|node| tcx.def_span(statics[node.index()])); + nodes.sort_by_key(|node| tcx.def_span(statics[node.index()]).lo_hi()); let head_def = statics[nodes[0].index()]; let head_span = tcx.def_span(head_def); diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4926ec9872d..9d05a4d7ca8 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1210,7 +1210,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { if !reprs.is_empty() { let sorted_reprs = { let mut to_sort = reprs.to_owned(); - to_sort.sort_unstable(); + to_sort.sort_unstable_by_key(|(attr, span)| (*attr, span.lo_hi())); to_sort }; diff --git a/compiler/rustc_query_impl/src/handle_cycle_error.rs b/compiler/rustc_query_impl/src/handle_cycle_error.rs index 83e95b91955..3f70fc2a6b8 100644 --- a/compiler/rustc_query_impl/src/handle_cycle_error.rs +++ b/compiler/rustc_query_impl/src/handle_cycle_error.rs @@ -223,7 +223,7 @@ fn recursive_type_error( let start_index = item_and_field_ids .iter() .enumerate() - .min_by_key(|&(_, &(id, _))| tcx.def_span(id)) + .min_by_key(|&(_, &(id, _))| tcx.def_span(id).lo_hi()) .unwrap() .0; item_and_field_ids.rotate_left(start_index); diff --git a/compiler/rustc_resolve/src/diagnostics/impls.rs b/compiler/rustc_resolve/src/diagnostics/impls.rs index 331c948c664..29802b0db02 100644 --- a/compiler/rustc_resolve/src/diagnostics/impls.rs +++ b/compiler/rustc_resolve/src/diagnostics/impls.rs @@ -346,9 +346,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { self.lint_buffer.buffer_lint( MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, CRATE_NODE_ID, - span_use, + span_use.0, diagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths { - definition: span_def, + definition: span_def.0, }, ); } @@ -943,11 +943,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let BindingError { name, target, origin, could_be_path } = binding_error; let mut target_sp = target.iter().map(|pat| pat.span).collect::>(); - target_sp.sort(); - target_sp.dedup(); + target_sp.sort_by_key(|sp| sp.lo_hi()); + target_sp.dedup_by_key(|sp| sp.lo_hi()); let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::>(); - origin_sp.sort(); - origin_sp.dedup(); + origin_sp.sort_by_key(|sp| sp.lo_hi()); + origin_sp.dedup_by_key(|sp| sp.lo_hi()); let msp = MultiSpan::from_spans(target_sp.clone()); let mut err = self.dcx().create_err(diagnostics::VariableIsNotBoundInAllPatterns { diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 9faedfeac57..5b6bf203501 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -10,7 +10,7 @@ use rustc_middle::middle::resolve::PartialRes; use rustc_session::diagnostics::feature_err; use rustc_span::edition::Edition; use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext}; -use rustc_span::{Ident, Span, bug, kw, span_bug, sym}; +use rustc_span::{Ident, OrdSpan, Span, bug, kw, span_bug, sym}; use smallvec::SmallVec; use tracing::{debug, instrument}; @@ -1393,7 +1393,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { && let DeclKind::Import { import, .. } = binding.kind && matches!(import.kind, ImportKind::MacroExport) { - self.macro_expanded_macro_export_errors.insert((path_span, binding.span)); + self.macro_expanded_macro_export_errors + .insert((OrdSpan(path_span), OrdSpan(binding.span))); } self.record_use(ident, binding, used); diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index a19207d6fba..718b9e73055 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -20,7 +20,7 @@ use rustc_middle::ty::Visibility; use rustc_session::diagnostics::feature_err; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::LocalExpnId; -use rustc_span::{Ident, Span, Symbol, kw, span_bug, sym}; +use rustc_span::{Ident, OrdSpan, Span, Symbol, kw, span_bug, sym}; use tracing::debug; use crate::Namespace::{self, *}; @@ -1757,7 +1757,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { && !other_binding.is_ambiguity_recursive(); if is_redundant { redundant_span[ns] = - Some((other_binding.span, other_binding.is_import())); + Some((OrdSpan(other_binding.span), other_binding.is_import())); } } Err(_) => is_redundant = false, @@ -1777,7 +1777,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let ident = source; let subs = redundant_spans .into_iter() - .map(|(span, is_imported)| match (span.is_dummy(), is_imported) { + .map(|(OrdSpan(span), is_imported)| match (span.is_dummy(), is_imported) { (false, true) => { diagnostics::RedundantImportSub::ImportedHere { span, ident } } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 3dbb1b7fff6..f39cbc911ed 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -113,7 +113,7 @@ fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, Str } /// Description of an elided lifetime. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug)] pub(super) struct MissingLifetime { /// Used to overwrite the resolution with the suggestion, to avoid cascading errors. pub id: NodeId, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index a9131497336..74ff5e3868e 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -69,7 +69,7 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{self, RegisteredTools, TyCtxt, TyCtxtFeed, Visibility}; use rustc_span::def_id::{LocalModId, ModId}; use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}; -use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug, sym}; +use rustc_span::{DUMMY_SP, Ident, OrdSpan, Span, Symbol, bug, kw, span_bug, sym}; use rustc_structures::CrateType; use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; @@ -1431,7 +1431,7 @@ pub struct Resolver<'ra, 'tcx> { /// Visibility path resolution failures are delayed until all modules are collected. delayed_vis_resolution_errors: Vec> = Vec::new(), /// Crate-local macro expanded `macro_export` referred to by a module-relative path. - macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(), + macro_expanded_macro_export_errors: BTreeSet<(OrdSpan, OrdSpan)> = BTreeSet::new(), arenas: &'ra WorkerLocal>, dummy_decl: Decl<'ra>, diff --git a/compiler/rustc_span/Cargo.toml b/compiler/rustc_span/Cargo.toml index 7889e533153..f8e5e2b48b5 100644 --- a/compiler/rustc_span/Cargo.toml +++ b/compiler/rustc_span/Cargo.toml @@ -7,7 +7,6 @@ edition = "2024" # tidy-alphabetical-start bitflags = "2.4.1" blake3 = "1.5.2" -derive-where = "1.2.7" indexmap = { version = "2.0.0" } itoa = "1.0" md5 = { package = "md-5", version = "0.10.0" } diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 20950c1a5ff..b03c70726f1 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -32,7 +32,6 @@ // this crate without this line making `rustc_span` available. extern crate self as rustc_span; -use derive_where::derive_where; use rustc_data_structures::stable_hash::StableHashCtxt; use rustc_data_structures::{AtomicRef, outline}; use rustc_macros::{Decodable, Encodable, StableHash}; @@ -60,7 +59,7 @@ pub mod def_id; use def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId}; pub mod edit_distance; mod span_encoding; -pub use span_encoding::{DUMMY_SP, Span}; +pub use span_encoding::{DUMMY_SP, OrdSpan, Span}; pub mod symbol; pub use symbol::{ @@ -74,7 +73,6 @@ pub mod profiling; pub mod macros; use std::borrow::Cow; -use std::cmp::{self, Ordering}; use std::fmt::Display; use std::hash::Hash; use std::io::{self, Read}; @@ -82,7 +80,7 @@ use std::ops::{Add, Range, Sub}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; -use std::{fmt, iter}; +use std::{cmp, fmt, iter}; pub use macros::{bug, span_bug}; use md5::{Digest, Md5}; @@ -684,22 +682,20 @@ impl FileName { /// sent to other threads, but some pieces of performance infra run in a separate thread. /// Using `Span` is generally preferred. #[derive(Clone, Copy, Hash, PartialEq, Eq)] -#[derive_where(PartialOrd, Ord)] pub struct SpanData { pub lo: BytePos, pub hi: BytePos, /// Information about where the macro came from, if this piece of /// code was created by a macro expansion. - #[derive_where(skip)] - // `SyntaxContext` does not implement `Ord`. - // The other fields are enough to determine in-file order. pub ctxt: SyntaxContext, - #[derive_where(skip)] - // `LocalDefId` does not implement `Ord`. - // The other fields are enough to determine in-file order. pub parent: Option, } +// `SyntaxContext` and `LocalDefId` aren't orderable. See the equivalent negative impls for `Span` +// for more details. +impl !PartialOrd for SpanData {} +impl !Ord for SpanData {} + impl SpanData { #[inline] pub fn span(&self) -> Span { @@ -740,17 +736,6 @@ impl Default for SpanData { } } -impl PartialOrd for Span { - fn partial_cmp(&self, rhs: &Self) -> Option { - Some(self.cmp(rhs)) - } -} -impl Ord for Span { - fn cmp(&self, rhs: &Self) -> Ordering { - Ord::cmp(&self.data(), &rhs.data()) - } -} - impl Span { #[inline] pub fn lo(self) -> BytePos { @@ -773,6 +758,12 @@ impl Span { self.map_ctxt(|_| ctxt) } + #[inline] + pub fn lo_hi(self) -> (BytePos, BytePos) { + let data = self.data(); + (data.lo, data.hi) + } + #[inline] pub fn is_visible(self, sm: &SourceMap) -> bool { !self.is_dummy() && sm.is_span_accessible(self) diff --git a/compiler/rustc_span/src/span_encoding.rs b/compiler/rustc_span/src/span_encoding.rs index 64280d5ce4b..af6f219b4e5 100644 --- a/compiler/rustc_span/src/span_encoding.rs +++ b/compiler/rustc_span/src/span_encoding.rs @@ -1,3 +1,6 @@ +use std::cmp::Ordering; +use std::hash::Hash; + use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::stable_hash::RawSpan; // This code is very hot and uses lots of arithmetic, avoid overflow checks for performance. @@ -85,6 +88,12 @@ pub struct Span { ctxt_or_parent_or_marker: u16, } +// `SyntaxContext` (`SpanData::ctxt`) and `LocalDefId` (within `SpanData::parent`) aren't orderable. +// If you want to order spans just on `lo`/`hi`, use explicit comparisons involving `Span::lo_hi`. +// Or you can wrap your span within `OrdSpan` which impls `PartialOrd`/`Ord` via `Span::lo_hi`. +impl !PartialOrd for Span {} +impl !Ord for Span {} + // Convenience structures for all span formats. #[derive(Clone, Copy)] struct InlineCtxt { @@ -456,6 +465,38 @@ impl Span { } } +/// Span wrapper that provides equality and ordering based only on the `lo`/`hi` fields. Exists +/// because `Span` doesn't impl `PartialOrd`/`Ord` due to the `ctxt` and `parent` fields being +/// unorderable. Useful when storing things in source code order, e.g. in a `BTreeMap`. +#[derive(Clone, Copy, Debug)] +pub struct OrdSpan(pub Span); + +impl PartialEq for OrdSpan { + fn eq(&self, rhs: &Self) -> bool { + // Ignores `ctxt` and `parent` because they are unorderable. + self.0.lo_hi() == rhs.0.lo_hi() + } +} + +impl Eq for OrdSpan {} + +impl PartialOrd for OrdSpan { + fn partial_cmp(&self, rhs: &Self) -> Option { + Some(self.cmp(rhs)) + } +} + +impl Ord for OrdSpan { + fn cmp(&self, rhs: &Self) -> Ordering { + // Ignores `ctxt` and `parent` because they are unorderable. + self.0.lo_hi().cmp(&rhs.0.lo_hi()) + } +} + +// `OrdSpan` is typically stored in types that rely on ordering, such as `BTreeMap` or `SortedMap`. +// Hashing shouldn't be necessary. +impl !Hash for OrdSpan {} + #[derive(Default)] pub(crate) struct SpanInterner { spans: FxIndexSet, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 166c320cda2..e79a05328f1 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -73,16 +73,17 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { if mention_influencer { spans.push(sup_origin.span()); } - // We dedup the spans *ignoring* expansion context. - spans.sort(); - spans.dedup_by_key(|span| (span.lo(), span.hi())); + // We sort and dedup the spans *ignoring* expansion context. + spans.sort_by_key(|span| span.lo_hi()); + spans.dedup_by_key(|span| span.lo_hi()); // We try to make the output have fewer overlapping spans if possible. let require_span = if sup_origin.span().overlaps(return_sp) { sup_origin.span() } else { return_sp }; let spans_empty = spans.is_empty(); - let require_as_note = spans.iter().any(|sp| sp.overlaps(return_sp) || *sp > return_sp); + let require_as_note = + spans.iter().any(|sp| sp.overlaps(return_sp) || sp.lo_hi() > return_sp.lo_hi()); let bound = if let SubregionOrigin::RelateParamBound(_, _, Some(bound)) = sub_origin { Some(*bound) } else { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index b9f70cea5f5..59ce72eef48 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -210,12 +210,17 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; // sort the errors by span, for better error message stability. - errors.sort_by_key(|u| match *u { - RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(), - RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(), - RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(), - RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(), - RegionResolutionError::CannotNormalize(_, ref sro) => sro.span(), + errors.sort_by_key(|u| { + match *u { + RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(), + RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(), + RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(), + RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => { + rvo.span() + } + RegionResolutionError::CannotNormalize(_, ref sro) => sro.span(), + } + .lo_hi() }); errors } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 2fbfae88918..b55c9acdf5b 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -346,7 +346,7 @@ pub(super) fn build_function(cx: &mut DocContext<'_>, def_id: DefId) -> Box ExpandedCodeVisitor<'ast> { } fn compute_expanded(mut self) -> FxHashMap> { - self.expanded_codes.sort_unstable_by(|item1, item2| item1.span.cmp(&item2.span)); + self.expanded_codes.sort_unstable_by_key(|item| item.span.lo_hi()); let mut expanded: FxHashMap> = FxHashMap::default(); for ExpandedCodeInfo { span, code, original_span, .. } in self.expanded_codes { if let Ok(lines) = self.source_map.span_to_lines(span) diff --git a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs index 93f079f7351..fe0e8c98b46 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs @@ -77,7 +77,7 @@ impl EarlyLintPass for DisallowedScriptIdents { // Sort by `Span` so that error messages make sense with respect to the // order of identifier locations in the code. let mut symbols: Vec<_> = symbols.iter().collect(); - symbols.sort_unstable_by_key(|k| k.1); + symbols.sort_unstable_by_key(|k| k.1.lo_hi()); for &(symbol, &span) in &symbols { // Note: `symbol.as_str()` is an expensive operation, thus should not be called diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 22be9d8367d..a072e3dfff5 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -610,8 +610,8 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> { .any(|(span, _)| self.cx.sess().source_map().is_multiline(*span)); // Suggest removing each argument only once, for example in `format!("{0} {0}", arg)`. - fixes.sort_unstable_by_key(|(span, _)| *span); - fixes.dedup_by_key(|(span, _)| *span); + fixes.sort_unstable_by_key(|(span, _)| span.lo_hi()); + fixes.dedup_by_key(|(span, _)| span.lo_hi()); span_lint_and_then( self.cx, diff --git a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index 02f8170fedc..b511caf6b52 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs @@ -9,7 +9,7 @@ use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass, declare_lint_pass}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{Ty, TypeckResults}; -use rustc_span::Span; +use rustc_span::{OrdSpan, Span}; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::{IntoSpan as _, SpanExt as _, snippet, snippet_with_context}; @@ -94,7 +94,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { format!("{}<{}, S>", target.type_name(), target.type_arguments()), ), ]; - suggestions.extend(vis.suggestions); + suggestions.extend(vis.suggestions.into_iter().map(|(span, s)| (span.0, s))); diag.multipart_suggestion( "add a type parameter for `BuildHasher`", @@ -295,7 +295,7 @@ struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> { cx: &'a LateContext<'tcx>, maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>, target: &'b ImplicitHasherType<'tcx>, - suggestions: BTreeMap, + suggestions: BTreeMap, } impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> { @@ -337,7 +337,7 @@ impl<'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'_, '_, 'tcx> { match method.ident.name { sym::new => { - self.suggestions.insert(e.span, format!("{container_name}::default()")); + self.suggestions.insert(OrdSpan(e.span), format!("{container_name}::default()")); }, sym::with_capacity => { let (arg_snippet, _) = snippet_with_context( @@ -350,7 +350,7 @@ impl<'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'_, '_, 'tcx> { &mut Applicability::MaybeIncorrect, ); self.suggestions.insert( - e.span, + OrdSpan(e.span), format!("{container_name}::with_capacity_and_hasher({arg_snippet}, Default::default())"), ); }, diff --git a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs index 73e430fa08d..8b6c99cc122 100644 --- a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs +++ b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs @@ -1,3 +1,5 @@ +use std::cmp::max_by_key; + use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet; use rustc_errors::{Applicability, SuggestionStyle}; @@ -96,7 +98,9 @@ fn emit_lint( // `<>` needs to be added if there aren't yet any generic arguments or constraints let needs_angle_brackets = bound.args.is_empty() && bound.constraints.is_empty(); let insert_span = match (bound.args, bound.constraints) { - ([.., arg], [.., constraint]) => arg.span().max(constraint.span).shrink_to_hi(), + ([.., arg], [.., constraint]) => { + max_by_key(arg.span(), constraint.span, |span| span.lo_hi()).shrink_to_hi() + } ([.., arg], []) => arg.span().shrink_to_hi(), ([], [.., constraint]) => constraint.span.shrink_to_hi(), ([], []) => bound.span.shrink_to_hi(), diff --git a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs index 8242c383140..82af5d67e6f 100644 --- a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs +++ b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs @@ -7,7 +7,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{Visitor, walk_block, walk_expr, walk_stmt}; use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource}; use rustc_lint::{LateContext, LateLintPass, LintContext as _, impl_lint_pass}; -use rustc_span::{Span, SyntaxContext}; +use rustc_span::{OrdSpan, Span, SyntaxContext}; use std::collections::BTreeMap; use std::collections::btree_map::Entry; @@ -106,7 +106,7 @@ pub struct ExprMetavarsInUnsafe { /// } /// } /// ``` - metavar_expns: BTreeMap, + metavar_expns: BTreeMap, } impl ExprMetavarsInUnsafe { @@ -180,7 +180,7 @@ impl<'tcx> Visitor<'tcx> for BodyVisitor<'_, 'tcx> { } else if ctxt.is_root() && self.expn_depth > 0 { let unsafe_block = self.macro_unsafe_blocks.last().copied(); - match (self.lint.metavar_expns.entry(e.span), unsafe_block) { + match (self.lint.metavar_expns.entry(OrdSpan(e.span)), unsafe_block) { (Entry::Vacant(e), None) => { e.insert(MetavarState::ReferencedInSafe); }, diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 6f06e8665de..9efc3b2edb5 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -6,7 +6,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{self as hir, AmbigArg}; use rustc_lint::{LateContext, LateLintPass, LintContext as _, impl_lint_pass}; -use rustc_span::Span; +use rustc_span::{OrdSpan, Span}; use rustc_span::edition::Edition; use std::collections::BTreeMap; @@ -151,7 +151,7 @@ impl LateLintPass<'_> for MacroUseImports { if !check_dup.contains(&(*item).to_string()) { used.entry(( (*root).to_string(), - span, + OrdSpan(*span), hir_id.local_id, cx.tcx.def_path_hash(hir_id.owner.def_id.into()), )) @@ -175,7 +175,7 @@ impl LateLintPass<'_> for MacroUseImports { .collect::>(); used.entry(( (*root).to_string(), - span, + OrdSpan(*span), hir_id.local_id, cx.tcx.def_path_hash(hir_id.owner.def_id.into()), )) @@ -187,7 +187,7 @@ impl LateLintPass<'_> for MacroUseImports { let rest = rest.to_vec(); used.entry(( (*root).to_string(), - span, + OrdSpan(*span), hir_id.local_id, cx.tcx.def_path_hash(hir_id.owner.def_id.into()), )) @@ -215,11 +215,11 @@ impl LateLintPass<'_> for MacroUseImports { cx, MACRO_USE_IMPORTS, *hir_id, - *span, + span.0, "`macro_use` attributes are no longer needed in the Rust 2018 edition", |diag| { diag.span_suggestion( - *span, + span.0, "remove the attribute and import the macro directly, try", format!("use {import};"), Applicability::MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs index b58ceb263be..7dfe8202a12 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs @@ -187,7 +187,7 @@ impl<'tcx> Visitor<'tcx> for ReferenceVisitor<'_, 'tcx> { // If we haven't found a reference yet, check if this references // one of the locals that was moved in the `unwrap_or` argument. // We are only interested in exprs that appear before the `unwrap_or` call. - if expr.span < self.unwrap_or_span + if expr.span.lo_hi() < self.unwrap_or_span.lo_hi() && let ExprKind::Path(ref path) = expr.kind && let QPath::Resolved(_, path) = path && let Res::Local(local_id) = path.res diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs index edb1c9c53de..c7207bb4dd4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs @@ -373,7 +373,7 @@ fn check_option_fold<'tcx>( // `.iter().fold(` -> `.as_ref().map_or(`, drop the accumulator // parameter, and substitute `init` for each use of the accumulator. - acc_uses.sort(); + acc_uses.sort_by_key(|span| span.lo_hi()); let mut parts = vec![ ( recv.span.with_lo(option_expr.span.hi()).with_hi(init.span.lo()), diff --git a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs index bf649ff5e24..19c3abd2576 100644 --- a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs +++ b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs @@ -122,7 +122,7 @@ impl<'tcx> UnsafeExprCollector<'tcx> { .into_iter() .map(|(span, msg)| (msg, span)) .collect::>(); - unsafe_ops.sort_unstable(); + unsafe_ops.sort_unstable_by_key(|(s, span)| (*s, span.lo_hi())); unsafe_ops } diff --git a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs index 968f6ad679b..47708e8f02d 100644 --- a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs +++ b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs @@ -111,7 +111,7 @@ fn check_op(cx: &LateContext<'_>, outer: &Expr<'_>, expr: &Expr<'_>, other: &Exp } else { let span = expr.span.to(other.span); - let cmp_span = if other.span < expr.span { + let cmp_span = if other.span.lo_hi() < expr.span.lo_hi() { other.span.between(expr.span) } else { expr.span.between(other.span) diff --git a/src/tools/clippy/clippy_lints/src/useless_vec.rs b/src/tools/clippy/clippy_lints/src/useless_vec.rs index 3d2f47cee46..0b526010d2c 100644 --- a/src/tools/clippy/clippy_lints/src/useless_vec.rs +++ b/src/tools/clippy/clippy_lints/src/useless_vec.rs @@ -16,7 +16,7 @@ use rustc_hir::{BorrowKind, Expr, ExprKind, HirId, LetStmt, Mutability, Node, Pa use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; use rustc_middle::ty; use rustc_middle::ty::layout::LayoutOf as _; -use rustc_span::{DesugaringKind, Span}; +use rustc_span::{DesugaringKind, OrdSpan, Span}; pub struct UselessVec { too_large_for_stack: u64, @@ -41,7 +41,7 @@ pub struct UselessVec { /// the first `vec![1, 2]` (which is shared with the other expn) to an array which indeed would /// work, we get a false positive warning on the `$v.push(3)` which really requires `$v` to /// be a vector. - span_to_state: BTreeMap, + span_to_state: BTreeMap, allow_in_test: bool, } @@ -223,7 +223,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { }, }; - if let Entry::Vacant(entry) = self.span_to_state.entry(vec_span) { + if let Entry::Vacant(entry) = self.span_to_state.entry(OrdSpan(vec_span)) { entry.insert(VecState::Change { suggest_ty, vec_snippet, @@ -232,7 +232,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { } }, VecToArray::Impossible => { - self.span_to_state.insert(vec_span, VecState::NoChange); + self.span_to_state.insert(OrdSpan(vec_span), VecState::NoChange); }, } } @@ -246,6 +246,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { expr_hir_id, } = state { + let span = span.0; span_lint_hir_and_then(cx, USELESS_VEC, expr_hir_id, span, "useless use of `vec!`", |diag| { let help_msg = format!("you can use {} directly", suggest_ty.desc()); // If the `vec!` macro contains comment, better not make the suggestion machine applicable as it diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 25c659f7b3a..5587fbbcaed 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -171,15 +171,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Make sure we are consistent wrt what is 'first' and 'second'. let original_span = - tcx.def_span(original.instance.def_id()).data(); - let span = tcx.def_span(def_id).data(); - if original_span < span { + tcx.def_span(original.instance.def_id()); + let span = tcx.def_span(def_id); + if original_span.lo_hi() < span.lo_hi() { throw_machine_stop!( TerminationInfo::MultipleSymbolDefinitions { link_name, - first: original_span, + first: original_span.data(), first_crate: tcx.crate_name(original.cnum), - second: span, + second: span.data(), second_crate: tcx.crate_name(cnum), } ); @@ -187,9 +187,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { throw_machine_stop!( TerminationInfo::MultipleSymbolDefinitions { link_name, - first: span, + first: span.data(), first_crate: tcx.crate_name(cnum), - second: original_span, + second: original_span.data(), second_crate: tcx.crate_name(original.cnum), } );